From f514cb9a7dfcc1a22d3d5a05ff3a8057cfdcb83a Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 19 Oct 2026 00:16:00 +0300 Subject: [PATCH] Cut shadowed textures' copies to what their commands touch, merge back every buffer another writer may write, and count copies by cause A texture over a buffer's bytes or another image whose own image is a shadow now copies in, keeps, merges and copies back only the texels its commands reach, with fewer barriers, descriptor pools and scratch fills, and merges its writes back wherever another writer may write the bytes during the run. What changes: - Which shadows merge. A shadow merges back (kept before the first command that writes through it, only the words its commands changed reaching the bytes) over every buffer's bytes but a tracked Private or Memoryless buffer the runtime made: Shared buffers and host pages as before, and now Managed buffers (on unified memory the CPU writes the GPU's memory, and without it a later upload may run on another queue) and untracked buffers another queue may write. A tracked Private buffer's shadow, a command replacing every texel, an image's shadow, and turned and two-plane textures still copy back. A merge goes in place wherever the texture's first and last words lie in the buffer and the bytes lie in pages; only a first byte inside a word, a staging buffer or a last word past the buffer still merges through a copy, a new FAST-PATHS known gap since that round trip can undo another writer's write between its copies. - Correct merges. A command that replaces every texel followed by one that writes part of it is copied back before the keep, so the merge carries the later writes. A merge of a part leaves a twin stale there alone. A detached buffer's shadow binds no stand-in (the null handle while detached), so no merge binds a range past a 256-byte stand-in. - Cut copies. A read inside a rectangle keeps the rest of the changed rectangle for the next read; an image's one-level, one-slice shadow cuts its copies in as a buffer texture's do; a keep and merge are cut to the rectangle the encoder's commands write in, in bands within the device's limits; a loaded shadowed colour's copies are cut to its draws' scissors also in passes that clear another attachment or take a reach clear (Vulkan's scissor test leaves coverage outside at 0). - Cheaper copies. On ANV (DriverFact::ShadowCopyBackDispatchFaster, now every ANV device measured) a merge's keep and changed copy are the copy back's dispatch, and a cut merge reads the changed texels straight from the shadow's integer view (bind::shadow_merge_image_module), with no copy after the commands. On the UHD 770 (new DriverFact::ShadowCopyInDispatchFaster) a merged shadow's copy in and its keep are one dispatch (bind::shadow_copy_in_module), its 4-byte view R8G8B8A8_UINT because ANV drops a storage image's compression for an R32 view. The shadow kernels take a bind::ShadowTexelView. A cut merge's scratch is kept for the next merges and not zeroed. The shadow kernels and a linear attachment's merge push their descriptors where the device pushes set 0, so a shadowed pass makes no descriptor pool. A run of shadow copies in an unordered encoder shares one barrier before and one after, keeping a barrier only between copies that touch the same memory and one writes. - Counters (WorkCounts): every copy in by why it is made and by what holds the texture's truth, first copies apart (shadow_texels_first_copied_in_*, shadow_texels_recopied_*, shadow_texels_copied_in_images, shadow_texels_bounded_copied_in), shadow_texels_kept, shadow_merge_copies_dispatched, shadow_merges_fetched, shadow_copies_in_dispatched, shadow_merge_scratches_reused and _zeroed, owned_descriptor_pools, how passes take shadowed colours (shadow_attachment_loads_*, _clears, _clears_in_part), shadows_sharing_truth, and the tiles a loaded colour's scissors cover against their bounds. - Docs: shadow.rs and shadow_merge.rs module rules, API.md's shadow entries, FAST-PATHS' costs of matching Metal and known gaps; the snapshot rule's figure is now an upper bound. Why: Metal writes only the texels a command writes, and another writer may write bytes no command touches during a run. On an M3 Max under macOS 27.0.1, a fill of an untracked Private buffer from a second queue ran inside a first queue's kernel or render pass 5 times of 6 and both texels kept their writes, as did a CPU write to a Managed buffer; a tracked Private buffer's fill always ran after. And in the consumer's Finder drag on the Iris Xe, whole 1080p shadow copies were most of the composite command buffers' GPU time. Verified: - Iris Xe, four shadowed textures a frame over anonymous pages, commit to completion: merged passes that draw 11.7-11.8 ms -> 5.0-5.4 ms and scissored ones 11.3-11.4 -> 3.6-3.9 ms across the dispatched copies, cut keeps and fetched merges; a 1080p Load pass's GPU time 4572 -> 3484 us with the fetched merge. - UHD 770: a 1080p Load/Store pass 2390 -> 1683 us GPU with the fetched merge; a 1080p Load pass 1.64-1.67 -> 1.43 ms with the fused copy in; the kept scratch took a 1080p Load pass 4205-4755 -> 2626-3595 us commit to completion (RX 7900 XTX 4112-4392 -> 1628-1697 us). Shared barriers saved about 0.65 us of GPU time per barrier removed on the Iris Xe (680 -> 120 barriers a frame). - runtime_lane::pitched_surfaces 28 of 28 on the UHD 770, Iris Xe, Radeon 780M, RX 7900 XTX and lavapipe, with merges under changing scissors, split instances and two textures over one buffer matching a private texture's bytes; under synchronization validation with no message. The shadow lanes 123 to 132 of 123 to 132 on the M3 Max, lavapipe, Iris Xe and RADV; extended_range_blends, linear_attachments and padded_loads on the RTX 5080 with no validation message. - Unit tests: tests::shadow (24), clear_reach, owned_pushes, shadow kernels through all four views on the CPU interpreter, driver_facts. clippy -D warnings (plain, m2v_gpu, m2v_cpu_icd), rustdoc. --- crates/metal2vulkan-runtime/src/buffer.rs | 30 +- .../src/buffer_texture.rs | 49 +- .../metal2vulkan-runtime/src/clear_reach.rs | 74 ++ .../src/command_buffer/mod.rs | 18 + .../metal2vulkan-runtime/src/degradation.rs | 7 +- crates/metal2vulkan-runtime/src/encoder.rs | 277 +++++- crates/metal2vulkan-runtime/src/lib.rs | 1 + .../metal2vulkan-runtime/src/linear_merge.rs | 47 +- .../metal2vulkan-runtime/src/owned_kernel.rs | 201 +++- crates/metal2vulkan-runtime/src/render.rs | 16 +- .../src/render/inline_splits.rs | 6 +- .../src/render/shadows.rs | 164 +++- .../src/render/snapshot.rs | 9 +- crates/metal2vulkan-runtime/src/row_copies.rs | 11 + crates/metal2vulkan-runtime/src/shadow.rs | 651 +++++++++++-- .../src/shadow_copy_back.rs | 124 ++- .../src/shadow_copy_in.rs | 150 +++ .../metal2vulkan-runtime/src/shadow_merge.rs | 786 ++++++++++++--- .../src/tests/blit_holds.rs | 10 + crates/metal2vulkan-runtime/src/tests/mod.rs | 2 + .../src/tests/owned_pushes.rs | 38 + .../metal2vulkan-runtime/src/tests/shadow.rs | 916 +++++++++++++++--- .../src/tests/shadow_host_writes.rs | 29 + crates/metal2vulkan-runtime/src/texture.rs | 16 +- .../src/texture/attached_reads.rs | 20 +- .../metal2vulkan-runtime/src/texture/heap.rs | 9 +- .../src/texture/surface_depth.rs | 3 + .../src/texture/surface_two_planes.rs | 3 + .../src/texture/usage_shadow.rs | 6 +- .../src/texture/view_shadow.rs | 5 +- .../src/texture/ycbcr_image.rs | 7 + .../metal2vulkan-runtime/src/work_counts.rs | 456 ++++++++- .../src/runtime_lane.rs | 2 + .../src/runtime_lane/attachment_read_costs.rs | 210 ++++ .../src/runtime_lane/attachment_reads.rs | 102 +- .../src/runtime_lane/detach_textures.rs | 4 - .../src/runtime_lane/guest_frame_costs.rs | 3 + .../src/runtime_lane/no_copy_textures.rs | 42 +- .../src/runtime_lane/pitched_surfaces.rs | 699 +++++++++++-- .../src/runtime_lane/surface_texture_costs.rs | 90 +- .../src/runtime_lane/tile_edges.rs | 110 ++- crates/metal2vulkan/src/bind/mod.rs | 13 +- .../metal2vulkan/src/bind/shadow_copy_back.rs | 221 +++-- .../metal2vulkan/src/bind/shadow_copy_in.rs | 438 +++++++++ crates/metal2vulkan/src/bind/shadow_merge.rs | 57 +- .../src/bind/shadow_merge_image.rs | 384 ++++++++ .../metal2vulkan/src/device/driver_facts.rs | 53 +- .../src/device/tests/driver_facts.rs | 6 +- .../metal2vulkan/src/tests/owned_divisions.rs | 14 +- crates/metal2vulkan/tests/api_surface.rs | 5 + docs/API.md | 29 +- docs/FAST-PATHS.md | 57 +- 52 files changed, 5862 insertions(+), 818 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/row_copies.rs create mode 100644 crates/metal2vulkan-runtime/src/shadow_copy_in.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/owned_pushes.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/shadow_host_writes.rs create mode 100644 crates/metal2vulkan-validation/src/runtime_lane/attachment_read_costs.rs create mode 100644 crates/metal2vulkan-validation/src/runtime_lane/guest_frame_costs.rs create mode 100644 crates/metal2vulkan/src/bind/shadow_copy_in.rs create mode 100644 crates/metal2vulkan/src/bind/shadow_merge_image.rs diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 31eef3b6f..6d57d3d92 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -1130,6 +1130,15 @@ impl OwnBytes { } } + /// [`with`](Self::with) while the buffer lies in pages: `None` while it is detached. + match &self.lie { + Lie::Fixed(fixed) => Some(f(&fixed.pages)), + Lie::Host(cell) => match cell.lying() { + Lying::Detached(_) => None, + }, + } + } + /// Where the bytes lie in the pages the buffer lies in now ([`Shape`]), read without their /// `VkBuffer`. fn shape(&self) -> Shape { @@ -1531,11 +1540,21 @@ impl Device { /// it with the exit guard's entry points alone (`exit_guard`). Refused as /// [`Device::new_buffer`] refuses its length. pub(super) fn scratch_buffer(&self, length: u64) -> Result { + self.unzeroed_buffer(length, HazardTrackingMode::Untracked) + } + + /// [`scratch_buffer`](Device::scratch_buffer) of hazard tracking `tracking`: the tracker + /// orders its uses as any buffer's of that mode. + pub(super) fn unzeroed_buffer( + &self, + length: u64, + tracking: HazardTrackingMode, + ) -> Result { const CALL: &str = "new_buffer"; let modes = Modes::of(ResourceOptions::new( StorageMode::Private, CpuCacheMode::DefaultCache, - HazardTrackingMode::Untracked, + tracking, ))?; let class = buffer_class(CALL, modes)?; if length == 0 || length > self.properties().max_buffer_length { @@ -2186,8 +2205,13 @@ impl Buffer { /// a no-copy buffer's ([`Buffer::base`]), and a heap buffer's, which is its heap's. pub(super) fn at(&self, offset: u64) -> (vk::Buffer, u64) { match &self.0.bytes { - Bytes::Own(own) => own.with(|pages| (pages.raw, pages.base + offset)), - Bytes::Heap(bytes) => bytes.bytes.at(bytes.offset + offset), + + /// [`Buffer::at`] while the buffer's bytes lie in pages, read with them at once: `None` while + /// they are detached (`detach.rs`), when its `VkBuffer` is the device's stand-in, which holds + /// none of its bytes. + pub(super) fn attached_at(&self, offset: u64) -> Option<(vk::Buffer, u64)> { + match &self.0.bytes { + Bytes::Heap(bytes) => bytes.bytes.attached_at(bytes.offset + offset), } } diff --git a/crates/metal2vulkan-runtime/src/buffer_texture.rs b/crates/metal2vulkan-runtime/src/buffer_texture.rs index e96fd2817..eefdb1fdd 100644 --- a/crates/metal2vulkan-runtime/src/buffer_texture.rs +++ b/crates/metal2vulkan-runtime/src/buffer_texture.rs @@ -39,8 +39,11 @@ use super::linear_plan::{ }; use super::resource::{Identity, ResourceKey}; use super::rotated::{self, Frame, RotatedCopies}; -use super::shadow::{ShadowBuffer, ShadowCopies, ShadowSource, ShadowStaging, ShadowTarget}; +use super::shadow::{ + Backing, ShadowBuffer, ShadowCopies, ShadowSource, ShadowStaging, ShadowTarget, +}; use super::shadow_copy_back::WordView; +use super::shadow_merge::ScratchSpares; use super::texture::surface_two_planes; use super::texture::{IdUse, Texture}; use super::texture_descriptor::{ @@ -102,6 +105,8 @@ pub(super) struct Texels { /// The texture objects over the texels as a texture buffer's (`Storage::Texels`), and the /// caller's token for a texture buffer's range (`Device::new_texture_with_range_token`). pub(super) objects: ObjectsToken, + /// The texels lie in an IOSurface's plane (`Buffer::new_texture_with_iosurface_plane`). + surface: bool, } /// A texture's texel buffer views, by format, kind (storage or uniform) and range; destroyed @@ -636,7 +641,7 @@ impl Buffer { let id_use = IdUse::Program(descriptor.placement); return self.device().new_rotated_texture( call, - [rows, stored].map(|texels| texels.with_options(options)), + [rows, stored].map(|texels| texels.with_options(options).over_surface(surface)), descriptor, (&layout, rotation), id_use, @@ -648,16 +653,18 @@ impl Buffer { return Err(Error::DeviceLost); } if let Some(alpha) = alpha_plane { - let texels = - Texels::placed(self.clone(), placed, texel_bytes, descriptor).with_options(options); + let texels = Texels::placed(self.clone(), placed, texel_bytes, descriptor) + .with_options(options) + .over_surface(surface); let id_use = IdUse::Program(descriptor.placement); return self .device() .new_surface_planes_texture(call, texels, descriptor, &layout, id_use, alpha); } if let Some((planes, span)) = converted { - let texels = - Texels::placed(self.clone(), placed, texel_bytes, descriptor).with_options(options); + let texels = Texels::placed(self.clone(), placed, texel_bytes, descriptor) + .with_options(options) + .over_surface(surface); let id_use = IdUse::Program(descriptor.placement); return self.device().new_converted_texture( call, @@ -672,8 +679,9 @@ impl Buffer { let texels = Texels::texture_buffer(self.clone(), placed.gpu, texel_bytes, descriptor)?; Ok(texels.texture(descriptor, &layout, IdUse::Program(descriptor.placement))) } else { - let texels = - Texels::placed(self.clone(), placed, texel_bytes, descriptor).with_options(options); + let texels = Texels::placed(self.clone(), placed, texel_bytes, descriptor) + .with_options(options) + .over_surface(surface); let id_use = IdUse::Program(descriptor.placement); let texture = self .device() @@ -810,7 +818,8 @@ impl Texture { texels.texel_bytes, &descriptor, ) - .with_options(texels.options); + .with_options(texels.options) + .over_surface(texels.surface); device.new_texture_over_buffer(CALL, over, &descriptor, &layout, IdUse::Runtime) }) } @@ -909,6 +918,7 @@ impl Texels { }; Texels::new(self.buffer.clone(), layout, self.texel_bytes, &descriptor) .with_options(self.options) + .over_surface(self.surface) } /// These texels' buffer's bytes `span` as one row of `unit`-byte texels, of these texels' @@ -928,7 +938,9 @@ impl Texels { allow_gpu_optimized_contents: self.allow_gpu_optimized_contents, ..TextureDescriptor::default() }; - Texels::new(self.buffer.clone(), layout, unit, &descriptor).with_options(self.options) + Texels::new(self.buffer.clone(), layout, unit, &descriptor) + .with_options(self.options) + .over_surface(self.surface) } /// The attachment twin of `pixel_format` kept with the texels (a texture buffer's, or a @@ -999,6 +1011,8 @@ impl Texels { }, tracked: self.tracked(), drops_writes: false, + backing: self.backing(), + merge_scratch: ScratchSpares::default(), }) } @@ -1025,6 +1039,11 @@ impl Texels { Texels { options, ..self } } + /// These texels, in an IOSurface's plane where `surface`. + fn over_surface(self, surface: bool) -> Texels { + Texels { surface, ..self } + } + /// Every byte of the buffer the texels lie in, for the GPU or the CPU: from the first to the /// last of either layout, and of the alpha plane where the texels have one. pub(super) fn span(&self) -> std::ops::Range { @@ -1075,10 +1094,16 @@ impl Texels { twins: Mutex::new(HashMap::new()), alpha: None, objects: ObjectsToken::default(), + surface: false, buffer, } } + /// What holds the texels' bytes, as the CPU may write them (`shadow::Backing`). + pub(super) fn backing(&self) -> Backing { + Backing::of(&self.buffer, self.surface) + } + /// Where the CPU's `replace_region` and `get_bytes` find the texels. pub(super) fn cpu_layout(&self) -> BufferLayout { self.cpu @@ -1142,6 +1167,8 @@ impl Texels { shadow_range, tracked: texels.tracked(), drops_writes: false, + backing: texels.backing(), + merge_scratch: ScratchSpares::default(), }; texels.staged = Some(Arc::new(copies)); let (offset, alignment) = ( @@ -1267,6 +1294,8 @@ impl Texels { }, tracked: self.tracked(), drops_writes: false, + backing: self.backing(), + merge_scratch: ScratchSpares::default(), }) } diff --git a/crates/metal2vulkan-runtime/src/clear_reach.rs b/crates/metal2vulkan-runtime/src/clear_reach.rs index 7c0b1c473..579dbc64e 100644 --- a/crates/metal2vulkan-runtime/src/clear_reach.rs +++ b/crates/metal2vulkan-runtime/src/clear_reach.rs @@ -280,6 +280,10 @@ impl DontCareLoads { /// The most distinct pixel rectangles [`DrawnArea`] keeps; past them it is the whole render area. const MOST_RECTS: usize = 1024; +/// The words of a row of tiles in [`DrawnArea::covered_tiles`]: 512 tiles, the 16384 pixels of +/// the widest render area. +const ROW_WORDS: usize = 8; + /// The pixels a pass's draws may write, as far as the host bounds them: each draw that draws /// writes only inside its viewports' pixels within their scissor rectangles /// (`EncoderState::vk_scissors`), so a tile none of those reaches is one Metal's draws do not, @@ -372,6 +376,40 @@ impl DrawnArea { }) } + /// Of the tiles of [`TILE`] pixels a side, from the render area's origin, that + /// [`bounds`](Self::bounds) reaches, how many its rectangles reach, and how many it reaches: + /// `None` where it bounds nothing. A count (`WorkCounts::shadow_attachment_tiles_covered`): + /// what a copy cut to the rectangles' tiles would leave out of one cut to their bounds. + pub(super) fn covered_tiles(&self) -> Option<(u64, u64)> { + let [x0, y0, x1, y1] = self.bounds()?; + let (tx0, ty0) = (x0 / TILE, y0 / TILE); + let (tx1, ty1) = (x1.div_ceil(TILE), y1.div_ceil(TILE)); + let bounded = u64::from(tx1 - tx0) * u64::from(ty1 - ty0); + // A row of tiles in the bits of `ROW_WORDS` words; a wider one, which no render area + // has, counts as covered. + if (tx1 - tx0) as usize > ROW_WORDS * 64 { + return Some((bounded, bounded)); + } + let mut covered = 0; + for ty in ty0..ty1 { + let (top, bottom) = (ty * TILE, (ty + 1) * TILE); + let mut row = [0u64; ROW_WORDS]; + for &[rx0, ry0, rx1, ry1] in self.rects.iter() { + if rx0 >= rx1 || ry0 >= ry1 || ry0 >= bottom || ry1 <= top { + continue; + } + for tile in rx0 / TILE - tx0..rx1.div_ceil(TILE) - tx0 { + row[(tile / 64) as usize] |= 1 << (tile % 64); + } + } + covered += row + .iter() + .map(|word| u64::from(word.count_ones())) + .sum::(); + } + Some((covered, bounded)) + } + /// Add `other`'s rectangles: anywhere where it bounds nothing. pub(super) fn join(&mut self, other: &DrawnArea) { if other.whole { @@ -805,6 +843,42 @@ mod tests { } } + /// The tiles the rectangles cover, against those their bounding rectangle reaches, are + /// counted in 32-pixel tiles from the origin: two rectangles far apart cover their own + /// tiles alone, where their bounds reach every tile between them. + #[test] + fn covered_tiles_count_the_rectangles_tiles_against_their_bounds() { + let rect = |x: i32, y: i32, w: u32, h: u32| vk::Rect2D { + offset: vk::Offset2D { x, y }, + extent: vk::Extent2D { + width: w, + height: h, + }, + }; + let cases: [(Vec, Option<(u64, u64)>); 6] = [ + (vec![], None), + // A 1920x1080 render area's every tile: 60 by 34. + (vec![rect(0, 0, 1920, 1080)], Some((2040, 2040))), + // Off the grid: tiles 0 to 2 by 0 to 1. + (vec![rect(31, 1, 34, 32)], Some((6, 6))), + // Two corners at either end of a 1920x1080 area, four tiles each. + ( + vec![rect(0, 0, 64, 64), rect(1856, 1024, 64, 56)], + Some((8, 2040)), + ), + // Overlapping rectangles count each tile once. + (vec![rect(0, 0, 96, 32), rect(32, 0, 96, 32)], Some((4, 4))), + // An L: the bounds reach the corner the rectangles leave out. + (vec![rect(0, 0, 64, 32), rect(0, 32, 32, 32)], Some((3, 4))), + ]; + for (case, (rects, expected)) in cases.iter().enumerate() { + let mut area = DrawnArea::default(); + area.add(rects); + assert_eq!(area.covered_tiles(), *expected, "case {case}"); + } + assert_eq!(DrawnArea::unbounded().covered_tiles(), None); + } + /// The tiles a pass's rectangles reach are the tiles each overlaps, whether one of them /// reaches every tile (no grid made) or none does: checked tile by tile. #[test] diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index b2c61e377..29ae715a9 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -473,6 +473,8 @@ pub(super) struct State { /// state made without `supportIndirectCommandBuffers`): as it commits, they run nothing, and /// it completes with `CommandBufferError::PageFault`. faulted: BTreeSet, + /// The shadowed textures its ended encoders copied in first (`shadow.rs`), each once. + shadows_copied_in: Vec, /// The pools of its commands' set 0 (`descriptor_arena.rs`), given back or released with /// the uploads. pub(super) descriptors: DescriptorArena, @@ -959,6 +961,21 @@ impl State { self.fails_from.get_or_insert((encoder, error)); } + /// Note the shadowed textures an ended encoder copied in first, each copy's texture and + /// texels: the texels of those an earlier encoder of the command buffer copied in too. + pub(super) fn shadows_copied_in(&mut self, copies: &[(ResourceKey, u64)]) -> u64 { + let earlier = self.shadows_copied_in.len(); + let mut again = 0; + for &(key, texels) in copies { + if self.shadows_copied_in[..earlier].contains(&key) { + again += texels; + } else if !self.shadows_copied_in.contains(&key) { + self.shadows_copied_in.push(key); + } + } + again + } + /// Metal's GPU faults ended encoder `encoder` (`faulted`). pub(super) fn fault(&mut self, encoder: usize) { self.faulted.insert(encoder); @@ -1340,6 +1357,7 @@ impl CommandBuffer { unlisted_argument_samplers: false, fails_from: None, faulted: BTreeSet::new(), + shadows_copied_in: Vec::new(), descriptors: DescriptorArena::default(), status_words: None, capture_tallies: Vec::new(), diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 6c3ec44c3..47eaab504 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -258,7 +258,8 @@ degradations! { /// host pages: its image is a shadow of its elements tiled in the heap's bytes, where Metal /// lays them out. ShadowedTexture = "shadowed-texture", Performance, - "its texels are copied into an image before each use and back after each write"; + (over a buffer's bytes but a tracked private buffer's, kept before a write and merged \ + back after it)"; /// A texture buffer is viewed through a staging buffer: its texels start where the /// device views none (`minTexelBufferOffsetAlignment`). StagedTextureBuffer = "staged-texture-buffer", Performance, @@ -267,9 +268,7 @@ degradations! { /// One command writes a buffer's bytes through a shadowed texture or a staged texture /// buffer and also another way (`shadow_merge.rs`). ShadowMerge = "shadow-merge", Performance, - "the shadow's texels are kept in a scratch buffer of three times the texture's bytes \ - before the command, and after it a dispatch merges the bytes it changed through the \ - texture into the buffer's: three copies and a dispatch in place of one copy back"; + "the shadow's texels are kept in a scratch buffer of one to three times the texture's \ /// A draw's index buffer or indirect arguments start where Vulkan reads neither. CopiedDrawBytes = "copied-draw-bytes", Performance, "they are copied into a buffer of the command buffer before the pass, and the draw \ diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index a69feb95b..6e6ed43fe 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -41,7 +41,8 @@ use super::replay::Replay; use super::residency::Residency; use super::resource::ResourceKey; use super::retained::Retained; -use super::shadow::{ShadowCopy, ShadowSync, ShadowUse, Step, Within}; +use super::shadow::{CopyCause, ShadowCopy, ShadowSync, ShadowUse, Step, Within}; +use super::shadow_copy_in::CopyIn; use super::shadow_merge::ShadowMerge; use super::sparse::encoder::SparseUpdate; use super::texture::decoded_twin::TwinWrite; @@ -207,6 +208,9 @@ pub(super) struct EncoderCore { /// open, so a use at that place of the same key, named only where that one was, is kept and /// named already. touched: Vec<(ResourceKey, bool)>, + /// Its first copies in of shadowed textures, each copy's texture and texels: `end` notes them + /// in the command buffer (`WorkCounts::shadow_texels_first_copied_in_again`). + first_copies: Vec<(ResourceKey, u64)>, /// The heaps its commands used through what the encoder made resident; `end` hands them, /// and those of `keys`, to the command buffer, whose commit marks them used. heaps: Vec, @@ -321,6 +325,7 @@ impl EncoderCore { shadows: ShadowSync::default(), keys: BTreeSet::new(), touched: Vec::new(), + first_copies: Vec::new(), heaps: Vec::new(), holds: Holds::new(command_buffer.device()), taken: Taken::default(), @@ -396,6 +401,7 @@ impl EncoderCore { shadows: ShadowSync::default(), keys: BTreeSet::new(), touched: Vec::new(), + first_copies: Vec::new(), heaps: Vec::new(), holds: Holds::new(command_buffer.device()), taken: Taken::default(), @@ -962,30 +968,63 @@ impl EncoderCore { let device = self.device().clone(); let aliased = self.aliased(uses); let uses = aliased.as_deref().unwrap_or(uses); - let copies = self.shadows.before(shadows, uses, |copies| { - ShadowMerge::new(&device, copies).map(Arc::new) - })?; + .shadows + .before(shadows, uses, |copies, two_ways, area| { self.count_shadow_copies(&copies); for copy in &copies { if let Step::Keep(merge) = ©.step { self.retain(Arc::clone(merge)); } + if copy.cause == Some(CopyCause::First) { + (self.first_copies).push((copy.copies.shadow_key, copy.texels_copied_in())); + } } Ok(copies) } /// Count shadowed textures' `copies` as planned (`WorkCounts::shadow_copies`), the texels - /// their copies in and back of buffers' textures' images move, and those copies in of what - /// changed within a rectangle alone (`WorkCounts::bounded_shadow_copies`). + /// their copies in and back of buffers' textures' images move, each copy in's texels by why + /// it is made and what holds its truth (`WorkCounts::shadow_texels_first_copied_in` and kin), + /// those copies in of what changed within a rectangle alone + /// (`WorkCounts::bounded_shadow_copies`), and the keeps and merges whose copies of the shadow + /// into the scratch dispatch (`WorkCounts::shadow_merge_copies_dispatched`), and the texels the + /// keeps copy (`WorkCounts::shadow_texels_kept`). fn count_shadow_copies(&self, copies: &[ShadowCopy]) { let texels_in = copies.iter().map(ShadowCopy::texels_in).sum(); let texels_back = copies.iter().map(ShadowCopy::texels_back).sum(); let counts = &self.device().shared().counts; counts.shadow_copies_planned(copies.len(), texels_in, texels_back); - let bounded = copies.iter().filter(|copy| copy.bounded).count(); + for copy in copies { + counts.shadow_copy_in_planned(copy); + } + let bounded = (copies.iter()) + .filter(|copy| copy.cause == Some(CopyCause::Bounded)) + .count(); if bounded > 0 { counts.bounded_shadow_copies_planned(bounded); } + let dispatched = copies + .iter() + .filter(|copy| match ©.step { + Step::Keep(merge) => merge.dispatches(), + Step::Merge(merge) => merge.changed_dispatches(), + Step::Into | Step::Back => false, + }) + .count(); + if dispatched > 0 { + counts.shadow_merge_copies_dispatched(dispatched); + } + let kept: u64 = copies + .iter() + .filter_map(|copy| match ©.step { + Step::Keep(merge) => Some(merge.texels_kept()), + _ => None, + }) + .sum(); + if kept > 0 { + counts.shadow_texels_kept(kept); + } + } } /// Note a recorded command that used the shadowed textures `shadows` and had `uses`, and @@ -1013,13 +1052,37 @@ impl EncoderCore { } /// Record shadowed textures' `copies` as commands of the encoder: ordered as any command - /// is, in an encoder Metal orders; with a barrier from everything before and one to - /// everything after each copy, in one whose commands Metal leaves unordered. A copy back the - /// device runs faster as a dispatch is that dispatch (`shadow_copy_back.rs`), which the - /// command buffer retains until it completes. + /// is, in an encoder Metal orders; in one whose commands Metal leaves unordered, as one run + /// ([`ShadowRun`]) between a barrier from everything before its first copy and one to + /// everything after its last. A copy back the device runs faster as a dispatch is that + /// dispatch (`shadow_copy_back.rs`), a merged texture's copy in and its keep are one dispatch + /// at the copy in where the device takes it (`shadow_copy_in.rs`), and the rows a copy back + /// moves out of a staging buffer are a copy of rows (`row_copies.rs`); the command buffer + /// retains each until it completes. pub(super) fn shadow_copies(&mut self, copies: &[ShadowCopy]) { let device = self.device().clone(); - for copy in copies { + let mut run = ShadowRun::default(); + // The keeps a dispatch at their copy in took, which record nothing. + let mut taken = Vec::new(); + for (i, copy) in copies.iter().enumerate() { + if taken.contains(&i) { + continue; + } + if let Some((keep, both, uses)) = keep_with_copy_in(&device, copies, i) { + taken.push(keep); + let record = |device: &Vk, raw: vk::CommandBuffer| { + // SAFETY: the encoder's command buffer is recording outside a render pass; + // its commands retain the shadowed texture (and its view), the merge's scratch + // and the dispatch until it completes, and every image rests in the `GENERAL` + // layout. + unsafe { both.record(device, raw) } + }; + let stages = vk::PipelineStageFlags2::COMPUTE_SHADER; + self.shadow_command(&mut run, (stages, &uses, false), record); + device.shared().counts.shadow_copy_in_dispatched(); + self.retain(both); + continue; + } // A shadow takes the view a dispatch reads on a device that dispatches alone. let dispatched = copy.dispatched(&device); let (stages, uses) = match &dispatched { @@ -1037,31 +1100,47 @@ impl EncoderCore { // SAFETY: as above. None => unsafe { copy.record(device, raw) }, }; - if self.uses.ordered() { - self.command(stages, &uses, record); - } else { - // A copy of a detached buffer's bytes records nothing, nor does what follows. - if self.skips(uses.iter().map(|used| used.key)) { - continue; - } - self.barrier(Barrier::everything()); - let Some(raw) = self.recording() else { - continue; - }; - record(device.shared().vk(), raw); - self.barrier(Barrier::everything()); - let aliased = self.aliased(&uses); - self.uses - .record(stages, aliased.as_deref().unwrap_or(&uses), None); - self.touch(&uses); - } + self.shadow_command(&mut run, (stages, &uses, copy.writes_truth()), record); if let Some(back) = dispatched { device.shared().counts.shadow_copy_back_dispatched(); self.retain(back); } + if run.recorded() { + self.barrier(Barrier::everything()); } } + /// Record one shadowed texture's copy, of `uses` in `stages`, writing its truth where + /// `writes_truth`, by `record`: as any command in an encoder Metal orders, else in `run`, + /// after a barrier from everything before where the run takes one ([`ShadowRun::before`]). + /// A copy of a detached buffer's bytes records nothing, nor does what follows + /// ([`skips`](Self::skips)). + fn shadow_command( + &mut self, + run: &mut ShadowRun, + (stages, uses, writes_truth): (vk::PipelineStageFlags2, &[Use], bool), + record: impl FnOnce(&Vk, vk::CommandBuffer), + ) { + if self.uses.ordered() { + self.command(stages, uses, record); + return; + } + if self.skips(uses.iter().map(|used| used.key)) { + return; + } + let aliased = self.aliased(uses); + let tracked = aliased.as_deref().unwrap_or(uses); + if run.before(tracked, writes_truth) { + self.barrier(Barrier::everything()); + } + let Some(raw) = self.recording() else { + return; + }; + record(self.device().shared().vk(), raw); + self.uses.record(stages, tracked, None); + self.touch(uses); + } + /// The `VkCommandBuffer` a render pass holds ([`hold_pass`](Self::hold_pass)), until its /// release. pub(super) fn held_pass(&self) -> Option { @@ -1070,9 +1149,10 @@ impl EncoderCore { /// Record shadowed textures' `copies` into the command buffer a render pass holds /// ([`hold_pass`](Self::hold_pass)), between two of its render pass instances, as the pass's - /// end records them there (`render/inline_splits.rs`): each with a barrier from everything - /// before and one to everything after, its uses the encoder's, an unordered one's. A copy of a - /// detached buffer's bytes records nothing, nor does what follows ([`skips`](Self::skips)). + /// end records them there (`render/inline_splits.rs`): as one run ([`ShadowRun`]) after the + /// barrier from everything before that the caller records at the instance's end, with one + /// to everything after its last copy; their uses the encoder's, an unordered one's. A copy of + /// a detached buffer's bytes records nothing, nor does what follows ([`skips`](Self::skips)). /// Nothing where no pass holds one. pub(super) fn held_shadow_copies(&mut self, copies: &[ShadowCopy]) { let Some(held) = self.pass else { @@ -1080,24 +1160,29 @@ impl EncoderCore { }; let device = self.device().clone(); let raw = device.shared().vk(); + let mut run = ShadowRun::after_barrier(); for copy in copies { let uses = copy.uses(); if self.skips(uses.iter().map(|used| used.key)) { continue; } + let aliased = self.aliased(&uses); + let tracked = aliased.as_deref().unwrap_or(&uses); + let before = run.before(tracked, copy.writes_truth()); // SAFETY: the held command buffer is recording outside a render pass instance (the // caller ended the one before), and only this encoder records it; its commands retain // the shadowed textures (and their views) until it completes, and every image rests // in the `GENERAL` layout. unsafe { - Barrier::everything().record(raw, held); - copy.record(raw, held); - Barrier::everything().record(raw, held); + if before { + Barrier::everything().record(raw, held); + } } - let aliased = self.aliased(&uses); - self.uses - .record(copy.stages(), aliased.as_deref().unwrap_or(&uses), None); + self.uses.record(stages, tracked, None); self.touch(&uses); + if run.recorded() { + // SAFETY: as above. + unsafe { Barrier::everything().record(raw, held) }; } } @@ -1238,6 +1323,10 @@ impl EncoderCore { } Some(log) }); + let sharing = self.shadows.sharing_truth(); + if sharing > 0 { + self.device().shared().counts.shadows_sharing_truth(sharing); + } let copies = self.shadows.finish(); self.count_shadow_copies(&copies); self.shadow_copies(&copies); @@ -1257,6 +1346,7 @@ impl EncoderCore { retained, executions, keys, + first_copies, mut heaps, holds, taken, @@ -1274,6 +1364,13 @@ impl EncoderCore { .among(keys.iter().copied()); heaps.extend(keyed); let mut state = open.command_buffer.state(); + if !first_copies.is_empty() { + let again = state.shadows_copied_in(&first_copies); + if again > 0 { + (open.command_buffer.device().shared().counts) + .shadow_texels_first_copied_in_again(again); + } + } state.use_heaps(heaps); let encoder = state.encoder_ended(kind, keys, residency, taken); state.encoder_holds(encoder, uses.held().to_vec()); @@ -1475,3 +1572,105 @@ impl EncoderCore { }) } } + +/// A run of shadowed textures' copies in an encoder whose commands Metal leaves unordered +/// (`EncoderCore::shadow_copies`, `held_shadow_copies`): one barrier from everything before its +/// first copy and one to everything after its last order the run against the encoder's other +/// commands, as a barrier around each copy did, a global barrier's first scope being every +/// command before it and its second every command after. Inside the run a copy goes after a +/// barrier only where it needs one: +/// +/// - **Writes of the truth.** A copy back or a merge writes the texture's truth: a buffer's bytes +/// (another key's too, where buffers over the same memory are not one key, +/// `host_aliases.rs`) or a texture's image. It takes a barrier before it and one after it, as +/// every copy did. +/// - **The others** (copies in and keeps) write only memory the runtime made for the texture +/// alone: its shadow, a merge's scratch or kept image, each of a key of its own. One goes after +/// a barrier where a use of it and a use of a copy since the last barrier name the same key +/// (aliases added) over ranges that share memory, and one of the two writes it: the tracker's +/// rule for two commands that must run in order. Copies in of different textures (reads of +/// their truths, writes of their own shadows) run together; a keep after the copy in of its +/// texture (the shadow written, then read) takes its barrier. +/// +/// Every image rests in `GENERAL`, so no barrier the run leaves out carried a layout transition. +#[derive(Default)] +struct ShadowRun { + /// The uses of the copies since the run's last barrier (aliases added); `None` before its + /// first. + since: Option>>, + /// Whether the last copy wrote its truth: the next copy takes a barrier. + fenced: bool, + /// Whether a copy was recorded in the run. + recorded: bool, +} + +impl ShadowRun { + /// A run whose first copy follows a barrier from everything before, which the caller records. + fn after_barrier() -> ShadowRun { + ShadowRun { + since: Some(Vec::new()), + fenced: false, + recorded: false, + } + } + + /// Whether the next copy, of `uses` (aliases added), writing its truth where `writes_truth`, + /// goes after a barrier (the type's rules); noted as recorded. + fn before(&mut self, uses: &[Use], writes_truth: bool) -> bool { + let barrier = match &self.since { + None => true, + Some(since) => self.fenced || writes_truth || meets(since, uses), + }; + let since = self.since.get_or_insert_with(Vec::new); + if barrier { + since.clear(); + } + since.extend(uses.iter().cloned()); + self.fenced = writes_truth; + self.recorded = true; + barrier + } + + /// Whether a copy was recorded in the run, which then takes a barrier to everything after. + fn recorded(&self) -> bool { + self.recorded + } +} + +/// Whether a use of `later` and one of `earlier` name the same key over ranges that share memory, +/// and one of the two writes it. +fn meets(earlier: &[Use], later: &[Use]) -> bool { + later.iter().any(|used| { + earlier.iter().any(|before| { + before.key == used.key + && before.range.overlaps(&used.range) + && !(before.write.is_empty() && used.write.is_empty()) + }) + }) +} + +/// The dispatch that takes the copy in at `copies[i]` and its texture's keep after it together +/// (`ShadowMerge::keep_in`, `shadow_copy_in.rs`), where `device` takes one: the keep's place in +/// `copies`, the dispatch and its uses. The copies between them are of other textures' shadows, +/// so the keep's texels are the copy in's wherever it is recorded. `None` where the two stay +/// apart. +fn keep_with_copy_in( + device: &Device, + copies: &[ShadowCopy], + i: usize, +) -> Option<(usize, CopyIn, Vec>)> { + let copy = &copies[i]; + let region = copy.copied_region()?; + let shadow = copy.copies.shadow_key; + let (j, merge) = copies + .iter() + .enumerate() + .skip(i + 1) + .find(|(_, later)| later.copies.shadow_key == shadow) + .and_then(|(j, later)| match &later.step { + Step::Keep(merge) => Some((j, merge)), + _ => None, + })?; + let both = merge.keep_in(device, ©.copies, ®ion)?; + Some((j, both, merge.keep_in_uses(©.copies))) +} diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index 90abbf9e5..f1e5243e2 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -182,6 +182,7 @@ mod scheduler; mod shader_cache; mod shadow; mod shadow_copy_back; +mod shadow_copy_in; mod shadow_merge; mod shadow_stencil; mod sharing; diff --git a/crates/metal2vulkan-runtime/src/linear_merge.rs b/crates/metal2vulkan-runtime/src/linear_merge.rs index 132f6f16e..162849530 100644 --- a/crates/metal2vulkan-runtime/src/linear_merge.rs +++ b/crates/metal2vulkan-runtime/src/linear_merge.rs @@ -48,7 +48,7 @@ use super::buffer::Buffer; use super::encoder::EncoderCore; use super::error::{internal, Error}; -use super::owned_kernel::{OwnedKernel, OwnedModule, OwnedSets}; +use super::owned_kernel::{OwnedBinds, OwnedKernel, OwnedModule, OwnedSet}; use super::render_pass::Target; use super::resource::ResourceKey; use super::tracker::{Access, Barrier, Use}; @@ -84,9 +84,9 @@ pub(super) struct LinearMerge { padding: Option<(u64, u64)>, _held: Buffer, kernel: OwnedKernel, - /// One set per dispatch, each binding its band of the kept part, of the changed part and of - /// the surface's bytes. - sets: OwnedSets, + /// One set 0 per dispatch, each binding its band of the kept part, of the changed part and of + /// the surface's bytes; pushed where the kernel's set 0 is pushed (`OwnedBinds`). + binds: OwnedBinds, dispatches: Vec, /// The keep's uses: a read of the image the pass renders. keep_uses: Vec>, @@ -97,7 +97,7 @@ pub(super) struct LinearMerge { impl LinearMerge { /// The merge of the box `[x0, y0, x1, y1]` (half-open, inside the render area) of the pass /// rendering `own`, a bound linear attachment's target, through `backing`, the image its - /// texture keeps: its scratch, sets and dispatches on `device`. Refused (internal) for an + /// texture keeps: its scratch, binds and dispatches on `device`. Refused (internal) for an /// attachment whose rows or their offset are not whole words, whose texel is not 1, 2, 4, 8 /// or 16 bytes, or whose bands no binding holds, which no device's linear attachment is; and /// as `scratch_buffer` refuses the scratch. @@ -162,7 +162,7 @@ impl LinearMerge { return Err(internal("a linear attachment's rows no merge window holds")); } let mut regions = Vec::with_capacity(layers as usize); - let mut ranges = Vec::new(); + let mut sets = Vec::new(); let mut dispatches = Vec::new(); let u32_of = |value: u64| { u32::try_from(value).map_err(|_| internal("a linear merge past u32 words")) @@ -200,11 +200,15 @@ impl LinearMerge { let skip = at - bound; let kept = kept_at + start * row_bytes; let size = count * row_bytes; - ranges.push(vec![ - (scratch, kept, size), - (scratch, kept + part, size), - (surface, bound, skip + (count - 1) * pitch + row_bytes), - ]); + sets.push(OwnedSet { + images: Vec::new(), + storage_images: Vec::new(), + buffers: vec![ + (scratch, kept, size), + (scratch, kept + part, size), + (surface, bound, skip + (count - 1) * pitch + row_bytes), + ], + }); let total = count * words; dispatches.push(Dispatch { groups: u32_of(total.div_ceil(local))?, @@ -219,7 +223,7 @@ impl LinearMerge { } } let kernel = device.owned_kernel(OwnedModule::ShadowMerge)?; - let sets = OwnedSets::write(device, &kernel, &ranges)?; + let binds = OwnedBinds::new(device, &kernel, &sets)?; let levels = backing.level..backing.level + 1; let backing_layers = backing.layer..backing.layer + backing.layers.max(1); let read = Access::new( @@ -266,7 +270,7 @@ impl LinearMerge { padding, _held: held, kernel, - sets, + binds, dispatches, keep_uses: vec![backing_read.clone()], merge_uses: vec![backing_read, surface], @@ -374,8 +378,8 @@ impl LinearMerge { ..*region }) .collect(); - // SAFETY: as in `keep_in`; the sets bind bands inside the scratch's parts and the - // surface's bytes, and the kernel's push range holds the shape. + // SAFETY: as in `keep_in`; the binds name bands inside the scratch's parts and the + // surface's bytes, one per dispatch, and the kernel's push range holds the shape. unsafe { device.cmd_copy_image_to_buffer( raw, @@ -386,15 +390,8 @@ impl LinearMerge { ); Barrier::everything().record(device, raw); device.cmd_bind_pipeline(raw, vk::PipelineBindPoint::COMPUTE, self.kernel.pipeline); - for (set, dispatch) in self.sets.sets.iter().zip(&self.dispatches) { - device.cmd_bind_descriptor_sets( - raw, - vk::PipelineBindPoint::COMPUTE, - self.kernel.layout, - 0, - std::slice::from_ref(set), - &[], - ); + for (index, dispatch) in self.dispatches.iter().enumerate() { + self.binds.bind(device, raw, &self.kernel, index); device.cmd_push_constants( raw, self.kernel.layout, @@ -409,7 +406,7 @@ impl LinearMerge { } /// The greatest common divisor of `a` and `b`. -fn gcd(mut a: u64, mut b: u64) -> u64 { +pub(super) fn gcd(mut a: u64, mut b: u64) -> u64 { while b != 0 { (a, b) = (b, a % b); } diff --git a/crates/metal2vulkan-runtime/src/owned_kernel.rs b/crates/metal2vulkan-runtime/src/owned_kernel.rs index 1e5c560d6..ba459c6cb 100644 --- a/crates/metal2vulkan-runtime/src/owned_kernel.rs +++ b/crates/metal2vulkan-runtime/src/owned_kernel.rs @@ -12,18 +12,25 @@ //! the index rewrite one per `RewriteProgram` and `RewritePhase` (closed enums of a few). //! - **Descriptor sets** ([`OwnedSets`]): one pool per command, holding one set per dispatch, each //! written with the command's image views and buffer ranges; the command buffer retains it -//! until it completes. +//! until it completes (`WorkCounts::owned_descriptor_pools`). A kernel whose set 0 is a push +//! descriptor set's ([`OwnedKernel::pushed`]) takes no pool: each dispatch pushes its +//! descriptors as it records ([`OwnedBinds`], which binds either way by that field alone). +//! Vulkan forbids a set from such a layout ("Each element of `pSetLayouts` must not have been +//! created with `VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT` set", +//! `VkDescriptorSetAllocateInfo`), so `OwnedSets` refuses its kernel (internal). +use super::binding::{self, Info, SetWrite}; use super::device::lock; use super::error::{internal, vulkan, Error}; use super::exit_guard; use super::release; use super::texture::decoded_twin::TwinDecode; use super::Device; +use crate::device::functions::Vk; use crate::shader_cache::driver::Making; use ash::vk; use metal2vulkan::bind::{ - BlockDecode, CompressedBlit, MipmapFilterKernel, RewritePhase, RewriteProgram, + CompressedBlit, MipmapFilterKernel, RewritePhase, RewriteProgram, ShadowTexelView, TessellationScanKernel, TexelWords, YCbCrOutput, }; use metal2vulkan::metal::format::ExtendedRange; @@ -58,11 +65,20 @@ pub(super) enum OwnedModule { /// pass that renders over it, and the pass's words merged back into the depth after it /// (`signed_depth.rs`). DepthMagnitude, - /// `bind::shadow_copy_back_module` of one texel width (1, 2 or 4 words): a shadowed + /// `bind::shadow_copy_back_module` of one view of a texel (`ShadowTexelView`): a shadowed /// texture's texels stored back into its buffer's rows by a dispatch, where the device copies /// back faster so (`shadow_copy_back.rs`). Its shadow's unsigned-integer view is its sampled /// image. - ShadowCopyBack(u32), + ShadowCopyBack(ShadowTexelView), + /// `bind::shadow_merge_image_module` of one view of a texel (`ShadowTexelView`): a shadowed + /// texture's writes merged into its buffer's bytes, reading its shadow's texels through its + /// unsigned-integer view, its sampled image (`shadow_merge.rs`). + ShadowMergeImage(ShadowTexelView), + /// `bind::shadow_copy_in_module` of one view of a texel (`ShadowTexelView`): a merged + /// shadowed texture's texels copied in from its buffer's rows and kept in its merge's scratch + /// by one dispatch (`shadow_copy_in.rs`). Its shadow's unsigned-integer view is its storage + /// image. + ShadowCopyIn(ShadowTexelView), /// `bind::mipmap_filter_module` of one kernel: a level of a mipmap chain from the level /// above it, as Metal's filter computes it (`mipmap_filter.rs`); a kernel that fetches the /// first level binds its sampled view first. Needs `shaderInt64`: a device without it fails @@ -141,15 +157,28 @@ impl OwnedModule { fn images(self) -> u32 { match self { OwnedModule::MipmapFilter(kernel) => u32::from(kernel.fetches()), - OwnedModule::ShadowCopyBack(_) => 1, + OwnedModule::ShadowCopyBack(_) | OwnedModule::ShadowMergeImage(_) => 1, _ => 0, } } + /// copy's and a shadowed texture's copies' and merges', on a device with + /// `VK_KHR_push_descriptor`, so their commands make no pool on the encoding thread + /// (`row_copies.rs`, `shadow_copy_back.rs`, `shadow_copy_in.rs`, `shadow_merge.rs`). + matches!( + self, + OwnedModule::RowsCopy + | OwnedModule::ShadowCopyBack(_) + | OwnedModule::ShadowCopyIn(_) + | OwnedModule::ShadowMerge + | OwnedModule::ShadowMergeImage(_) + ) && device.shared().vk().push_descriptor().is_some() /// The module's storage-image bindings, which come after its sampled images. fn storage_images(self) -> u32 { match self { - OwnedModule::YCbCrConvert(_) | OwnedModule::YCbCrWrite => 1, + OwnedModule::YCbCrConvert(_) + | OwnedModule::YCbCrWrite + | OwnedModule::ShadowCopyIn(_) => 1, OwnedModule::ExtendedShadowLoad(_) => 2, _ => 0, } @@ -206,13 +235,27 @@ impl OwnedModule { let push_bytes = metal2vulkan::bind::DepthMagnitudeModule::PUSH_BYTES; Ok((module.spirv.to_vec(), 2, push_bytes)) } - OwnedModule::ShadowCopyBack(words) => { + OwnedModule::ShadowCopyBack(view) => { let module = - metal2vulkan::bind::shadow_copy_back_module(device.compile_device(), words) + metal2vulkan::bind::shadow_copy_back_module(device.compile_device(), view) .map_err(Error::Compile)?; let push_bytes = metal2vulkan::bind::ShadowCopyBackModule::PUSH_BYTES; Ok((module.spirv.to_vec(), 1, push_bytes)) } + OwnedModule::ShadowMergeImage(view) => { + let module = + metal2vulkan::bind::shadow_merge_image_module(device.compile_device(), view) + .map_err(Error::Compile)?; + let push_bytes = metal2vulkan::bind::ShadowMergeImageModule::PUSH_BYTES; + Ok((module.spirv.to_vec(), 2, push_bytes)) + } + OwnedModule::ShadowCopyIn(view) => { + let module = + metal2vulkan::bind::shadow_copy_in_module(device.compile_device(), view) + .map_err(Error::Compile)?; + let push_bytes = metal2vulkan::bind::ShadowCopyInModule::PUSH_BYTES; + Ok((module.spirv.to_vec(), 2, push_bytes)) + } OwnedModule::MipmapFilter(kernel) => { let module = metal2vulkan::bind::mipmap_filter_module(device.compile_device(), kernel) @@ -366,7 +409,9 @@ pub(super) struct OwnedKernels { flat_dispatch: Option, shadow_merge: Option, depth_magnitude: Option, - shadow_copy_backs: HashMap, + shadow_copy_backs: HashMap, + shadow_merge_images: HashMap, + shadow_copy_ins: HashMap, mipmap_filters: HashMap, mesh_scan: Option, plane_words: Option, @@ -417,6 +462,8 @@ impl OwnedKernels { .into_iter() .flatten() .chain(self.shadow_copy_backs.values().copied()) + .chain(self.shadow_merge_images.values().copied()) + .chain(self.shadow_copy_ins.values().copied()) .chain(self.mipmap_filters.values().copied()) .chain(self.index_rewrites.values().copied()) .chain(self.ycbcr_converts.values().copied()) @@ -433,7 +480,9 @@ impl OwnedKernels { /// The kernel of `which`, where the device has made it. fn get(&mut self, which: OwnedModule) -> Option { match which { - OwnedModule::ShadowCopyBack(words) => self.shadow_copy_backs.get(&words).copied(), + OwnedModule::ShadowCopyBack(view) => self.shadow_copy_backs.get(&view).copied(), + OwnedModule::ShadowMergeImage(view) => self.shadow_merge_images.get(&view).copied(), + OwnedModule::ShadowCopyIn(view) => self.shadow_copy_ins.get(&view).copied(), OwnedModule::MipmapFilter(kernel) => self.mipmap_filters.get(&kernel).copied(), OwnedModule::IndexRewrite(program, phase) => { self.index_rewrites.get(&(program, phase)).copied() @@ -453,8 +502,14 @@ impl OwnedKernels { /// Keep `kernel`, the kernel of `which`. fn put(&mut self, which: OwnedModule, kernel: OwnedKernel) { match which { - OwnedModule::ShadowCopyBack(words) => { - self.shadow_copy_backs.insert(words, kernel); + OwnedModule::ShadowCopyBack(view) => { + self.shadow_copy_backs.insert(view, kernel); + } + OwnedModule::ShadowMergeImage(view) => { + self.shadow_merge_images.insert(view, kernel); + } + OwnedModule::ShadowCopyIn(view) => { + self.shadow_copy_ins.insert(view, kernel); } OwnedModule::MipmapFilter(key) => { self.mipmap_filters.insert(key, kernel); @@ -488,6 +543,8 @@ impl OwnedKernels { } } + /// The slot of a kernel the device makes once (none for the shadow copy back's, the image + /// merge's, the shadow copy in's, the mipmap filter's, the index rewrite's, the YCbCr conversion's, the unused bits', the compressed /// blit's, the extended shadow load's, the twin decode's or the tessellation scan's, one /// per key). fn slot(&mut self, which: OwnedModule) -> Option<&mut Option> { @@ -501,6 +558,8 @@ impl OwnedKernels { OwnedModule::ShadowMerge => &mut self.shadow_merge, OwnedModule::DepthMagnitude => &mut self.depth_magnitude, OwnedModule::ShadowCopyBack(_) + | OwnedModule::ShadowMergeImage(_) + | OwnedModule::ShadowCopyIn(_) | OwnedModule::MipmapFilter(_) | OwnedModule::IndexRewrite(..) | OwnedModule::YCbCrConvert(_) @@ -690,7 +749,9 @@ impl OwnedSets { } /// One set per entry of `sets`, of the kernel at its index in `kernels`, each written with - /// its entry's views and then its buffer ranges, in binding order. + /// its entry's views and then its buffer ranges, in binding order. Refused (internal) for a + /// kernel whose set 0 is pushed, which no set is allocated from (the module docs): its + /// dispatches bind through [`OwnedBinds`]. pub(super) fn write_each( device: &Device, kernels: &[OwnedKernel], @@ -708,6 +769,9 @@ impl OwnedSets { { return Err(internal("owned sets that do not match their kernel")); } + if kernels.iter().any(|kernel| kernel.pushed) { + return Err(internal("owned sets of a kernel whose set 0 is pushed")); + } let total = |of: fn(&OwnedKernel) -> u32| { kernels .iter() @@ -734,6 +798,7 @@ impl OwnedSets { .pool_sizes(&sizes); // SAFETY: `info` and its array are live for the call. let pool = unsafe { raw.create_descriptor_pool(&info, None) }.map_err(vulkan)?; + device.shared().counts.owned_descriptor_pool(); let mut owned = OwnedSets { device: device.clone(), pool, @@ -810,3 +875,113 @@ impl OwnedSets { Ok(owned) } } + +/// How one command's dispatches of a kernel bind set 0 (the module docs): pushed as each +/// records where the kernel's set 0 is a push descriptor set's ([`OwnedKernel::pushed`]), so the +/// command makes no pool; else one set per dispatch from a pool of their own ([`OwnedSets`]), +/// which the command buffer retains with the command until it completes. +pub(super) enum OwnedBinds { + /// Each dispatch's writes, in binding order, pushed by the push command of the checked + /// functions it records with (`Vk::push_descriptor`). + Pushed(Vec>), + /// One set per dispatch. + Sets(OwnedSets), +} + +impl OwnedBinds { + /// The binds of `kernel`'s dispatches on `device`, one per entry of `sets`: each its entry's + /// sampled images, storage images (each in the `GENERAL` layout) and storage buffers, in + /// binding order. + pub(super) fn new( + device: &Device, + kernel: &OwnedKernel, + sets: &[OwnedSet], + ) -> Result { + if !kernel.pushed { + let kernels = vec![*kernel; sets.len()]; + return OwnedSets::write_each(device, &kernels, sets).map(OwnedBinds::Sets); + } + let image = |view: &vk::ImageView| { + Info::Image(vk::DescriptorImageInfo { + sampler: vk::Sampler::null(), + image_view: *view, + image_layout: vk::ImageLayout::GENERAL, + }) + }; + let mut pushed = Vec::with_capacity(sets.len()); + for set in sets { + if set.images.len() != kernel.images as usize + || set.storage_images.len() != kernel.storage_images as usize + || set.buffers.len() != kernel.buffers as usize + { + return Err(internal("owned binds that do not match their kernel")); + } + let images = set + .images + .iter() + .map(|view| (vk::DescriptorType::SAMPLED_IMAGE, image(view))); + let storage = set + .storage_images + .iter() + .map(|view| (vk::DescriptorType::STORAGE_IMAGE, image(view))); + let buffers = set.buffers.iter().map(|&(buffer, offset, range)| { + let info = vk::DescriptorBufferInfo { + buffer, + offset, + range, + }; + (vk::DescriptorType::STORAGE_BUFFER, Info::Buffer(info)) + }); + let writes = (0..) + .zip(images.chain(storage).chain(buffers)) + .map(|(binding, (ty, info))| SetWrite { + binding, + element: 0, + ty, + info, + }) + .collect(); + pushed.push(writes); + } + Ok(OwnedBinds::Pushed(pushed)) + } + + /// Bind dispatch `index`'s set 0 of `kernel` into `command_buffer`, whose compute pipeline is + /// `kernel`'s. + /// + /// # Safety + /// + /// `command_buffer` is recording on the device of `device`, which made `kernel`; every view + /// and buffer the binds name is live until it completes, and `index` names one of them. + pub(super) unsafe fn bind( + &self, + device: &Vk, + command_buffer: vk::CommandBuffer, + kernel: &OwnedKernel, + index: usize, + ) { + let point = vk::PipelineBindPoint::COMPUTE; + // SAFETY: the caller's contract. + unsafe { + match (self, device.push_descriptor()) { + (OwnedBinds::Pushed(writes), Some(push)) => { + binding::push_set(push, command_buffer, point, kernel.layout, &writes[index]); + } + // A kernel made pushed on a device that pushes (`OwnedKernel::pushed`), so not + // reached: a push binds nothing here. + (OwnedBinds::Pushed(_), None) => {} + (OwnedBinds::Sets(sets), _) => { + let set = std::slice::from_ref(&sets.sets[index]); + device.cmd_bind_descriptor_sets( + command_buffer, + point, + kernel.layout, + 0, + set, + &[], + ); + } + } + } + } +} diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 7ab955b69..96e861a30 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -4351,17 +4351,23 @@ impl RenderCommandEncoder { order.extend(after.map(|dispatch| (&dispatch.shadows, None, true))); } let reached = reach != clear_reach::PassReach::Nothing; - // Where nothing but the draws writes the loaded colors: no reach clear before the - // pass. - let drawn_bounds = match (reach, &reach_clears) { - (clear_reach::PassReach::Draws, None) => drawn.bounds(), - _ => None, + // A pass whose draws reach tiles changes the colors the encoder set to load inside + // its draws' scissors alone (`render/shadows.rs`), whichever tiles it reaches: one + // that reaches every tile (an attachment it clears and stores) loads and stores + // their other texels as they were. A clear before the pass leaves them alone too: a + // reach clear clears only attachments whose load is `Clear`, a `DontCare` load turned + // into one among them (`clear_reach::ReachClears`), and no load the encoder set to + // `Load` turns into `Clear`. + let drawn_bounds = match reach { + clear_reach::PassReach::Draws | clear_reach::PassReach::Every => drawn.bounds(), + clear_reach::PassReach::Nothing => None, }; let planned = shadows::plan( &mut core, order.iter().map(|&(s, bound, _)| (s, bound)), &layout, (reached, drawn_bounds.map(|area| (area, loaded_colors))), + drawn_bounds.is_some().then_some(&drawn), )?; let (mut planned_copies, mut dispatch_copies) = (Vec::new(), Vec::new()); for (&(_, _, of_dispatch), copies) in order.iter().zip(planned) { diff --git a/crates/metal2vulkan-runtime/src/render/inline_splits.rs b/crates/metal2vulkan-runtime/src/render/inline_splits.rs index 6be5793a8..d99e8d5ae 100644 --- a/crates/metal2vulkan-runtime/src/render/inline_splits.rs +++ b/crates/metal2vulkan-runtime/src/render/inline_splits.rs @@ -292,6 +292,7 @@ impl RenderCommandEncoder { std::iter::once((&instance.shadows, bound)), &self.layout, (true, area.map(|area| (area, &loaded[..]))), + area.is_some().then_some(&self.drawn), )?; Ok(planned.into_iter().next().unwrap_or_default()) } @@ -332,8 +333,9 @@ impl RenderCommandEncoder { } /// Record `instance`, kept (the module docs), into the pass's command buffer after the render -/// pass instance before it: that one's end, a barrier from everything before, `copies` (each -/// followed by a barrier), the steps its draws take before it, its render pass instance's begin +/// pass instance before it: that one's end, a barrier from everything before, `copies` (one run +/// of them, `EncoderCore::held_shadow_copies`, followed by a barrier), the steps its draws take +/// before it, its render pass instance's begin /// in `objects` (a render pass compatible with its draws' pipelines, and the pass's /// framebuffer), and its commands, recorded through `bound`, the record of what the command /// buffer bound. diff --git a/crates/metal2vulkan-runtime/src/render/shadows.rs b/crates/metal2vulkan-runtime/src/render/shadows.rs index e9ef3be75..8a95813d2 100644 --- a/crates/metal2vulkan-runtime/src/render/shadows.rs +++ b/crates/metal2vulkan-runtime/src/render/shadows.rs @@ -17,15 +17,18 @@ //! (`clear_reach::PassReach::Nothing`) leaves a color attachment it loads, resolves nothing from //! and stores (or stores `DontCare`) as it was, as Metal loads and stores only the tiles a draw //! reaches: where its texture's shadow is an image of a buffer's bytes, nothing is copied in or -//! back. A pass whose draws do reach tiles changes a color attachment it loads (as the encoder -//! set its load, with no clear before the pass) only inside its draws' scissors -//! (`clear_reach::DrawnArea`): only those texels are copied back, and, where the pass takes the -//! texture in no other way, only those are copied in, as nothing the pass reads outside them -//! reaches anything but the image (its load is stored back unchanged, and a fragment reads the -//! attachment at its own pixel alone). A texture over a buffer with an aliasing image renders -//! into that image: the buffer's bytes, with no copy; but a pass that does not store it renders -//! through an image its texture keeps, from which nothing is copied back either -//! (`kept_bytes.rs`). +//! back. A pass whose draws do reach tiles, some or (where it clears and stores an attachment) +//! every one, changes a color attachment it loads (as the encoder set its load, so no clear +//! before the pass reaches it: a clear past the render area clears attachments loaded `Clear` +//! alone, `clear_reach.rs`) only inside its draws' scissors (`clear_reach::DrawnArea`), the +//! load pass of a format whose tiles Metal stores otherwise rewriting the buffer's bytes before +//! it (`render/unused_bits_load.rs`): only those texels are copied back, and, where the pass +//! takes the texture in no other way, only those are copied in, as nothing the pass reads +//! outside them reaches anything but the image (its load is stored back unchanged, and a +//! fragment reads the attachment at its own pixel alone). A texture over a buffer with an +//! aliasing image renders into that image: the buffer's bytes, with no copy; but a pass that +//! does not store it renders through an image its texture keeps, from which nothing is copied +//! back either (`kept_bytes.rs`). //! - **Two ways.** An instance that writes through a shadowed texture (in a draw, or as an //! attachment it stores) and also writes its bytes another way keeps the texture before it //! and merges it after it, as `shadow.rs` does for a command: the merge goes between it and the @@ -48,6 +51,7 @@ //! call did not gather (none can: its tables and residency are the call's). use crate::buffer::Buffer; +use crate::clear_reach::DrawnArea; use crate::encoder::EncoderCore; use crate::error::Error; use crate::render_pass::{ColorTarget, PassLayout, Target}; @@ -56,6 +60,7 @@ use crate::render_values::{LoadAction, StoreAction}; use crate::resource::ResourceKey; use crate::shadow::{self, ShadowCopy, ShadowTarget, ShadowUse, Within}; use crate::tracker::{Access, Use, UseRange}; +use crate::work_counts::{ColorTaken, Counters}; use ash::vk; use metal2vulkan::metal::TextureType; use std::collections::BTreeMap; @@ -241,11 +246,14 @@ impl InstanceShadows { /// (an instance of draws alone, after the pass's first, which the steps before the pass's /// instances do not precede): its writes of those colors change their bytes inside it alone /// ([`bounded_color`], `shadow::Within`), and an attachment's shadow is copied back there. +/// `area` is the draws' scissor rectangles `drawn` bounds, which the first instance's colors +/// are counted against (`WorkCounts::shadow_attachment_tiles_covered`). pub(super) fn plan<'a>( core: &mut EncoderCore, instances: impl Iterator)>, layout: &PassLayout, (reached, drawn): (bool, Option<([u32; 4], &[bool])>), + area: Option<&DrawnArea>, ) -> Result>, Error> { let attached = render_target::attachment_uses(layout)?; // The colors whose writes an instance bounds, and the uses of the other attachments. @@ -272,6 +280,7 @@ pub(super) fn plan<'a>( for (instance, bound) in instances { let bound = bound.filter(|_| drawn.is_some()); let attachments = attachment_shadows(layout, reached, drawn, bound); + count_colors(&core.device().shared().counts, layout, reached, drawn, area); let mut shadows = Vec::with_capacity(attachments.len() + instance.shadows.len()); for shadow in attachments.iter().chain(&instance.shadows) { shadow::join(&mut shadows, shadow); @@ -425,42 +434,11 @@ fn attachment_shadows( color.store, StoreAction::Store | StoreAction::StoreAndMultisampleResolve | StoreAction::Unknown ); - let overwrites = color.load == LoadAction::Clear - && color.stand_in.is_none() - && color.planes.is_none() - && whole(&color.target, layout); - // A pass that reaches no tile and loads the attachment leaves its texels as they were: - // Metal loads and stores only the tiles a draw reaches (`clear_reach::PassReach`), and - // Vulkan's load and store write back what they read. Nothing resolves from it, so the - // pass needs none of the texels: a texture over a buffer's bytes in its own image takes - // no copy in, and nothing is copied back. - let untouched = !reached - && color.load == LoadAction::Load - && matches!(color.store, StoreAction::Store | StoreAction::DontCare) - && color.resolve.is_none() - && color.copied_resolve.is_none() - && color.stand_in.is_none() - && color.planes.is_none(); - // A pass that loads the attachment changes no texel outside its draws' scissors: a - // fragment's samples outside the scissor rectangle "will have their coverage set to 0" - // (the Fragment Operations chapter's Scissor Test), and its load and store write back - // what they read (as above). Each Vulkan scissor is Metal's rectangle clipped to the - // pixels its viewport overlaps (`render_state.rs`), which Metal's draw writes no pixel - // past, and `drawn` bounds them all. So only the texels inside it are copied back, of - // the attachment's texture where it is the whole of a one-level, one-slice texture. - // Nor does the pass read one outside it into anything but the image: the load reads - // every texel, but the store writes it back unchanged, a fragment reads the attachment - // at its own pixel alone (a blend, framebuffer fetch, programmable blending, an - // imageblock), and the area is unbounded wherever a fragment's write is not bounded so - // (a rasterization rate map, an execution of render commands) or something reads past - // its pixel (a tile dispatch reads the whole tile; a resolve reads every sample, and is - // excluded below). So only those texels are copied in (`ShadowUse::loads`); a draw that - // takes the texture another way (bound, or made resident) joins a use that reads - // anywhere, and each encoder copies in again before its first use. - let loaded = drawn.filter(|(_, loaded)| loaded.get(index) == Some(&true)); - let area = loaded - .map(|(area, _)| area) - .filter(|_| bounded_color(color, layout)); + let ColorTake { + overwrites, + untouched, + area, + } = color_take(layout, index, color, reached, drawn); let own = color.stand_in.as_ref().map(|s| &s.own); for target in std::iter::once(&color.target).chain(own) { if let Some(copies) = target.texture.shadow() { @@ -501,6 +479,102 @@ fn attachment_shadows( shadows } +/// How a pass takes a color attachment ([`color_take`]). +struct ColorTake { + /// It clears every texel of the attachment's texture ([`ShadowUse::overwrites`]). + overwrites: bool, + /// It changes no texel and reads none: a pass that reaches no tile and loads it. + untouched: bool, + /// The rectangle of texels it changes the attachment inside, and reads it inside but at its + /// load, which stores back what it read ([`ShadowUse::area`], [`ShadowUse::loads`]); `None` + /// for anywhere. + area: Option<[u32; 4]>, +} + +/// How a pass of `layout` that reaches tiles where `reached`, inside `drawn` where its draws' +/// scissors bound them (with the colors it loads by index, as [`plan`] takes them), takes its +/// color attachment `color`, at `index`. +fn color_take( + layout: &PassLayout, + index: usize, + color: &ColorTarget, + reached: bool, + drawn: Option<([u32; 4], &[bool])>, +) -> ColorTake { + let overwrites = color.load == LoadAction::Clear + && color.stand_in.is_none() + && color.planes.is_none() + && whole(&color.target, layout); + // A pass that reaches no tile and loads the attachment leaves its texels as they were: + // Metal loads and stores only the tiles a draw reaches (`clear_reach::PassReach`), and + // Vulkan's load and store write back what they read. Nothing resolves from it, so the + // pass needs none of the texels: a texture over a buffer's bytes in its own image takes + // no copy in, and nothing is copied back. + let untouched = !reached + && color.load == LoadAction::Load + && matches!(color.store, StoreAction::Store | StoreAction::DontCare) + && color.resolve.is_none() + && color.copied_resolve.is_none() + && color.stand_in.is_none() + && color.planes.is_none(); + // A pass that loads the attachment changes no texel outside its draws' scissors: a + // fragment's samples outside the scissor rectangle "will have their coverage set to 0" + // (the Fragment Operations chapter's Scissor Test), and its load and store write back + // what they read (as above). Each Vulkan scissor is Metal's rectangle clipped to the + // pixels its viewport overlaps (`render_state.rs`), which Metal's draw writes no pixel + // past, and `drawn` bounds them all. So only the texels inside it are copied back, of + // the attachment's texture where it is the whole of a one-level, one-slice texture. + // Nor does the pass read one outside it into anything but the image: the load reads + // every texel, but the store writes it back unchanged, a fragment reads the attachment + // at its own pixel alone (a blend, framebuffer fetch, programmable blending, an + // imageblock), and the area is unbounded wherever a fragment's write is not bounded so + // (a rasterization rate map, an execution of render commands) or something reads past + // its pixel (a tile dispatch reads the whole tile; a resolve reads every sample, and is + // excluded below). So only those texels are copied in (`ShadowUse::loads`); a draw that + // takes the texture another way (bound, or made resident) joins a use that reads + // anywhere, and each encoder copies in again before its first use. + let loaded = drawn.filter(|(_, loaded)| loaded.get(index) == Some(&true)); + let area = loaded + .map(|(area, _)| area) + .filter(|_| bounded_color(color, layout)); + ColorTake { + overwrites, + untouched, + area, + } +} + +/// Count how a pass of `layout` takes each of its color attachments whose texture is shadowed +/// (`WorkCounts::shadow_attachment_loads_within` and kin), as [`attachment_shadows`] plans them. +fn count_colors( + counts: &Counters, + layout: &PassLayout, + reached: bool, + drawn: Option<([u32; 4], &[bool])>, + area: Option<&DrawnArea>, +) { + let tiles = area.and_then(DrawnArea::covered_tiles); + let colors = layout.colors.iter().enumerate(); + for (index, color) in colors.filter_map(|(index, color)| Some((index, color.as_ref()?))) { + let Some(copies) = color.target.texture.shadow() else { + continue; + }; + let take = color_take(layout, index, color, reached, drawn); + let plain = matches!(copies.target(), Some(ShadowTarget::Image { .. })); + let taken = match color.load { + _ if take.untouched && plain && !copies.drops_writes => ColorTaken::Untouched, + _ if take.overwrites => ColorTaken::Cleared, + LoadAction::Clear => ColorTaken::ClearedInPart, + _ if take.area.is_some() => ColorTaken::LoadedWithin, + _ => ColorTaken::Loaded, + }; + counts.shadow_color_taken(taken); + if let (ColorTaken::LoadedWithin, Some((covered, bounded))) = (taken, tiles) { + counts.shadow_attachment_tiles(covered, bounded); + } + } +} + /// Whether `target` is the whole of its texture, a 2D texture of one level, and the pass's /// render area covers it: a clear of it replaces every texel. fn whole(target: &Target, layout: &PassLayout) -> bool { diff --git a/crates/metal2vulkan-runtime/src/render/snapshot.rs b/crates/metal2vulkan-runtime/src/render/snapshot.rs index 9035766be..e10c3a5c3 100644 --- a/crates/metal2vulkan-runtime/src/render/snapshot.rs +++ b/crates/metal2vulkan-runtime/src/render/snapshot.rs @@ -352,9 +352,12 @@ impl RenderCommandEncoder { /// costs no more than the split would: both forms are exact, so the draw takes the cheaper. The /// snapshot draw costs [`SNAPSHOT_PIXEL_COST`] for each color at each pixel the draw covers, /// which its Vulkan scissors bound (`EncoderState::vk_scissors`: each viewport's pixels within - /// its scissor rectangle, inside the render area); the split's copy reads and writes each - /// color's every texel of the rendered level, its format's bytes each. The split's pass break - /// (each attachment stored and loaded again) is left out, which errs toward the split. The + /// its scissor rectangle, inside the render area); the split's copy is weighed as reading and + /// writing each color's every texel of the rendered level, its format's bytes each, an upper + /// bound: a copy of a one-level, one-slice texture's image moves only the texels around the + /// draw's scissors, or those the instances before changed (`ShadowCopies::cuts`), which errs + /// toward the snapshot. The split's pass break (each attachment stored and loaded again) is + /// left out, which errs toward the split. The /// draw's pixels for every color (the scissors' pixels times the colors), the colors' pixels, /// and their bytes; it takes the snapshot where the first times [`SNAPSHOT_PIXEL_COST`] is at /// most the last. diff --git a/crates/metal2vulkan-runtime/src/row_copies.rs b/crates/metal2vulkan-runtime/src/row_copies.rs new file mode 100644 index 000000000..f071775bd --- /dev/null +++ b/crates/metal2vulkan-runtime/src/row_copies.rs @@ -0,0 +1,11 @@ +use super::owned_kernel::{OwnedBinds, OwnedKernel, OwnedModule, OwnedSet, OwnedSets}; + /// Its two buffers' bytes: pushed where the device pushes, else a set of a pool of its own. + binds: OwnedBinds, + binds: OwnedBinds::Sets(sets), + let set = OwnedSet { + images: Vec::new(), + storage_images: Vec::new(), + buffers: buffers.to_vec(), + let binds = OwnedBinds::new(device, &kernel, &[set]).ok()?; + binds, + self.binds.bind(device, command_buffer, &self.kernel, 0); diff --git a/crates/metal2vulkan-runtime/src/shadow.rs b/crates/metal2vulkan-runtime/src/shadow.rs index 6784731fa..dfbb5c6fa 100644 --- a/crates/metal2vulkan-runtime/src/shadow.rs +++ b/crates/metal2vulkan-runtime/src/shadow.rs @@ -22,8 +22,10 @@ //! attachment it loads, inside its draws' scissors), or by a copy back of a part of another //! shadow laid over the bytes texel for texel as it is ([`ShadowCopies::same_texels`]), takes //! a copy in of the texels inside the rectangle bounding those alone -//! (`WorkCounts::bounded_shadow_copies`): every other texel holds the bytes still. Any other -//! write of the bytes leaves it to copy in as above; it holds no writes of its own, nor a keep. +//! (`WorkCounts::bounded_shadow_copies`): every other texel holds the bytes still. A command +//! that reads only inside a rectangle and writes none takes those of them inside it, and the +//! rest stay to copy in before the next command that reads them. Any other write of the bytes +//! leaves it to copy in as above; it holds no writes of its own, nor a keep. //! - **Copy back** what a command wrote through the texture before the next command that touches //! the bytes some other way, and at the end of the encoder (orchestrator, 2026-10-04: at the //! end of the encoder that writes through the texture, not of the command buffer). A copy moves @@ -33,6 +35,30 @@ //! its draws' scissors), as the image's other texels are what the last copy in left. Where the //! device runs it faster so, a copy back of such a texture's image is a compute dispatch that //! stores the same bytes (`shadow_copy_back.rs`). +//! - **Merged back** ([`ShadowCopies::merges_back`]: a buffer's bytes another writer may write +//! while a command buffer runs, where a merge serves the shadow). A copy back would write every +//! texel it moves, those no command wrote too, with what the copy in read, over another writer's +//! writes to them while the command buffer ran, which Metal keeps: it writes only the texels a +//! command writes, and another writer writing bytes no command touches while a command buffer +//! runs is no race under its contract. The CPU writes a `Shared` or `Managed` buffer's bytes and +//! host pages so (an M3 Max under macOS 27.0.1 kept such a write, made inside a kernel's run, +//! every time, a `Managed` buffer's too), and another queue's commands an untracked buffer's, +//! which the program orders (the M3 Max ran another queue's fill of an untracked `Private` +//! buffer's other texels inside a kernel's or a render pass's run and kept it). A tracked +//! `Private` buffer's bytes have no such writer: the CPU writes none, and the tracker orders +//! another queue's commands that touch them before or after the encoder's command buffer, as +//! Metal does (the M3 Max ran another queue's fill of a tracked buffer after the kernel or the +//! pass ended, every time), so its texture's shadow is copied back. A merged-back image is kept, +//! after its copy in, before the first command since the last copy back that writes through it, +//! and each copy back of it is a merge (`shadow_merge.rs`): only the words the encoder's +//! commands changed through the texture since the keep reach the bytes. The keep holds the +//! rectangle the commands write in where they bound it ([`ShadowUse::area`]); a command that +//! writes outside it takes the merge first, and a keep of the rectangle bounding both. The image +//! still holds the bytes as the encoder's commands left them. A command that replaces every +//! texel ([`ShadowUse::overwrites`]) keeps nothing, as its copy back writes only texels it +//! wrote; that copy back goes before the keep of a later command that writes through the +//! texture, since the merge after the keep takes only the words changed since it. The keeps' +//! scratch is the encoder's, one per texture and rectangle. //! - **Ordering.** A copy is a command of the encoder with uses of both the buffer's bytes and the //! image, so the tracker orders it against the encoder's other commands and other encoders' //! like any use: the texture and its buffer are one resource to it. In an encoder whose @@ -64,7 +90,11 @@ //! texels between the two formats (an alpha format and another, `A8_UNORM` and `R8_UNORM`: //! `image_plan::copies_between`), and the rules above are the same with the image in the //! buffer's place, except that a command writing the image two ways (below) is refused: no merge -//! serves an image. +//! serves an image. A shadow of one level and slice copied image to image (a 2D texture's own +//! image's, `texture/usage_shadow.rs`, among them) has its copies in cut to rectangles as a +//! one-level, one-slice texture's over a buffer has, its texels the image's at their own +//! coordinates ([`ShadowCopies::cuts`]); its copies back move every texel, so a command that +//! writes through it takes every texel in first. //! - **Rotated textures** (`rotated.rs`, `texture/rotation.rs`). A rotated texture renders through //! an image of its pass's frame whose truth is the buffer's bytes in the frame Metal stores the //! texture in, turned: its copies go through a staging buffer of the bytes as laid out and a @@ -116,11 +146,12 @@ use super::error::{Error, RuntimeGap}; use super::resource::ResourceKey; use super::rotated::{RotatedCopies, Turn}; use super::shadow_copy_back::{CopyBack, WordView}; -use super::shadow_merge::ShadowMerge; +use super::shadow_merge::{ScratchSpares, ShadowMerge}; use super::texture::heap_tiled::HeapTiledCopies; use super::texture::heap_two_planes::HeapPlaneCopies; use super::texture::Texture; use super::tracker::{Access, Barrier, Use, UseRange}; +use super::values::StorageMode; use super::view_plan::reinterpretation_refused; use super::ycbcr::{YCbCrConversion, YCbCrWriteBack}; use super::Device; @@ -146,6 +177,54 @@ pub(super) struct ShadowCopies { /// ZCI2-rotprobe5-m4). Such a shadow is never copied back, and a command writing through it /// leaves it to copy in again at its next use. pub(super) drops_writes: bool, + /// What holds the truth, as the CPU may write it. + pub(super) backing: Backing, + /// The scratch buffers its merges are done with, kept for its next ones (`shadow_merge.rs`). + pub(super) merge_scratch: ScratchSpares, +} + +/// What holds a shadow's truth, as the CPU may write it, by which the encoders' first copies in +/// are counted (`WorkCounts::shadow_texels_first_copied_in`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Backing { + /// An image (a texture's own, or the image a view presents): only the runtime's commands and + /// calls write it. + Image, + /// A buffer of private or memoryless storage the runtime allocated: likewise. + PrivateBuffer, + /// A buffer of shared or managed storage the runtime allocated, which the CPU maps. + MappedBuffer, + /// Host pages a no-copy buffer imported, or the memory of the caller's `VkBuffer`. + HostPages, + /// Host pages that the texture's own image lies in too (an aliasing image, a pitched host + /// image among them), a shadow of which reads them as the image left them. + AliasedHostPages, + /// The bytes of an IOSurface's plane. + Surface, +} + +impl Backing { + /// What holds the bytes of `buffer`, a texture's over an IOSurface's plane where `surface`. + pub(super) fn of(buffer: &Buffer, surface: bool) -> Backing { + let private = matches!( + buffer.resource_options().storage_mode(), + Ok(StorageMode::Private | StorageMode::Memoryless) + ); + match (surface, buffer.caller_memory(), private) { + (true, _, _) => Backing::Surface, + (false, Some(_), _) => Backing::HostPages, + (false, None, true) => Backing::PrivateBuffer, + (false, None, false) => Backing::MappedBuffer, + } + } + + /// The backing of a shadow of a texture whose own image lies in the bytes too. + pub(super) fn aliased(self) -> Backing { + match self { + Backing::HostPages => Backing::AliasedHostPages, + other => other, + } + } } /// A shadow's truth: what the shadow holds a copy of between an encoder's copies (the module's @@ -222,8 +301,9 @@ pub(super) enum ShadowSource { /// The `VkBuffer` a shadow's bytes lie in. pub(super) enum ShadowBuffer { - /// One for good. - Fixed(vk::Buffer), + /// One for good: a buffer's the runtime made, or the caller's own `VkBuffer`; and where the + /// buffer's bytes end in it. + Fixed(vk::Buffer, u64), /// A buffer over host pages, which a rebind gives other pages (`rebind.rs`): its `VkBuffer` /// is read as each copy is recorded. A rebind keeps the bytes' offset in it (a heap's bytes /// start at its first byte, and a no-copy buffer with a texture over it keeps its offset in @@ -239,18 +319,33 @@ impl ShadowBuffer { pub(super) fn of(buffer: &Buffer, raw: vk::Buffer) -> ShadowBuffer { match buffer.caller_memory() { Some(CallerMemory::HostPages) => ShadowBuffer::Rebound(buffer.downgrade()), - _ => ShadowBuffer::Fixed(raw), + _ => ShadowBuffer::Fixed(raw, buffer.start() + buffer.length()), } } - /// The `VkBuffer` the bytes lie in now: the null handle once a rebound buffer went, which no - /// copy records (a copy's texture keeps its buffer). - pub(super) fn raw(&self) -> vk::Buffer { + /// Where the buffer's bytes end in its `VkBuffer` (its byte 0's offset there, + /// [`Buffer::start`], past its length), which a rebind keeps: a merge in place reads and + /// writes whole words of them up to it (`shadow_merge.rs`). 0 once a rebound buffer went. + pub(super) fn end(&self) -> u64 { match self { - ShadowBuffer::Fixed(raw) => *raw, + ShadowBuffer::Fixed(_, end) => *end, ShadowBuffer::Rebound(buffer) => buffer .upgrade() - .map_or(vk::Buffer::null(), |buffer| buffer.at(0).0), + .map_or(0, |buffer| buffer.start() + buffer.length()), + } + /// The `VkBuffer` the bytes lie in now: the null handle once a rebound buffer went (a copy's + /// texture keeps its buffer), and while it is detached (`detach.rs`), when its `VkBuffer` is + /// the device's stand-in, which holds none of its bytes. No copy records it: an encoder + /// records nothing of a command that names detached bytes (`EncoderCore::skips`), and nothing + /// planned binds it (a copy back's dispatch, `CopyBack::new`; a merge's window, + /// `ShadowMerge::new`). + pub(super) fn raw(&self) -> vk::Buffer { + match self { + ShadowBuffer::Fixed(raw, _) => *raw, + ShadowBuffer::Rebound(buffer) => buffer + .upgrade() + .and_then(|buffer| buffer.attached_at(0)) + .map_or(vk::Buffer::null(), |(raw, _)| raw), } } } @@ -267,8 +362,9 @@ pub(super) enum ShadowTarget { /// texture ([`ShadowCopy::area`]) offsets its region; `None` where no copy of it is /// bounded (a heap's depth or stencil texture, which is no color attachment). texel: Option, - /// The image's unsigned-integer view through which its copies back dispatch, where the - /// device copies back faster so (`shadow_copy_back.rs`); `None` where they copy. + /// The image's unsigned-integer view, where the device copies back faster by a dispatch + /// (`shadow_copy_back.rs`): through which its copies back dispatch and its merges read + /// the texels the commands left (`shadow_merge.rs`); `None` where they copy. words: Option, }, /// A texture buffer's staging buffer, which its bindings view. @@ -327,26 +423,77 @@ impl ShadowStaging { } impl ShadowCopies { - /// Whether a copy of the shadow's texels is cut to the rectangle of a part of them - /// ([`ShadowCopy::area`], [`part_of`]): a one-level, one-slice 2D texture's image over a - /// buffer's bytes, one region copied in place (no staging buffer). + /// Whether a copy in of the shadow's texels is cut to the rectangle of a part of them + /// ([`ShadowCopy::area`]): a one-level, one-slice 2D texture's image over a buffer's bytes, + /// one region copied in place (no staging buffer, [`part_of`]), whose copies back are cut + /// too; or a shadow of one level and slice of another image, copied image to image + /// ([`image_part_of`]), whose copies back move every texel ([`cuts_back`](Self::cuts_back)). pub(super) fn cuts(&self) -> bool { - matches!( - self.target(), - Some(ShadowTarget::Image { - regions, - staging: None, - texel: Some(_), + match &self.source { + ShadowSource::Bytes { + target: + ShadowTarget::Image { + regions, + staging: None, + texel: Some(_), + .. + }, .. - }) if regions.len() == 1 - ) + } => regions.len() == 1, + ShadowSource::Image { + regions, + through: None, + .. + } => one_image_copy(regions).is_some(), + _ => false, + } } - /// Whether `other`'s texels lie in the truth's bytes as this shadow's do, texel for texel: - /// both cut to rectangles ([`cuts`](Self::cuts)), of one buffer, their one regions starting at - /// one byte, rows as long, of one extent, of texels of one size. A change of the bytes of - /// one's texels inside a rectangle is then a change of the other's inside it alone. + /// Whether a copy back of the shadow's texels is cut to a rectangle as its copy in is: a + /// buffer's bytes' shadow that [`cuts`](Self::cuts). An image's shadow's copy back moves + /// every texel, so a command that writes through it takes every texel in first. + fn cuts_back(&self) -> bool { + self.cuts() && self.target().is_some() + } + + /// The texels the shadow holds: its every region's, every slice of each. + pub(super) fn texels(&self) -> u64 { + match &self.source { + ShadowSource::Image { regions, .. } => regions.iter().map(image_copy_texels).sum(), + ShadowSource::Bytes { + target: ShadowTarget::Image { regions, .. }, + .. + } => regions.iter().map(buffer_copy_texels).sum(), + ShadowSource::Bytes { .. } + | ShadowSource::Converted { .. } + | ShadowSource::YCbCrWrite { .. } => 0, + } + } + + /// Whether `other`'s texels lie in the truth as this shadow's do, texel for texel: both cut + /// to rectangles ([`cuts`](Self::cuts)), of one buffer, their one regions starting at one + /// byte, rows as long, of one extent, of texels of one size; or of one image, their one + /// regions of one aspect, level and slice, at one offset, of one extent. A change of one's + /// texels inside a rectangle is then a change of the other's inside it alone. pub(super) fn same_texels(&self, other: &ShadowCopies) -> bool { + let of_image = |copies: &ShadowCopies| match &copies.source { + ShadowSource::Image { + key, + regions, + through: None, + .. + } => one_image_copy(regions).map(|region| (*key, *region)), + _ => None, + }; + if let (Some((key, a)), Some((other_key, b))) = (of_image(self), of_image(other)) { + let (s, t) = (a.src_subresource, b.src_subresource); + return key == other_key + && s.aspect_mask == t.aspect_mask + && s.mip_level == t.mip_level + && s.base_array_layer == t.base_array_layer + && a.src_offset == b.src_offset + && a.extent == b.extent; + } let layout = |copies: &ShadowCopies| match &copies.source { ShadowSource::Bytes { key, @@ -456,6 +603,19 @@ impl ShadowCopies { } } + /// Whether what the commands write through the shadow goes back into its truth as a merge + /// (`shadow_merge.rs`): a buffer's bytes that another writer may write beside the commands' + /// writes while a command buffer runs, whose writes to texels the commands left Metal keeps; + /// never copied back over those texels (the module's rules). That is every buffer's bytes but + /// a tracked `Private` or `Memoryless` buffer's the runtime made: the CPU writes the others + /// (a `Shared` or `Managed` buffer's, host pages, the caller's own `VkBuffer`'s memory), and + /// another queue's commands an untracked buffer's, which the tracker leaves to the program. An + /// image's shadow, a turned one and two planes take no merge ([`unmerged`](Self::unmerged)), + /// and writes Metal drops go back no way. + pub(super) fn merges_back(&self) -> bool { + let bytes = matches!(&self.source, ShadowSource::Bytes { .. }); + let other_writer = self.backing != Backing::PrivateBuffer || !self.tracked; + bytes && other_writer && !self.drops_writes && self.unmerged().is_none() /// Whether two shadowed textures copy some of the same truth. fn shares_truth(&self, other: &ShadowCopies) -> bool { let ((key, range), (other_key, other_range)) = (self.truth(), other.truth()); @@ -569,7 +729,8 @@ pub(super) enum Step { Into, /// From the shadow back into the buffer. Back, - /// The shadow kept, before a command that writes its bytes two ways. + /// command since the last copy back that writes through it where it merges back + /// ([`ShadowCopies::merges_back`]). Keep(M), /// After that command, the bytes it changed through the texture merged into the buffer's. Merge(M), @@ -587,12 +748,74 @@ pub(super) struct ShadowCopy> { /// nowhere else ([`ShadowUse::area`]), or a copy in of them alone, where the command reads /// and writes no other texel of it ([`ShadowUse::loads`]); `None` for every texel. pub(super) area: Option<[u32; 4]>, + /// Why a copy in is made, as `WorkCounts` counts its texels; `None` for every other step. + pub(super) cause: Option, +} + +/// Why a copy in is made, as `WorkCounts` counts its texels. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum CopyCause { + /// The encoder's first copy in of the texture: before the first command of the encoder that + /// uses it, or the first after work it records apart ([`ShadowSync::leave`]). Every later one + /// follows a change of the truth, or a command that needs texels the image does not hold + /// (`WorkCounts::shadow_texels_first_copied_in`). + First, + /// A later copy in before a command that needs texels outside the rectangle the image holds + /// (its last copy in's, [`ShadowUse::loads`]), the truth unchanged there or not + /// (`WorkCounts::shadow_texels_recopied_beyond_held`). + BeyondHeld, + /// The truth changed since the image's copy in, other than by writes within a rectangle that + /// left it stale there alone, for the reason given + /// (`WorkCounts::shadow_texels_recopied_after_changes`). + Changed(Lost), /// A copy in of the texels writes [`Within`] a rectangle changed since the image's copy in, - /// `area` the rectangle bounding them (the module's rules). - pub(super) bounded: bool, + /// [`ShadowCopy::area`] the rectangle bounding them (the module's rules, + /// `WorkCounts::shadow_texels_bounded_copied_in`). + Bounded, +} + +/// Why a shadow's image no longer holds the truth as the encoder's commands left it, so the next +/// command that uses the texture copies it in again ([`CopyCause::Changed`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Lost { + /// Another shadowed texture over the same truth was copied back or merged. + OtherShadow, + /// Its own merge after a command that wrote the truth two ways. + TwoWays, + /// A command wrote the truth another way (its bytes, or an image's levels and layers). + Written, + /// A command wrote the truth within a rectangle ([`Within`]) where that leaves the image + /// stale nowhere alone: the writes' texture has no shadow, or the image is written, kept, or + /// its texels are laid out otherwise. + Within, + /// A command wrote through it where Metal drops the writes. + Dropped, } impl ShadowCopy { + /// Whether the copy writes the texture's truth: a copy back or a merge. + pub(super) fn writes_truth(&self) -> bool { + matches!(self.step, Step::Back | Step::Merge(_)) + } + + /// The texels a copy in moves, as `record` cuts it, of a 2D texture's image over a buffer's + /// bytes (as [`texels_in`](Self::texels_in) counts them) or of an image's shadow (its every + /// region's, or its one region's inside [`area`](Self::area)): 0 for every other copy. + pub(super) fn texels_copied_in(&self) -> u64 { + match (&self.step, &self.copies.source) { + (Step::Into, ShadowSource::Image { regions, .. }) => { + match (self.area, self.copies.cuts(), one_image_copy(regions)) { + (Some(area), true, Some(region)) => image_part_of(region, area) + .as_ref() + .map_or(0, image_copy_texels), + _ => regions.iter().map(image_copy_texels).sum(), + } + } + (Step::Into, _) => self.texels_in(), + _ => 0, + } + } + /// The texels a copy back of a 2D texture's image over a buffer's bytes moves (its every /// region's, or its one region's inside [`area`](Self::area)): 0 for every other copy. pub(super) fn texels_back(&self) -> u64 { @@ -623,20 +846,29 @@ impl ShadowCopy { else { return 0; }; - let texels = |r: &vk::BufferImageCopy| { - let e = r.image_extent; - u64::from(e.width) * u64::from(e.height) * u64::from(e.depth) - }; // As `record` cuts the region. match (self.area, staging, regions.as_slice(), texel) { - (Some(area), None, [region], Some(texel)) => { - part_of(region, area, *texel).as_ref().map_or(0, texels) - } - _ => regions.iter().map(texels).sum(), + (Some(area), None, [region], Some(texel)) => part_of(region, area, *texel) + .as_ref() + .map_or(0, buffer_copy_texels), + _ => regions.iter().map(buffer_copy_texels).sum(), } } } +/// The texels a copy of `region` moves between a buffer and an image. +fn buffer_copy_texels(region: &vk::BufferImageCopy) -> u64 { + let e = region.image_extent; + u64::from(e.width) * u64::from(e.height) * u64::from(e.depth) +} + +/// The texels a copy of `region` moves between two images: every slice's. +fn image_copy_texels(region: &vk::ImageCopy) -> u64 { + let e = region.extent; + let layers = u64::from(region.src_subresource.layer_count); + u64::from(e.width) * u64::from(e.height) * u64::from(e.depth) * layers +} + impl ShadowCopy { /// The dispatch that takes this copy where it is a copy back that dispatches /// (`shadow_copy_back.rs`): a one-slice 2D texture's image over a buffer's bytes, copied in @@ -669,6 +901,36 @@ impl ShadowCopy { CopyBack::new(device, *words, buffer.raw(), ®ion) } + /// The texels a copy in of a one-region, one-slice 2D texture's image over a buffer's bytes + /// copied in place moves, as `record` cuts its region (where they lie in the buffer, and in + /// the image): what a merge's keep may take with it (`ShadowMerge::keep_in`). `None` for any + /// other copy, or one that moves no texel. + pub(super) fn copied_region(&self) -> Option { + let ( + Step::Into, + ShadowSource::Bytes { + target: + ShadowTarget::Image { + regions, + staging: None, + texel: Some(texel), + .. + }, + .. + }, + ) = (&self.step, &self.copies.source) + else { + return None; + }; + let [region] = regions.as_slice() else { + return None; + }; + match self.area { + Some(area) => part_of(region, area, *texel), + None => Some(*region), + } + } + /// The uses of the dispatch that takes a copy back ([`dispatched`](Self::dispatched)): a /// sampled read of the shadow and a storage write of the buffer's bytes, in the compute /// stage. @@ -698,8 +960,9 @@ impl ShadowCopy { } /// The stages the copy runs in: a rotated texture's copies dispatch the rotation kernel, a - /// heap's two-plane texture's the two-plane kernel, and a tiled heap texture's the tiled - /// texel kernel (its keep too). + /// heap's two-plane texture's the two-plane kernel, a tiled heap texture's the tiled texel + /// kernel (its keep too), and a keep that dispatches the copy back's kernel + /// (`ShadowMerge::dispatches`) that kernel. pub(super) fn stages(&self) -> vk::PipelineStageFlags2 { let tiled = matches!(self.copies.target(), Some(ShadowTarget::Tiled { .. })); let rotated = tiled @@ -716,7 +979,7 @@ impl ShadowCopy { Step::Into | Step::Back if rotated => { vk::PipelineStageFlags2::TRANSFER | vk::PipelineStageFlags2::COMPUTE_SHADER } - Step::Keep(_) if tiled => { + Step::Keep(ref merge) if tiled || merge.dispatches() => { vk::PipelineStageFlags2::TRANSFER | vk::PipelineStageFlags2::COMPUTE_SHADER } Step::Into if converted => { @@ -793,9 +1056,10 @@ impl ShadowCopy { /// /// # Safety /// - /// `command_buffer` is recording, outside a render pass; the buffer and the shadow are live - /// until it completes, and an image is in the `GENERAL` layout. - pub(super) unsafe fn record(&self, device: &Vk, command_buffer: vk::CommandBuffer) { + /// `command_buffer` is recording, outside a render pass, after a barrier that orders the copy + /// after what precedes it; the buffer and the shadow are live until it completes, and an + /// image is in the `GENERAL` layout; `back` is this copy's `staged_back`, over the buffer's + /// `VkBuffer` as it is now. let c = &self.copies; let into_shadow = match &self.step { Step::Into => true, @@ -883,8 +1147,17 @@ impl ShadowCopy { } return; } + // A copy in cut to a rectangle moves its texels alone; a copy back moves every + // texel (`ShadowCopies::cuts_back`). let regions: Vec = if into_shadow { - regions.clone() + match (self.area, c.cuts(), one_image_copy(regions)) { + (Some(area), true, Some(region)) => match image_part_of(region, area) { + Some(part) => vec![part], + // The command reads no texel. + None => return, + }, + _ => regions.clone(), + } } else { regions .iter() @@ -1073,6 +1346,48 @@ pub(super) fn part_of( }) } +fn one_image_copy(regions: &[vk::ImageCopy]) -> Option<&vk::ImageCopy> { + match regions { + [region] if region.src_subresource.layer_count == 1 && region.extent.depth == 1 => { + Some(region) + } + _ => None, + } +} + +/// `region` (one level and one slice of an image, copied into the same texels of its shadow) cut +/// to the texels inside `[x0, y0, x1, y1)`: `None` where none lies there. +pub(super) fn image_part_of( + region: &vk::ImageCopy, + [x0, y0, x1, y1]: [u32; 4], +) -> Option { + let extent = region.extent; + let (x1, y1) = (x1.min(extent.width), y1.min(extent.height)); + if x0 >= x1 || y0 >= y1 { + return None; + } + let moved = |offset: vk::Offset3D| vk::Offset3D { + x: offset.x + x0 as i32, + y: offset.y + y0 as i32, + z: offset.z, + }; + Some(vk::ImageCopy { + src_offset: moved(region.src_offset), + dst_offset: moved(region.dst_offset), + extent: vk::Extent3D { + width: x1 - x0, + height: y1 - y0, + depth: extent.depth, + }, + ..*region + }) +} + +/// Whether a command writes through `shadow` without replacing every texel, where it merges back +/// ([`ShadowCopies::merges_back`]): kept and merged back (the module's rules), as a command that +/// writes them two ways too ([`two_ways`]) is. +fn merged_back(shadow: &ShadowUse) -> bool { + shadow.writes && !shadow.overwrites && shadow.copies.merges_back() /// Whether a command that uses the shadowed textures `shadows` and has `uses` writes the bytes /// of `shadows[i]` two ways: through it, and through `uses` or another shadowed texture over /// them (the module's rules). @@ -1172,13 +1487,23 @@ pub(super) fn join(shadows: &mut Vec, shadow: &ShadowUse) { } } +/// Where a shadowed texture's image stands against its truth in an encoder. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Standing { + /// Not copied in since the encoder met the texture: its next copy in is the encoder's first. + Unread, + /// The image holds the buffer's bytes as the encoder's commands so far left them, inside + /// `held`. + Current, + /// The truth changed since the image's copy in, for the reason given. + Lost(Lost), +} + /// A shadowed texture an encoder used, and where its image stands. struct Entry { copies: Arc, - /// The image holds the buffer's bytes as the encoder's commands so far left them, inside - /// `held`. - current: bool, - /// Where the image holds them when `current`: the texels inside `[x0, y0, x1, y1)`, all its + standing: Standing, + /// Where the image holds them when [`Standing::Current`]: the texels inside `[x0, y0, x1, y1)`, all its /// last copy in moved ([`ShadowUse::loads`]); `None` for every texel. Its other texels are /// whatever the image held before, which no command of the encoder reads and no copy back /// moves: a command that needs them current copies back what was written and copies every @@ -1189,11 +1514,15 @@ struct Entry { /// Where those commands wrote through it, where they bound it ([`ShadowUse::area`]). area: Option<[u32; 4]>, /// The scratch the image was kept in before a command that writes its bytes two ways, until - /// the merge after it. + /// through a texture that merges back ([`ShadowCopies::merges_back`]), until the next copy + /// back, which is then a merge. merge: Option, - /// When `current`, the rectangle bounding the texels whose bytes changed since the image's + /// The scratch of the texture's keeps where it merges back, made at the first + /// When [`Standing::Current`], the rectangle bounding the texels whose bytes changed since the image's /// copy in, where only writes [`Within`] it changed them (the module's rules): the next - /// command that uses the texture copies those in first. `None` where none changed. + /// command that uses the texture copies those in first, or those of them it reads where it + /// reads only inside a rectangle and writes none, the rest left here. `None` where none + /// changed. stale: Option<[u32; 4]>, } @@ -1202,12 +1531,24 @@ impl Entry { /// current but there ([`Entry::stale`]): it holds the bytes, and no write of its own or keep, /// and its texels are `texels`' ([`ShadowCopies::same_texels`]). fn stale_within(&self, texels: &ShadowCopies) -> bool { - self.current && !self.dirty && self.merge.is_none() && self.copies.same_texels(texels) + self.standing == Standing::Current + && !self.dirty + && self.merge.is_none() + && self.copies.same_texels(texels) + } + + /// Note a change of the truth for `lost`: the image no longer holds it. One not copied in + /// yet stays so, and one that lost it already keeps the first reason. + fn lose(&mut self, lost: Lost) { + if self.standing == Standing::Current { + self.standing = Standing::Lost(lost); + } } /// Note a change of the bytes of `texels`' texels inside `area` (`[x0, y0, x1, y1)`), or - /// anywhere where `area` is `None`: the image is stale there, or no longer current. - fn changed(&mut self, texels: &ShadowCopies, area: Option<[u32; 4]>) { + /// anywhere where `area` is `None`, for `lost`: the image is stale there, or no longer + /// current. + fn changed(&mut self, texels: &ShadowCopies, area: Option<[u32; 4]>, lost: Lost) { match area.filter(|_| self.stale_within(texels)) { Some(area) => { self.stale = Some(match self.stale { @@ -1220,7 +1561,7 @@ impl Entry { None => area, }); } - None => self.current = false, + None => self.lose(lost), } } } @@ -1281,6 +1622,29 @@ fn meet([a0, a1, a2, a3]: [u32; 4], [b0, b1, b2, b3]: [u32; 4]) -> Option<[u32; (r[0] < r[2] && r[1] < r[3]).then_some(r) } +/// The rectangle bounding the texels of `a` outside `b`, each `[x0, y0, x1, y1)`; `None` where `b` +/// covers `a`. +fn outside(a: [u32; 4], b: [u32; 4]) -> Option<[u32; 4]> { + let ([a0, a1, a2, a3], [b0, b1, b2, b3]) = (a, b); + if meet(a, b).is_none() { + return Some(a); + } + let (across, down) = (b0 <= a0 && a2 <= b2, b1 <= a1 && a3 <= b3); + // Where `b` crosses `a` from side to side, the texels left are the rows above and below it; + // from top to bottom, the columns beside it. One of the two alone is a rectangle of its own. + let left = match (across, down) { + (true, true) => return None, + (true, false) => (a1 < b1, b3 < a3, [a0, a1, a2, b1], [a0, b3, a2, a3]), + (false, true) => (a0 < b0, b2 < a2, [a0, a1, b0, a3], [b2, a1, a2, a3]), + (false, false) => return Some(a), + }; + match left { + (true, false, before, _) => Some(before), + (false, true, _, after) => Some(after), + _ => Some(a), + } +} + /// Whether an image holding the buffer's texels inside `held` (`None` every texel) holds those /// inside `needs` (`None` every texel). fn holds(held: Option<[u32; 4]>, needs: Option<[u32; 4]>) -> bool { @@ -1307,7 +1671,32 @@ impl Default for ShadowSync { } } -impl ShadowSync { + + /// How many of the textures the encoder used share their truth with one it used before + /// (another texture over the same bytes): each copies the texels in apart + /// (`WorkCounts::shadows_sharing_truth`). + pub(super) fn sharing_truth(&self) -> usize { + let entries = &self.entries; + (1..entries.len()) + .filter(|&i| { + (entries[..i].iter()).any(|earlier| earlier.copies.shares_truth(&entries[i].copies)) + }) + .count() + } +/// What a merge's scratch keeps of a shadow's texels (`shadow_merge.rs`): the rectangle +/// `[x0, y0, x1, y1)` its keep, its copy of the changed texels and its merge are cut to, or `None` +/// for every texel. +pub(super) trait KeptArea { + fn kept_area(&self) -> Option<[u32; 4]>; +} + +impl KeptArea for Arc { + fn kept_area(&self) -> Option<[u32; 4]> { + self.area() + } +} + +impl ShadowSync { /// The entry of `copies`, made when the encoder had none. fn entry(&mut self, copies: &Arc) -> usize { match self @@ -1319,7 +1708,7 @@ impl ShadowSync { None => { self.entries.push(Entry { copies: Arc::clone(copies), - current: false, + standing: Standing::Unread, held: None, dirty: false, area: None, @@ -1333,19 +1722,20 @@ impl ShadowSync { /// Copy back entry `i` (dirty): its image's bytes replace the buffer's, so every other /// texture over them is no longer current, or, where the copy back covers a rectangle of - /// texels laid out as its own, stale there alone (the module's rules). One kept before a - /// command that wrote its bytes two ways is merged instead, and is then no longer current - /// either: the buffer holds the other way's writes too. A copy back covers only the area the - /// commands wrote in, where they bound it: the image's other texels are what the last copy - /// in left, which the buffer still holds (a write of its bytes another way leaves the image - /// stale, and copies in again before the next use). + /// either, as the buffer holds the other way's writes too, and leaves every other texture + /// over the bytes no longer current; one kept as it merges back still holds what the + /// encoder's commands left in them, and its merge changes only words they changed through + /// it, inside the area they wrote in where they bound it, so it leaves the others stale there + /// alone, as a copy back of that area does. A copy back covers only the fn copy_back(&mut self, i: usize, copies: &mut Vec>) { let entry = &mut self.entries[i]; + let two_ways = entry.two_ways; let step = match &entry.merge { Some(merge) => { let merge = merge.clone(); entry.merge = None; - entry.current = false; + if two_ways { + entry.lose(Lost::TwoWays); Step::Merge(merge) } None => Step::Back, @@ -1354,6 +1744,11 @@ impl ShadowSync { Step::Back => entry.area, _ => None, }; + // Where the buffer's bytes may have changed for the other textures over them. + let changed = match step { + Step::Merge(_) if two_ways => None, + _ => entry.area, + }; entry.dirty = false; entry.area = None; let written = Arc::clone(&entry.copies); @@ -1362,11 +1757,11 @@ impl ShadowSync { step, kept: false, area, - bounded: false, + cause: None, }); for (j, other) in self.entries.iter_mut().enumerate() { if j != i && other.copies.shares_truth(&written) { - other.changed(&written, area); + other.changed(&written, changed, Lost::OtherShadow); } } } @@ -1374,8 +1769,15 @@ impl ShadowSync { /// The copies to record, in order, before a command that uses the shadowed textures /// `shadows` and has `uses` (every use of the command, the textures' among them): merges of /// the textures kept before the command before, copies back of what the command touches, - /// copies in of what it uses, and a keep of each texture it writes two ways, in a scratch - /// `merge` makes. Refused, changing nothing, as `merge` refuses, and for a command that + /// copies in of what it uses, a keep of each texture it writes through that merges back, where + /// none is kept since the last copy back, and a keep of each texture it writes two ways, each + /// in a scratch `merge` makes (told whether the command writes the bytes two ways, and the + /// rectangle of texels it is to keep, `None` for every texel). Where the texture merges back, + /// the scratch keeps the rectangle the command writes in, where + /// it bounds that and the copies are cut to rectangles ([`ShadowUse::area`]); a later command + /// that writes outside what the encoder's scratch keeps takes a scratch of the rectangle + /// bounding both, after a merge of what was kept in the last. Refused, changing nothing, as + /// `merge` refuses, and for a command that /// writes an image two ways, through a view's shadow of it and another alias, which no merge /// serves (`Unsupported`, `Feature::ViewFormatReinterpretation`), or a rotated texture's bytes /// two ways (`NotImplemented(RotatedTexture)`). @@ -1383,7 +1785,7 @@ impl ShadowSync { &mut self, shadows: &[ShadowUse], uses: &[Use], - mut merge: impl FnMut(&ShadowCopies) -> Result, + mut merge: impl FnMut(&ShadowCopies, bool, Option<[u32; 4]>) -> Result, ) -> Result>, Error> { // A copy back of an image's shadow would replace the other alias's writes, and only a // buffer's bytes laid out as the texture's are merged: such a command is refused before @@ -1396,11 +1798,44 @@ impl ShadowSync { } } let mut kept = Vec::new(); + // The textures the command writes through, its bytes another way not, that merge back: + // kept in a scratch of the encoder's, made at the first such command. + let mut merged_kept = Vec::new(); for (i, shadow) in shadows.iter().enumerate() { if two_ways(shadows, i, uses) { - kept.push((Arc::clone(&shadow.copies), merge(&shadow.copies)?)); + kept.push(( + Arc::clone(&shadow.copies), + merge(&shadow.copies, true, None)?, + )); + } else if merged_back(shadow) { + merged_kept.push(Arc::clone(&shadow.copies)); + // The texels the command writes, where it bounds them and the copies are cut so. + let writes = shadow.area.filter(|_| shadow.copies.cuts_back()); + let scratch = self + .entries + .iter() + .find(|e| e.copies.shadow_key == shadow.copies.shadow_key) + .and_then(|e| e.scratch.as_ref()); + let area = match scratch { + Some(scratch) if holds(scratch.kept_area(), writes) => continue, + Some(scratch) => bounding(scratch.kept_area(), writes), + None => writes, + }; + scratches.push(( + Arc::clone(&shadow.copies), + merge(&shadow.copies, false, area)?, + )); } } + // A texture kept in a scratch that does not keep what the command writes: merged before + // its keep in the new one. + let mut regrown = Vec::new(); + let entry = &mut self.entries[i]; + if entry.merge.is_some() && !entry.two_ways { + regrown.push(copies.shadow_key); + } + entry.scratch = Some(scratch); + } let mut copies = Vec::new(); // Merge what the command before wrote two ways; copy back what this one reads or writes // another way: through the buffer's bytes, or through another texture over them that is @@ -1415,11 +1850,19 @@ impl ShadowSync { shadow.copies.shadow_key != entry.shadow_key && shadow.copies.shares_truth(entry) }); - if touched || self.entries[i].merge.is_some() { + let regrows = regrown.contains(&entry.copies.shadow_key); + // Written since its last copy back with nothing kept (by a command that replaced + // every texel), and kept below: copied back first, as the merge after the keep takes + // only the words changed since it, which would leave those writes out. + let unkept = entry.merge.is_none() + && (merged_kept.iter()).any(|kept| kept.shadow_key == entry.copies.shadow_key); + if touched || regrows || unkept || (entry.merge.is_some() && entry.two_ways) { self.copy_back(i, &mut copies); } } for shadow in shadows { + // Made here, or for a keep's scratch above: not copied in yet, so its copy in is the + // encoder's first. let i = self.entry(&shadow.copies); let two_ways = kept .iter() @@ -1427,50 +1870,59 @@ impl ShadowSync { let overwrites = shadow.overwrites && !two_ways; // The texels the command needs as the buffer holds them: those it reads, and those // it writes (which a copy back moves), where it bounds both and the copies are cut to - // a rectangle; every texel where it writes the bytes two ways, as the merge after it - // compares every texel the keep took. + // a rectangle; every texel where it writes through a shadow whose copies back move + // every texel, or writes the bytes two ways, as the merge after it compares every + // texel the keep took. let needs = match two_ways || !shadow.copies.cuts() { true => None, + false if shadow.writes && !shadow.copies.cuts_back() => None, false if shadow.writes => bounding(shadow.loads, shadow.area), false => shadow.loads, }; let entry = &self.entries[i]; - if entry.current && !overwrites && !holds(entry.held, needs) { - // The image holds the buffer's texels only inside its last copy in's rectangle: - // what the encoder wrote through it goes back first, then the copy in below - // moves what this command needs. - if entry.dirty { - self.copy_back(i, &mut copies); - } - self.entries[i].current = false; + let beyond_held = + entry.standing == Standing::Current && !overwrites && !holds(entry.held, needs); + // The image holds the buffer's texels only inside its last copy in's rectangle: what + // the encoder wrote through it goes back first, then the copy in below moves what + // this command needs. + if beyond_held && entry.dirty { + self.copy_back(i, &mut copies); } let entry = &mut self.entries[i]; - if !entry.current { + let cause = match entry.standing { + _ if beyond_held => Some(CopyCause::BeyondHeld), + Standing::Current => None, + Standing::Unread => Some(CopyCause::First), + Standing::Lost(lost) => Some(CopyCause::Changed(lost)), + }; + if let Some(cause) = cause { if !overwrites { copies.push(ShadowCopy { copies: Arc::clone(&shadow.copies), step: Step::Into, kept: shadow.kept, area: needs, - bounded: false, + cause: Some(cause), }); } - entry.current = true; + entry.standing = Standing::Current; entry.held = needs; entry.stale = None; } // The texels writes within a rectangle changed since the copy in: those alone. A // command that reads only the texels inside a rectangle and writes none takes those of - // them inside it alone: the image then holds the buffer's texels there, inside what it - // held, which is all it claims from then on. + // them inside it alone, and the rest stay changed, for the next command that reads + // them: the image holds the buffer's texels everywhere else it held them. if let Some(stale) = entry.stale { - entry.stale = None; let area = match (shadow.writes, needs) { (false, Some(reads)) => { - entry.held = Some(reads); + entry.stale = outside(stale, reads); meet(stale, reads) } - _ => Some(stale), + _ => { + entry.stale = None; + Some(stale) + } }; if let (false, Some(area)) = (overwrites, area) { copies.push(ShadowCopy { @@ -1478,7 +1930,7 @@ impl ShadowSync { step: Step::Into, kept: shadow.kept, area: Some(area), - bounded: true, + cause: Some(CopyCause::Bounded), }); } } @@ -1487,6 +1939,9 @@ impl ShadowSync { entry.held = None; } } + // copy in read, over what another writer may have written since. + for shadow in merged_kept { + cause: None, for (shadow, merge) in kept { let i = self.entry(&shadow); self.entries[i].merge = Some(merge.clone()); @@ -1495,7 +1950,7 @@ impl ShadowSync { step: Step::Keep(merge), kept: false, area: None, - bounded: false, + cause: None, }); } Ok(copies) @@ -1517,13 +1972,13 @@ impl ShadowSync { let copies = Arc::clone(&entry.copies); let writes = |used: &Use| !used.write.is_empty() && copies.meets(used); if uses.iter().any(writes) { - entry.current = false; + entry.lose(Lost::Written); continue; } for part in within.iter().filter(|part| part.uses.iter().any(writes)) { match &part.texels { - Some(texels) => entry.changed(texels, Some(part.area)), - None => entry.current = false, + Some(texels) => entry.changed(texels, Some(part.area), Lost::Within), + None => entry.lose(Lost::Within), } } } @@ -1532,7 +1987,7 @@ impl ShadowSync { // Writes Metal drops are not copied back, and the image no longer holds the bytes. let entry = &mut self.entries[i]; match shadow.copies.drops_writes { - true => entry.current = false, + true => entry.lose(Lost::Dropped), false => { entry.area = match entry.dirty { true => bounding(entry.area, shadow.area), diff --git a/crates/metal2vulkan-runtime/src/shadow_copy_back.rs b/crates/metal2vulkan-runtime/src/shadow_copy_back.rs index 5b14d77ba..df3a2b2d6 100644 --- a/crates/metal2vulkan-runtime/src/shadow_copy_back.rs +++ b/crates/metal2vulkan-runtime/src/shadow_copy_back.rs @@ -6,10 +6,17 @@ //! `vkCmdCopyImageToBuffer` on every device. On a device measured to run that copy slower than a //! dispatch that stores the same words, the shadow of a one-level, one-slice 2D texture whose //! texel is 4, 8 or 16 bytes, copied in place, is made `MUTABLE_FORMAT` with the unsigned-integer -//! format of its texel's width listed and sampled usage ([`with_word_view`]), and its copies back -//! are one dispatch of `bind::shadow_copy_back_module` each: invocation `(x, y)` fetches texel -//! `(x0 + x, y0 + y)` through that view and stores its words at the texel's place in the buffer -//! ([`CopyBack`]). The copies in stay copies. +//! format of its texel's width listed (`R32_UINT`, `R32G32_UINT` or `R32G32B32A32_UINT`), and +//! sampled usage ([`with_word_view`]), and its copies back are one dispatch of +//! `bind::shadow_copy_back_module` each: invocation `(x, y)` fetches texel `(x0 + x, y0 + y)` +//! through that view and stores its words at the texel's place in the buffer ([`CopyBack`]). A +//! merge's copy of such a shadow into its scratch before the commands, which stores the same +//! texels laid out the same way, is such a dispatch too, and the merge after them fetches the +//! texels the commands left through the view rather than copy them out (`shadow_merge.rs`). On a +//! device also measured to take a merged texture's copy in and its keep faster as one dispatch +//! (`DriverFact::ShadowCopyInDispatchFaster`), the view stores too, and the copy in of the +//! texels a keep keeps, right before it, is that dispatch (`shadow_copy_in.rs`); the other copies +//! in stay copies. //! //! **Exact.** The dispatch writes the bytes the copy writes and no other: the texels inside the //! copy's region (every texel, or the rectangle a pass's scissors bound, `ShadowCopy::area`), each @@ -18,8 +25,17 @@ //! locations irrespective of the format, with only the interpretation of the bit pattern //! changing" (`VkImageViewCreateInfo`): the texel's format and its unsigned-integer twin of its //! width share a compatibility class, and the twin's components are unconverted unsigned -//! integers, so the words a fetch returns are the texel's bytes in memory order, which the copy -//! writes. +//! integers, so the components a fetch returns are the texel's bytes in memory order (a 4-byte +//! texel's word through `R32_UINT`, its four bytes through `R8G8B8A8_UINT`, which the kernel +//! packs into its word; a wider texel's words), which the copy writes. +//! +//! **Storage usage.** Only on a device with `DriverFact::ShadowCopyInDispatchFaster`, where it +//! stores the view's format, and but for a shadow of a single 32-bit channel's format +//! (`R32_UINT`, `R32_SINT`, `R32_SFLOAT`) whose image has no storage usage of its own; a 4-byte +//! texel's view is then `R8G8B8A8_UINT`. Storage usage beside a 32-bit single-channel format, the +//! image's own or a listed view's, may cost the image its compression where the device keeps +//! atomics apart from it (Mesa's ANV on gfx12.0 then makes the image without its aux surface, so +//! its clears are not fast). Such a shadow's copy in and keep stay two (`shadow_copy_in.rs`). //! //! **Synchronization.** The dispatch's uses are a sampled read of the shadow and a storage write //! of the buffer's bytes in `COMPUTE_SHADER`, which the encoder's tracker orders as any command's @@ -34,10 +50,11 @@ //! does not make: each copies back as before, the exact form every device takes. use super::image_plan::{compatible, ImageFacts, ImagePlan}; -use super::owned_kernel::{OwnedKernel, OwnedModule, OwnedSet, OwnedSets}; +use super::owned_kernel::{OwnedBinds, OwnedKernel, OwnedModule, OwnedSet}; use super::Device; +use crate::device::functions::Vk; use ash::vk; -use metal2vulkan::bind::ShadowCopyBackModule; +use metal2vulkan::bind::{ShadowCopyBackModule, ShadowTexelView}; use metal2vulkan::device::DriverFact; use metal2vulkan::vk::{Format, FormatFeatureFlags2, ImageCreateFlags, ImageUsageFlags}; @@ -48,8 +65,11 @@ use metal2vulkan::vk::{Format, FormatFeatureFlags2, ImageCreateFlags, ImageUsage #[derive(Clone, Copy, Debug)] pub(super) struct WordView { pub(super) view: vk::ImageView, - /// The texel's 4-byte words: 1, 2 or 4. - pub(super) words: u32, + /// Its format, as the kernels read it (its texel's words: 1, 2 or 4). + pub(super) texel: ShadowTexelView, + /// Whether the view is also a storage image, through which a merged texture's copy in and + /// keep dispatch (`shadow_copy_in.rs`): the module's storage usage. + pub(super) stores: bool, } /// Whether `device`'s shadows copy back by dispatch (the module docs). @@ -60,41 +80,67 @@ pub(super) fn dispatches(device: &Device) -> bool { .contains(&DriverFact::ShadowCopyBackDispatchFaster) } -/// The unsigned-integer format of a texel `bytes` wide that a [`WordView`] takes, and its words. -pub(super) fn word_format(bytes: u32) -> Option<(Format, u32)> { - match bytes { - 4 => Some((Format::R32_UINT, 1)), - 8 => Some((Format::R32G32_UINT, 2)), - 16 => Some((Format::R32G32B32A32_UINT, 4)), +/// Whether `device` takes a merged texture's copy in and its keep as one dispatch, its shadows' +/// views storing (the module's storage usage). +pub(super) fn dispatches_in(device: &Device) -> bool { + device + .properties() + .driver_facts + .contains(&DriverFact::ShadowCopyInDispatchFaster) +} + +/// The unsigned-integer format of a texel `bytes` wide that a [`WordView`] takes, and the view as +/// the kernels read it: a 4-byte texel's bytes where the view `stores`, else its word. +pub(super) fn word_format(bytes: u32, stores: bool) -> Option<(Format, ShadowTexelView)> { + match (bytes, stores) { + (4, true) => Some((Format::R8G8B8A8_UINT, ShadowTexelView::R8G8B8A8Uint)), + (4, false) => Some((Format::R32_UINT, ShadowTexelView::R32Uint)), + (8, _) => Some((Format::R32G32_UINT, ShadowTexelView::R32G32Uint)), + (16, _) => Some((Format::R32G32B32A32_UINT, ShadowTexelView::R32G32B32A32Uint)), _ => None, } } /// `plan`, a shadow's image, made to take its [`WordView`]: `MUTABLE_FORMAT`, with the /// unsigned-integer format of its texel's width listed beside its own (or none listed where it -/// takes any compatible format), and sampled usage (`EXTENDED_USAGE` where its own format is not -/// sampled); with that format and its words. `None`, `plan` unchanged, for a one-level, -/// one-slice 2D color image's texel of another width, a compressed block, or a device that does -/// not sample the integer format. +/// takes any compatible format), sampled usage, and, where `stores_in` (the device's +/// [`dispatches_in`]), storage usage where the device stores the integer format and the image has +/// it already or its own format is not a single 32-bit channel (the module's storage usage; +/// `EXTENDED_USAGE` where its own format takes either not); with that format, the view and +/// whether it stores. `None`, `plan` unchanged, for a one-level, one-slice 2D color image's texel +/// of another width, a compressed block, or a device that does not sample the integer format. pub(super) fn with_word_view( mut plan: ImagePlan, facts: &ImageFacts<'_>, -) -> (ImagePlan, Option<(Format, u32)>) { + stores_in: bool, +) -> (ImagePlan, Option<(Format, ShadowTexelView, bool)>) { let single = plan.levels == 1 && plan.layers == 1 && plan.extent[2] == 1; + let single_channel_word = matches!( + plan.format, + Format::R32_UINT | Format::R32_SINT | Format::R32_SFLOAT + ); + let storing = + stores_in && (plan.usage.contains(ImageUsageFlags::STORAGE) || !single_channel_word); let word = plan .format .block() - .and_then(|block| word_format(block.size)); + .and_then(|block| word_format(block.size, storing)); let sampled = FormatFeatureFlags2::SAMPLED_IMAGE; - let Some((format, words)) = word.filter(|&(format, _)| { + let Some((format, texel)) = word.filter(|&(format, _)| { single && compatible(plan.format, format, false) && facts.optimal(format).contains(sampled) }) else { return (plan, None); }; - if !facts.optimal(plan.format).contains(sampled) { + let storage = FormatFeatureFlags2::STORAGE_IMAGE; + let stores = storing && facts.optimal(format).contains(storage); + let own = facts.optimal(plan.format); + if !own.contains(sampled) || (stores && !own.contains(storage)) { plan.flags |= ImageCreateFlags::EXTENDED_USAGE; } plan.usage |= ImageUsageFlags::SAMPLED; + if stores { + plan.usage |= ImageUsageFlags::STORAGE; + } let any_format = plan.flags.contains(ImageCreateFlags::MUTABLE_FORMAT) && plan.view_formats.is_empty(); plan.flags |= ImageCreateFlags::MUTABLE_FORMAT; @@ -106,15 +152,16 @@ pub(super) fn with_word_view( plan.view_formats.push(format); } } - (plan, Some((format, words))) + (plan, Some((format, texel, stores))) } -/// One copy back's dispatch (the module docs): the kernel of its texel's width, its set (the -/// shadow's view and the buffer's bytes from the region's first texel, as they lie now), its -/// shape and its workgroups. The command buffer retains it until it completes. +/// One copy back's dispatch (the module docs): the kernel of its texel's width, its set 0 (the +/// shadow's view and the buffer's bytes from the region's first texel, as they lie now; pushed +/// where the device pushes, `OwnedBinds`), its shape and its workgroups. The command buffer +/// retains it until it completes. pub(super) struct CopyBack { kernel: OwnedKernel, - sets: OwnedSets, + binds: OwnedBinds, shape: [u8; 16], groups: [u32; 2], } @@ -133,7 +180,7 @@ impl CopyBack { return None; } let limits = &device.properties().description.limits; - let texel = 4 * u64::from(words.words); + let texel = 4 * u64::from(words.texel.words()); let extent = region.image_extent; let (width, height) = (extent.width, extent.height); let row = match region.buffer_row_length { @@ -164,17 +211,17 @@ impl CopyBack { let row_words = (row_bytes / 4) as u32; let first_word = ((first - offset) / 4) as u32; let kernel = device - .owned_kernel(OwnedModule::ShadowCopyBack(words.words)) + .owned_kernel(OwnedModule::ShadowCopyBack(words.texel)) .ok()?; let set = OwnedSet { images: vec![words.view], storage_images: Vec::new(), buffers: vec![(buffer, offset, range)], }; - let sets = OwnedSets::write_each(device, &[kernel], &[set]).ok()?; + let binds = OwnedBinds::new(device, &kernel, &[set]).ok()?; Some(CopyBack { kernel, - sets, + binds, shape: ShadowCopyBackModule::shape([x0, y0], width, row_words, first_word), groups, }) @@ -186,7 +233,7 @@ impl CopyBack { /// /// `command_buffer` is recording, outside a render pass; the shadow, its view and the buffer /// are live until it completes, and the shadow is in the `GENERAL` layout. - pub(super) unsafe fn record(&self, device: &ash::Device, command_buffer: vk::CommandBuffer) { + pub(super) unsafe fn record(&self, device: &Vk, command_buffer: vk::CommandBuffer) { // SAFETY: the caller's contract; the set binds the view and the bytes the region's // texels lie in, and the shape and workgroups stay inside both (checked in `new`). unsafe { @@ -195,14 +242,7 @@ impl CopyBack { vk::PipelineBindPoint::COMPUTE, self.kernel.pipeline, ); - device.cmd_bind_descriptor_sets( - command_buffer, - vk::PipelineBindPoint::COMPUTE, - self.kernel.layout, - 0, - &self.sets.sets, - &[], - ); + self.binds.bind(device, command_buffer, &self.kernel, 0); device.cmd_push_constants( command_buffer, self.kernel.layout, diff --git a/crates/metal2vulkan-runtime/src/shadow_copy_in.rs b/crates/metal2vulkan-runtime/src/shadow_copy_in.rs new file mode 100644 index 000000000..b1431a6c5 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/shadow_copy_in.rs @@ -0,0 +1,150 @@ +//! A merged shadowed texture's copy in and keep as one compute dispatch, where the device takes +//! them faster so (`DriverFact::ShadowCopyInDispatchFaster`). +//! +//! A shadowed texture over bytes another writer may write while a command buffer runs is merged +//! back (`shadow_merge.rs`): before the encoder's first command that writes through it, its +//! shadow is copied in from the buffer's bytes (`vkCmdCopyBufferToImage`, `shadow.rs`) and then +//! kept, its texels stored row after row in the merge's scratch (the copy back's dispatch on such +//! a device, `shadow_copy_back.rs`), with a barrier between the two. Where both move the same +//! rectangle of a one-region texture copied in place, with no copy of the shadow between them, +//! the encoder records them as one dispatch of `bind::shadow_copy_in_module` at the copy in +//! ([`CopyIn`]): invocation `(x, y)` reads texel `(x0 + x, y0 + y)`'s words from the buffer once, +//! stores them through the shadow's unsigned-integer view, its storage image +//! (`shadow_copy_back::WordView::stores`), and stores them at the texel's place in the kept part; +//! the keep records nothing (`WorkCounts::shadow_copies_in_dispatched`). +//! +//! **Exact.** The shadow holds the bytes the copy writes, and the kept part the words the keep +//! stores: Vulkan states that "Views of compatible formats will have the same mapping between +//! texel coordinates and memory locations irrespective of the format, with only the +//! interpretation of the bit pattern changing" (`VkImageViewCreateInfo`), and the view's +//! unsigned-integer components store their bits unconverted (a 4-byte texel's bytes, one a +//! component of its `R8G8B8A8_UINT` view). The kept part takes the words the +//! shadow takes, from the same read, as the keep after the copy took the shadow's: the merge after +//! the commands compares the texels with them alone. +//! +//! **Synchronization.** The dispatch's uses are a storage read of the buffer's bytes and storage +//! writes of the shadow and of the kept part in `COMPUTE_SHADER` (`ShadowMerge::keep_in_uses`), +//! which the encoder's tracker orders as any command's, before the commands that read the shadow. +//! +//! **Where the two stay.** A device without the fact (its shadows' views do not store), a merge +//! not cut to one rectangle in place, a copy in of another rectangle than the keep's, a copy of +//! the shadow between them, a texel of another width, a shadow whose view takes no storage (a +//! single 32-bit channel's format without storage usage of its own, `shadow_copy_back.rs`), a +//! region past the device's storage buffer range or workgroup counts, a kept part off the +//! storage buffer alignment, a buffer whose `VkBuffer` went, or a kernel the device does not +//! make: each records its copy in and its keep as before. + +use super::owned_kernel::{OwnedBinds, OwnedKernel, OwnedModule, OwnedSet}; +use super::shadow_copy_back::WordView; +use super::Device; +use crate::device::functions::Vk; +use ash::vk; +use metal2vulkan::bind::ShadowCopyInModule; + +/// One copy in and keep's dispatch (the module docs): the kernel of its texel's width, its set 0 +/// (the shadow's view, the buffer's bytes from the region's first texel and the kept part, as they +/// lie now; pushed where the device pushes, `OwnedBinds`), its shape and its workgroups. The +/// command buffer retains it until it completes. +pub(super) struct CopyIn { + kernel: OwnedKernel, + binds: OwnedBinds, + shape: [u8; 16], + groups: [u32; 2], +} + +impl CopyIn { + /// The dispatch on `device` that copies `region` of the buffer `buffer`'s `VkBuffer` (its + /// offset there, its row length, its texels' origin and extent in the shadow) into the shadow + /// through `words`, and its texels row after row into the kept part at `kept` (its `VkBuffer` + /// and where the part starts there); `None` where the copy and the keep take it (the module + /// docs). + pub(super) fn new( + device: &Device, + words: WordView, + buffer: vk::Buffer, + region: &vk::BufferImageCopy, + kept: (vk::Buffer, u64), + ) -> Option { + if buffer == vk::Buffer::null() || !words.stores { + return None; + } + let limits = &device.properties().description.limits; + let texel = 4 * u64::from(words.texel.words()); + let extent = region.image_extent; + let (width, height) = (extent.width, extent.height); + let row = match region.buffer_row_length { + 0 => width, + row => row, + }; + let [x0, y0] = [region.image_offset.x, region.image_offset.y].map(|o| o as u32); + let first = region.buffer_offset; + let align = limits.min_storage_buffer_offset_alignment.max(4); + let offset = first - first % align; + let row_bytes = u64::from(row) * texel; + let end = first + u64::from(height.max(1) - 1) * row_bytes + u64::from(width) * texel; + let range = end - offset; + let kept_range = u64::from(width) * u64::from(height) * texel; + let groups = ShadowCopyInModule::groups([width, height]); + let max_range = u64::from(limits.max_storage_buffer_range); + let fits = width > 0 + && height > 0 + && extent.depth == 1 + && first.is_multiple_of(4) + && kept.1.is_multiple_of(align) + && x0 < 1 << 16 + && y0 < 1 << 16 + && range <= max_range + && kept_range <= max_range + && groups[0] <= limits.max_compute_work_group_count[0] + && groups[1] <= limits.max_compute_work_group_count[1]; + if !fits { + return None; + } + // Each below `maxStorageBufferRange`, a `u32`. + let row_words = (row_bytes / 4) as u32; + let first_word = ((first - offset) / 4) as u32; + let kernel = device + .owned_kernel(OwnedModule::ShadowCopyIn(words.texel)) + .ok()?; + let set = OwnedSet { + images: Vec::new(), + storage_images: vec![words.view], + buffers: vec![(buffer, offset, range), (kept.0, kept.1, kept_range)], + }; + let binds = OwnedBinds::new(device, &kernel, &[set]).ok()?; + Some(CopyIn { + kernel, + binds, + shape: ShadowCopyInModule::shape([x0, y0], width, row_words, first_word), + groups, + }) + } + + /// Record the dispatch into `command_buffer`. + /// + /// # Safety + /// + /// `command_buffer` is recording, outside a render pass; the shadow, its view, the buffer and + /// the kept part are live until it completes, and the shadow is in the `GENERAL` layout. + pub(super) unsafe fn record(&self, device: &Vk, command_buffer: vk::CommandBuffer) { + // SAFETY: the caller's contract; the set binds the view, the bytes the region's texels + // lie in and the kept part, and the shape and workgroups stay inside them (checked in + // `new`). + unsafe { + device.cmd_bind_pipeline( + command_buffer, + vk::PipelineBindPoint::COMPUTE, + self.kernel.pipeline, + ); + self.binds.bind(device, command_buffer, &self.kernel, 0); + device.cmd_push_constants( + command_buffer, + self.kernel.layout, + vk::ShaderStageFlags::COMPUTE, + 0, + &self.shape, + ); + device.cmd_dispatch(command_buffer, self.groups[0], self.groups[1], 1); + } + } +} diff --git a/crates/metal2vulkan-runtime/src/shadow_merge.rs b/crates/metal2vulkan-runtime/src/shadow_merge.rs index 47f6f9ad4..ede7ccfc2 100644 --- a/crates/metal2vulkan-runtime/src/shadow_merge.rs +++ b/crates/metal2vulkan-runtime/src/shadow_merge.rs @@ -1,43 +1,84 @@ -//! A shadowed texture's writes merged into its buffer's bytes: one command that writes through a -//! shadowed texture (`shadow.rs`) and also writes the same buffer's bytes another way (through the -//! buffer, a texture buffer, or another texture over them). A copy back of the shadow would replace -//! the other write's bytes with the shadow's, where Metal keeps both writes when they touch -//! different bytes (Metal probe cases `k.two_ways_disjoint` and `k.two_ways_gap`, M3 Max and M4), -//! so the bytes the command changed through the texture are merged into the buffer's instead: +//! - **Merged back** (`ShadowCopies::merges_back`: a buffer's bytes but a tracked `Private` +//! buffer's): a copy back would write the texels the encoder's commands left with what the copy +//! in read, over another writer's writes to them while the command buffer ran (the CPU's, or +//! another queue's commands' over an untracked buffer's), where Metal writes only the texels a +//! command writes (`shadow.rs`). Merged in place of each copy back. //! //! - **Kept.** Before the command, after its copies in, the shadow's texels are copied into the //! *kept* part of a scratch buffer, laid out as in the buffer from the texture's first byte. -//! - **Merged.** After the command (before the encoder's next command, or as it ends), the -//! shadow's texels are copied into the *changed* part, and the buffer's bytes from the -//! texture's first to its last into the *current* part. One dispatch of the merge kernel then -//! takes, in each byte of the current part, the changed part's byte where it differs from the -//! kept one, and the current part is copied back into the buffer. A byte the command wrote -//! both ways is the texture's where its value changed: Metal leaves such a race unordered. -//! - **The scratch** is the command's, retained until its command buffer completes: three parts -//! of the texture's bytes rounded up to 256, in one buffer where the device's buffers take it -//! (else one each), all zero when made, so the bytes between the texture's rows, which no copy -//! of the shadow writes, are the same in the kept and changed parts. +//! - **Merged in place**, where the texture's first byte is a whole word of its buffer, its last +//! byte's word lies in the buffer, and the bytes lie in pages when the merge is planned (not +//! detached, `detach.rs`): the shadow's texels are copied into the *changed* part, and the merge +//! kernel binds the buffer's own bytes as its current buffer, from the texture's first byte +//! rounded down to 256 (the largest `minStorageBufferOffsetAlignment`), its first word pushed, +//! to its last byte's word. A word whose kept and changed words are equal is neither read nor +//! written: the bytes the commands left, those between the rows and those past the last texel +//! in its word keep whatever another writer wrote there meanwhile. In a word they changed, each +//! byte they changed becomes the texture's, and the others keep the buffer's: another writer's +//! write to the word's other bytes during the merge itself is a race the merge does not order. +//! - **Merged through a copy** elsewhere (a texture's first byte inside a word, through a staging +//! buffer, or a last word past its buffer; never recorded over detached bytes): the shadow's +//! texels are copied into the *changed* part, and the buffer's bytes from the texture's first to +//! its last into the *current* part. One dispatch of the merge kernel then takes, in each byte of +//! the current part, the changed part's byte where it differs from the kept one, and the current +//! part is copied back into the buffer: another writer's write to the texture's bytes between +//! that copy and the copy back is undone (`docs/FAST-PATHS.md`'s known gaps). +//! - **Cut.** Where a merge after commands that write through the texture goes in place over one +//! region's texels, the keep holds the rectangle the encoder's commands write in, where they +//! bound it (`ShadowUse::area`: a pass's attachment it loads, inside its draws' scissors), else +//! every texel, each row widened to whole words of the buffer. The keep and the changed copy +//! move that rectangle's texels, row after row, and the merge binds the buffer's rows it lies +//! in, in bands of rows no binding of which passes `maxStorageBufferRange` and no dispatch of +//! which passes `maxComputeWorkGroupCount[0]` workgroups, each band's kept rows from a multiple +//! of 256 bytes. +//! No command since the keep wrote a texel outside it: a later command that writes outside it +//! takes the merge of what was kept first, and a keep of the rectangle bounding both +//! (`ShadowSync::before`). (`WorkCounts::shadow_texels_kept`.) +//! - **Fetched.** Where the shadow has its unsigned-integer view (`shadow_copy_back.rs`: on a +//! device that runs a copy back faster as a compute dispatch, +//! `DriverFact::ShadowCopyBackDispatchFaster`, a one-slice image of 4-, 8- or 16-byte texels +//! copied in place), a cut merge copies nothing of the texels the commands left: its kernel +//! (`bind::shadow_merge_image_module`) fetches them from the shadow through the view, the same +//! words a copy of them would hold, and compares them with the kept part's, so the scratch is +//! the kept part alone (`WorkCounts::shadow_merges_fetched`). +//! - **Dispatched copies.** Where the shadow has that view, the copies of its texels into the +//! kept part, and into the changed part where the merge does not fetch, are that dispatch, each +//! storing the bytes the copy would (`WorkCounts::shadow_merge_copies_dispatched`). Where the +//! view also stores (`DriverFact::ShadowCopyInDispatchFaster`), a cut keep in place whose +//! texels the copy in before it moves, and no copy of the shadow between them, takes that copy +//! in with it: one dispatch reads the texels' words from the buffer and stores them in the +//! shadow, through the view, and in the kept part (`shadow_copy_in.rs`, +//! `WorkCounts::shadow_copies_in_dispatched`). +//! - **The scratch** is the command's, or for a merge in place of a copy back the encoder's, kept +//! in again at each keep after a merge (each merge ends with a barrier to everything after it), +//! retained until its command buffer completes: one, two or three parts of the texture's bytes +//! (a cut's rows) rounded up to 256, in one buffer where the device's buffers take it (else one //! - **The kernel** (`bind::shadow_merge_module`, one per device, `owned_kernel.rs`): one //! invocation per 4-byte word, the three parts bound as its kept, changed and current storage //! buffers, in windows of at most `maxStorageBufferRange` bytes and -//! `maxComputeWorkGroupCount[0]` groups, one dispatch each. +//! `maxComputeWorkGroupCount[0]` groups, one dispatch each; where it fetches +//! (`bind::shadow_merge_image_module`, one per texel width), one invocation per texel, the //! -//! It costs the scratch, three copies and the dispatches in place of one copy back, which the -//! runtime announces once per device (`shadow-merge`, performance). +//! A byte a command wrote both ways is the texture's where its value changed: Metal leaves such a use super::buffer::Buffer; use super::degradation::Degradation; +use super::device::lock; use super::error::{internal, Error}; -use super::owned_kernel::{OwnedKernel, OwnedModule, OwnedSets}; +use super::linear_merge::gcd; +use super::owned_kernel::{OwnedBinds, OwnedKernel, OwnedModule, OwnedSet}; use super::resource::ResourceKey; -use super::shadow::{ShadowCopies, ShadowSource}; +use super::shadow::{ShadowCopies, ShadowSource, ShadowTarget}; +use super::shadow_copy_back::{self, CopyBack, WordView}; +use super::shadow_copy_in::CopyIn; use super::tracker::{Access, Barrier, Use, UseRange}; -use super::values::ResourceOptions; +use super::values::{HazardTrackingMode, ResourceOptions}; use super::Device; use crate::device::functions::Vk; use ash::vk; use metal2vulkan::bind::ShadowMergeModule; use std::ops::Range; +use std::sync::{Arc, Mutex}; /// Bytes one workgroup merges: a word per invocation. const GROUP_BYTES: u64 = 4 * ShadowMergeModule::LOCAL_SIZE as u64; @@ -45,6 +86,37 @@ const GROUP_BYTES: u64 = 4 * ShadowMergeModule::LOCAL_SIZE as u64; /// `minStorageBufferOffsetAlignment` and of every texel's size. const PART_ALIGNMENT: u64 = 256; +/// The most scratch buffers a shadow keeps for its next merges ([`ScratchSpares`]): one a frame's +/// command buffer holds while the next frame's is encoded, and one more. +const KEPT_SCRATCHES: usize = 2; + +#[derive(Clone, Default)] + +impl ScratchSpares { + /// The smallest kept buffer of at least `length` bytes, taken. + fn take(&self, length: u64) -> Option { + let at = (spares.iter().enumerate()) + .filter(|(_, buffer)| buffer.length() >= length) + .min_by_key(|(_, buffer)| buffer.length()) + .map(|(at, _)| at)?; + Some(spares.swap_remove(at)) + } + + /// Keep `buffer` for a later merge, the smallest kept going past [`KEPT_SCRATCHES`]. + fn give(&self, buffer: Buffer) { + .min_by_key(|(_, buffer)| buffer.length()) + .map(|(at, _)| at) + drop(gone); + } +} + +enum Held { + /// One buffer, back to its shadow's spares as the merge goes. + Spare(Buffer, ScratchSpares), + /// A buffer per part, where the device's buffers take no single one. + Apart(Vec), +} + /// One part of the scratch: its `VkBuffer` and where it starts there. #[derive(Clone, Copy)] struct Part { @@ -61,28 +133,54 @@ struct Merged { first: u64, } -/// The scratch and the dispatches of one command's merge (the module docs). +/// The rectangle of a shadow's texels a merge is cut to (the module docs). +struct Cut { + /// `[x0, y0, x1, y1)`, its rows' first and last bytes whole words of the buffer. + area: [u32; 4], + /// Whether it is every texel, the cut made for a merge whose commands bound no area: its + /// keep holds every texel, as one not cut does. + whole: bool, + /// The shadow's image, and the copy of the rectangle's texels into a part from its start, row + /// after row (`bufferOffset` 0, `bufferRowLength` the rectangle's width). + image: vk::Image, + region: vk::BufferImageCopy, +} + +/// How a merge reads the shadow's texels after the commands (the module docs). +enum Changed { + /// Copied into the changed part (by the copy back's dispatch where the device runs one faster + /// and the shadow takes it, `shadow_copy_back.rs`), which `bind::shadow_merge_module` reads. + Copied { + part: Part, + dispatch: Option, + }, + /// Fetched from the shadow through its unsigned-integer view by + /// `bind::shadow_merge_image_module`: no copy. + Fetched, +} + pub(super) struct ShadowMerge { /// The texture's bytes. merged: Merged, - /// The kept, changed and current parts. - parts: [Part; 3], - /// The kept part's identity and range, for the tracker: kept before the command, read by the - /// merge after it. - kept: (ResourceKey, bool, Range), - /// The buffers the parts lie in, held until the command buffer completes. - _held: Vec, + /// The rectangle the keep, the changed copy and the merge are cut to; `None` for every texel. + cut: Option, + /// The texels the keep copies. + texels: u64, + /// How the merge reads the texels after the commands. + changed: Changed, + /// The keep's dispatch, where the device runs a copy back faster as one + keep_dispatch: Option, + held: Held, kernel: OwnedKernel, - /// One set per window, each binding the window of the three parts. - sets: OwnedSets, - /// Each window's workgroups and words. - groups: Vec<(u32, u32)>, + /// One set 0 per window, each binding the window of the parts (and the shadow's view, where + binds: OwnedBinds, + /// Each window's workgroups (along x and y) and push bytes. + dispatches: Vec<([u32; 2], [u8; 16])>, } impl ShadowMerge { - /// The scratch and the kernel's sets for a merge of the texture of `copies` on `device`, - /// announced once per device. Refused as `new_buffer` refuses the scratch. - pub(super) fn new(device: &Device, copies: &ShadowCopies) -> Result { + /// in place of a copy back; cut to the texels inside `area` (`[x0, y0, x1, y1)`), widened + /// to whole words of the buffer, where given and the merge goes in place over one region's let ( ShadowSource::Bytes { buffer, key, bytes, .. @@ -90,7 +188,7 @@ impl ShadowMerge { Some(first), ) = (&copies.source, copies.first_byte()) else { - // A command writing an image two ways is refused before (`ShadowSync::before`). + // only a buffer's bytes merge back (`ShadowCopies::merges_back`). return Err(internal("a merge of an image's shadow")); }; let merged = Merged { @@ -100,22 +198,74 @@ impl ShadowMerge { first, }; let span = merged.bytes.end - merged.bytes.start; - let part = span.next_multiple_of(PART_ALIGNMENT); + // A window binds the bytes only while they lie in pages: a detached buffer's `VkBuffer` is + // the device's stand-in, smaller than any window, and a binding past a buffer's size is + // invalid (VUID-VkDescriptorBufferInfo-range-00342). The encoder records nothing of a + // command over detached bytes (`EncoderCore::skips`), so their merge, planned through a + // copy, whose windows bind the scratch alone, is never recorded. + // In place, the merge reads and writes whole words, up to the last byte's word, which + // must lie in the buffer's bytes. + let rounded = span.next_multiple_of(4); + let in_place = copies.merges_back() + && first.is_multiple_of(4) + && first + rounded <= buffer.end() + && merged.buffer != vk::Buffer::null(); + let limits = &device.properties().description.limits; + let range = u64::from(limits.max_storage_buffer_range); + let [groups, groups_y] = + [0, 1].map(|axis| u64::from(limits.max_compute_work_group_count[axis])); + // A merge in place whose commands bound no area is cut to every texel where it can be: + // its parts hold the texels row after row, as a cut's do, and need no zero (below). A cut + // fetches the texels after the commands through the shadow's unsigned-integer view where + // it has one, and the rectangle lies within the kernel's origin and workgroups. + let cut = in_place + .then(|| cut_of(copies, area)) + .flatten() + .and_then(|(cut, geometry)| { + let view = word_view(copies).filter(|_| fetches(&cut, groups, groups_y)); + let rows = match view { + Some(_) => groups_y, + None => { + groups * u64::from(ShadowMergeModule::LOCAL_SIZE) / (geometry.row_bytes / 4) + } + }; + Some((cut, geometry, geometry.band(range, rows)?, view)) + }); + let part = match &cut { + Some((_, geometry, ..)) => geometry.rows * geometry.row_bytes, + None => rounded, + } + .next_multiple_of(PART_ALIGNMENT); + let fetched = cut.as_ref().and_then(|(.., view)| *view); + }; let options = ResourceOptions::private(); let place = |buffer: &Buffer, at: u64| { let (raw, at) = buffer.at(at); Part { raw, at } }; + let length = roles * part; + let counts = &device.shared().counts; // The kept part is the first `part` bytes of the first buffer either way. - let (held, parts) = if 3 * part <= device.properties().max_buffer_length { - let one = device.own_buffer(3 * part, options)?; - let parts = [0, 1, 2].map(|role| place(&one, role * part)); - (vec![one], parts) + // A cut's copies write every byte of its kept and changed parts the kernel reads (its + // rows of whole words, back to back), so its scratch needs no zero: one of the + // shadow's spares, else a new one unzeroed. Every other merge's scratch is new and + // zero. + let spares = copies.merge_scratch.clone(); + let one = match (&cut, cut.as_ref().and_then(|_| spares.take(length))) { + (Some(_), Some(spare)) => { + counts.shadow_merge_scratch_reused(); + spare + } + (Some(_), None) => device.unzeroed_buffer(length, HazardTrackingMode::Default)?, + (None, _) => { + counts.shadow_merge_scratch_zeroed(); + device.own_buffer(length, options)? + } + }; + (Held::Spare(one, spares), placed) } else { - let [kept, changed, current] = [(); 3].map(|()| device.own_buffer(part, options)); - let [kept, changed, current] = [kept?, changed?, current?]; - let parts = [place(&kept, 0), place(&changed, 0), place(¤t, 0)]; - (vec![kept, changed, current], parts) + counts.shadow_merge_scratch_zeroed(); + (Held::Apart(held), placed) }; let kept = { let first = held @@ -124,29 +274,115 @@ impl ShadowMerge { let (identity, range) = first.tracked(0..part); (identity.key, identity.tracked, range) }; - let limits = &device.properties().description.limits; - let window = (u64::from(limits.max_storage_buffer_range) / PART_ALIGNMENT * PART_ALIGNMENT) - .min(u64::from(limits.max_compute_work_group_count[0]) * GROUP_BYTES); - if window == 0 { - return Err(internal( - "a device whose storage buffers hold no merge window", - )); + } + }; + let mut sets = Vec::new(); + let set = |buffers: Vec<(vk::Buffer, u64, u64)>| OwnedSet { + storage_images: Vec::new(), + buffers, + }; + if let Some((cut, geometry, band, _)) = &cut { + // The rectangle's rows in bands, each band's kept and changed rows from a multiple of + // the alignment (`Geometry::band`), its current bytes bound from its first byte + // rounded down to it. + let Geometry { + first, + row_bytes, + pitch, + rows, + } = *geometry; + let words = row_bytes / 4; + let [x0, y0] = [cut.region.image_offset.x, cut.region.image_offset.y].map(|o| o as u32); + let width = cut.region.image_extent.width; + let mut start = 0; + while start < rows { + let count = (*band).min(rows - start); + let at = first + start * pitch; + let bound = at / PART_ALIGNMENT * PART_ALIGNMENT; + let skip = at - bound; + let size = count * row_bytes; + let current_window = (merged.buffer, bound, skip + (count - 1) * pitch + row_bytes); + let (row_words, first_word) = (u32_of(pitch / 4)?, u32_of(skip / 4)?); + let changed_window = (changed.raw, changed.at + start * row_bytes, size); + let total = count * words; + let shape = ShadowMergeModule::shape( + u32_of(words)?, + u32_of(total)?, + row_words, + first_word, + ); + let local = u64::from(ShadowMergeModule::LOCAL_SIZE); + dispatches.push(([u32_of(total.div_ceil(local))?, 1], shape)); + } + let origin = [x0, y0 + u32_of(start)?]; + let shape = + ShadowMergeImageModule::shape(origin, width, row_words, first_word); + let groups = ShadowMergeImageModule::groups([width, u32_of(count)?]); + dispatches.push((groups, shape)); + } + } + start += count; + } + } else { + // In place, the current bytes' binding starts up to 255 bytes before each window. + let room = match in_place { + true => range.saturating_sub(PART_ALIGNMENT), + false => range, + let window = (room / PART_ALIGNMENT * PART_ALIGNMENT).min(groups * GROUP_BYTES); + if window == 0 { + return Err(internal( + "a device whose storage buffers hold no merge window", + )); + } + let mut start = 0; + // In place, the windows cover the texture's bytes alone, which lie in the buffer; + // through a copy, the parts whole. + let total = if in_place { rounded } else { part }; + while start < total { + let size = window.min(total - start); + let words = u32_of(size / 4)?; + let (current_window, first_word) = match current { + Some(current) => ((current.raw, current.at + start, size), 0), + None => { + let at = merged.first + start; + let bound = at / PART_ALIGNMENT * PART_ALIGNMENT; + let skip = at - bound; + ((merged.buffer, bound, skip + size), u32_of(skip / 4)?) + } + }; + let changed = + changed.ok_or_else(|| internal("a merge without its changed part"))?; + sets.push(set(vec![ + (kept_part.raw, kept_part.at + start, size), + (changed.raw, changed.at + start, size), + current_window, + ])); + // The window's words, one row of them. + let shape = ShadowMergeModule::shape(words, words, 0, first_word); + dispatches.push(([words.div_ceil(ShadowMergeModule::LOCAL_SIZE), 1], shape)); + start += size; + } } - let mut ranges = Vec::new(); - let mut groups = Vec::new(); - let mut start = 0; - while start < part { - let size = window.min(part - start); - ranges.push( - parts - .iter() - .map(|p| (p.raw, p.at + start, size)) - .collect::>(), - ); - let words = - u32::try_from(size / 4).map_err(|_| internal("a merge window past u32 words"))?; - groups.push((words.div_ceil(ShadowMergeModule::LOCAL_SIZE), words)); - start += size; + }; + let binds = OwnedBinds::new(device, &kernel, &sets)?; + let cut = cut.map(|(cut, ..)| cut); + let changed = match changed { + Some(part) => Changed::Copied { + part, + dispatch: dispatched_out(device, copies, part, cut.as_ref()), + }, + None => { + device.shared().counts.shadow_merge_fetched(); + Changed::Fetched + } + }; + let texels = match &cut { + Some(Cut { region, .. }) => { + let extent = region.image_extent; + u64::from(extent.width) * u64::from(extent.height) + } + None => copies.texels(), + }; } let kernel = device.owned_kernel(OwnedModule::ShadowMerge)?; let sets = OwnedSets::write(device, &kernel, &ranges)?; @@ -161,35 +397,163 @@ impl ShadowMerge { }); Ok(ShadowMerge { merged, - parts, + cut, + texels, + changed, kept, - _held: held, + keep_dispatch, + held, kernel, - sets, - groups, - }) + binds, } - /// The uses of keeping the shadow of `copies`: a read of the shadow and a write of the kept - /// part. - pub(super) fn keep_uses(&self, copies: &ShadowCopies) -> Vec> { - let (key, tracked, range) = self.kept.clone(); + /// Whether the keep is a dispatch (`ShadowMerge::keep_dispatch`), which runs in the compute + /// stage. + pub(super) fn dispatches(&self) -> bool { + self.keep_dispatch.is_some() + } + + /// The dispatch on `device` that takes the copy in of `region` of the shadow of `copies` (its + /// texels in the buffer, as the copy in cuts it, `ShadowCopy::copied_region`) and this + /// merge's keep together (`shadow_copy_in.rs`): where the keep is a dispatch of the + /// rectangle the merge is cut to, in place, which is the copy in's, and the shadow's view + /// stores; `None` where the copy in and the keep stay apart. + pub(super) fn keep_in( + &self, + device: &Device, + copies: &ShadowCopies, + region: &vk::BufferImageCopy, + ) -> Option { + return None; + }; + // Both of the texture's one region, of one slice and level. + let same = region.image_offset == cut.region.image_offset + && region.image_extent == cut.region.image_extent; + if !same { + return None; + } + let view = word_view(copies)?; + } + + /// The uses of the dispatch that takes the copy in of the shadow of `copies` and the keep + /// ([`keep_in`](Self::keep_in)): a storage read of the texture's bytes, and storage writes of + /// the shadow and of the kept part, in the compute stage. + pub(super) fn keep_in_uses(&self, copies: &ShadowCopies) -> Vec> { + let storage = |access| Access::new(vk::PipelineStageFlags2::COMPUTE_SHADER, access); + let (truth, range) = copies.truth(); + let (key, tracked, kept) = self.kept.clone(); vec![ Use::reads( + truth, + copies.tracked, + range, + storage(vk::AccessFlags2::SHADER_STORAGE_READ), + ), + Use::writes( copies.shadow_key, copies.tracked, copies.shadow_range.clone(), - transfer(vk::AccessFlags2::TRANSFER_READ), + storage(vk::AccessFlags2::SHADER_STORAGE_WRITE), ), Use::writes( key, tracked, - UseRange::Bytes(range), - transfer(vk::AccessFlags2::TRANSFER_WRITE), + storage(vk::AccessFlags2::SHADER_STORAGE_WRITE), ), ] } + /// Whether the merge's copy of the texels after the commands into the changed part is a + /// dispatch (none where the merge fetches them). + pub(super) fn changed_dispatches(&self) -> bool { + matches!( + self.changed, + Changed::Copied { + dispatch: Some(_), + .. + } + ) + } + + /// The rectangle `[x0, y0, x1, y1)` of the shadow's texels the merge keeps and merges, `None` + /// for every texel. + pub(super) fn area(&self) -> Option<[u32; 4]> { + (self.cut.as_ref()) + .filter(|cut| !cut.whole) + .map(|cut| cut.area) + } + + /// The texels each keep copies (`WorkCounts::shadow_texels_kept`). + pub(super) fn texels_kept(&self) -> u64 { + self.texels + } + + /// Record the copy of the shadow of `copies` into `part`: the cut rectangle's texels, row after + /// row, or every texel laid out as in the buffer from the texture's first byte. + /// + /// # Safety + /// + /// As `record_keep`. + unsafe fn record_out( + &self, + device: &Vk, + command_buffer: vk::CommandBuffer, + copies: &ShadowCopies, + part: Part, + ) { + // SAFETY: the caller's contract; the part holds the rectangle's texels row after row, or + // the texture's bytes. + unsafe { + match &self.cut { + Some(Cut { image, region, .. }) => device.cmd_copy_image_to_buffer( + command_buffer, + *image, + vk::ImageLayout::GENERAL, + part.raw, + &[vk::BufferImageCopy { + buffer_offset: part.at, + ..*region + }], + ), + None => copies.record_out(device, command_buffer, part.raw, part.at), + } + } + } + + /// The use of the shadow of `copies` by the keep, the changed copy or the merge's fetches: a + /// copy's transfer read, or a dispatch's sampled read where `dispatched`. + fn shadow_read(copies: &ShadowCopies, dispatched: bool) -> Use { + let read = match dispatched { + true => Access::new( + vk::PipelineStageFlags2::COMPUTE_SHADER, + vk::AccessFlags2::SHADER_SAMPLED_READ, + ), + false => transfer(vk::AccessFlags2::TRANSFER_READ), + }; + Use::reads( + copies.shadow_key, + copies.tracked, + copies.shadow_range.clone(), + read, + ) + } + + /// The uses of keeping the shadow of `copies`: a read of the shadow and a write of the kept + /// part, by a copy or a dispatch. + pub(super) fn keep_uses(&self, copies: &ShadowCopies) -> Vec> { + let (key, tracked, range) = self.kept.clone(); + let write = match self.dispatches() { + true => Access::new( + vk::PipelineStageFlags2::COMPUTE_SHADER, + vk::AccessFlags2::SHADER_STORAGE_WRITE, + ), + false => transfer(vk::AccessFlags2::TRANSFER_WRITE), + }; + vec![ + ShadowMerge::shadow_read(copies, self.dispatches()), + ] + } + /// The uses of merging the shadow of `copies`: a read of the shadow and of the kept part, and /// a read and a write of the texture's bytes. pub(super) fn merge_uses(&self, copies: &ShadowCopies) -> Vec> { @@ -210,6 +574,11 @@ impl ShadowMerge { vk::AccessFlags2::SHADER_STORAGE_READ, ), ), + let dispatched = match self.changed { + Changed::Copied { ref dispatch, .. } => dispatch.is_some(), + Changed::Fetched => true, + }; + ShadowMerge::shadow_read(copies, dispatched), Use { key: self.merged.key, tracked: copies.tracked, @@ -232,16 +601,22 @@ impl ShadowMerge { command_buffer: vk::CommandBuffer, copies: &ShadowCopies, ) { - let [kept, _, _] = self.parts; - // SAFETY: the caller's contract; the kept part holds the texture's bytes. - unsafe { copies.record_out(device, command_buffer, kept.raw, kept.at) }; + // SAFETY: the caller's contract; the kept part holds the texture's bytes, and the + unsafe { + } + } } - /// Record the merge of the shadow of `copies` into its buffer's bytes (the module docs). + /// Record the merge of the shadow of `copies` into its buffer's bytes (the module docs): a + /// barrier between the copies of the texels into the changed and current parts, where it has + /// them, and its dispatches; and one to everything after them. A merge that fetches the + /// texels in place records no copy, and its dispatches follow the commands by the barrier + /// every caller records before a copy (the encoder's, from the merge's uses). /// /// # Safety /// - /// As `record_keep`, after the keep and the command it surrounds. + /// As `record_keep`, after the keep and the command it surrounds, and after a barrier from + /// what precedes it. pub(super) unsafe fn record_merge( &self, device: &Vk, @@ -257,36 +632,31 @@ impl ShadowMerge { } = self.merged; let span = bytes.end - bytes.start; // SAFETY: the caller's contract; each part holds the texture's bytes, and the sets bind - // windows inside the parts. + // windows inside the parts and, in place, inside the texture's bytes (and the shadow's + // view, where the merge fetches its texels). unsafe { - copies.record_out(device, command_buffer, changed.raw, changed.at); - device.cmd_copy_buffer( - command_buffer, - buffer, - current.raw, - &[vk::BufferCopy { - src_offset: first, - dst_offset: current.at, - size: span, - }], - ); - Barrier::everything().record(device, command_buffer); + match &self.changed { + Changed::Copied { + dispatch: Some(out), + .. + } => out.record(device, command_buffer), + Changed::Copied { part, .. } => { + self.record_out(device, command_buffer, copies, *part); + } + Changed::Fetched => {} + } + let copied = !matches!(self.changed, Changed::Fetched) || self.current.is_some(); + if copied { + Barrier::everything().record(device, command_buffer); + } device.cmd_bind_pipeline( command_buffer, vk::PipelineBindPoint::COMPUTE, self.kernel.pipeline, ); - for (set, &(groups, words)) in self.sets.sets.iter().zip(&self.groups) { - device.cmd_bind_descriptor_sets( - command_buffer, - vk::PipelineBindPoint::COMPUTE, - self.kernel.layout, - 0, - std::slice::from_ref(set), - &[], - ); - // The window's words, one row of them. - let shape = ShadowMergeModule::shape(words, words, 0, 0); + for (window, (groups, shape)) in self.dispatches.iter().enumerate() { + self.binds + .bind(device, command_buffer, &self.kernel, window); device.cmd_push_constants( command_buffer, self.kernel.layout, @@ -294,23 +664,197 @@ impl ShadowMerge { 0, &shape, ); - device.cmd_dispatch(command_buffer, groups, 1, 1); + device.cmd_dispatch(command_buffer, groups[0], groups[1], 1); } Barrier::everything().record(device, command_buffer); - device.cmd_copy_buffer( - command_buffer, - current.raw, - buffer, - &[vk::BufferCopy { - src_offset: current.at, - dst_offset: first, - size: span, - }], - ); +} + +impl Drop for ShadowMerge { + /// Its scratch goes back to its shadow's spares: the merge goes once the command buffers that + /// recorded it completed, which retain it. + fn drop(&mut self) { } } } +/// The shadow's unsigned-integer view of `copies`, where it has one (`shadow_copy_back.rs`): a +/// one-region image of 4-, 8- or 16-byte texels copied in place. +fn word_view(copies: &ShadowCopies) -> Option { + match &copies.source { + ShadowSource::Bytes { + target: ShadowTarget::Image { + words: Some(words), .. + }, + .. + } => Some(*words), + _ => None, + } +} + +/// Whether `bind::shadow_merge_image_module` takes the rectangle of `cut`: its first texel's +/// coordinates and its last row's below 65536 (the shape's origin), and its row's workgroups +/// within `groups` (`maxComputeWorkGroupCount[0]`); its rows go in bands of at most +/// `groups_y` (`maxComputeWorkGroupCount[1]`). +fn fetches(cut: &Cut, groups: u64, groups_y: u64) -> bool { + let (offset, extent) = (cut.region.image_offset, cut.region.image_extent); + let row_groups = u64::from(ShadowMergeImageModule::groups([extent.width, 1])[0]); + let below = |o: i32, n: u32| u64::from(o as u32) + u64::from(n) <= 1 << 16; + below(offset.x, 1) && below(offset.y, extent.height) && row_groups <= groups && groups_y > 0 +} + +/// The dispatch on `device` that stores the shadow of `copies` into `part`, as its copy out +/// (`ShadowMerge::record_out`) would: the texels of `cut` row after row, or every texel laid +/// out as in the buffer from the texture's first byte; where `device` runs a copy back faster as +/// a dispatch and the shadow is a one-region image copied in place with its integer view +/// (`shadow_copy_back.rs`); `None` where the part does not fit one (a copy takes it). +fn dispatched_out( + device: &Device, + copies: &ShadowCopies, + part: Part, + cut: Option<&Cut>, +) -> Option { + if !shadow_copy_back::dispatches(device) { + return None; + } + let ShadowSource::Bytes { + target: + ShadowTarget::Image { + regions, + staging: None, + words: Some(words), + .. + }, + .. + } = &copies.source + else { + return None; + }; + let [region] = regions.as_slice() else { + return None; + }; + let region = cut.map_or(region, |cut| &cut.region); + let region = vk::BufferImageCopy { + buffer_offset: part.at, + ..*region + }; + CopyBack::new(device, *words, part.raw, ®ion) +} + +/// Where a cut rectangle's rows lie in the buffer's `VkBuffer`. +#[derive(Clone, Copy)] +struct Geometry { + /// Its first byte, a whole word. + first: u64, + /// The bytes of each of its rows (whole words), their pitch in the buffer (whole words), and + /// its rows. + row_bytes: u64, + pitch: u64, + rows: u64, +} + +impl Geometry { + /// The rows of each band of the merge: all of them where one binding of each part and of the + /// current bytes stays within `range` (`maxStorageBufferRange`) and one dispatch takes at most + /// `dispatched` rows (as the device's workgroup counts bound its kernel), else the most that + /// do in a whole number of steps, so each band's kept and changed rows start at a multiple of + /// the alignment; `None` where not one row fits. + fn band(&self, range: u64, dispatched: u64) -> Option { + let Geometry { + row_bytes, + pitch, + rows, + .. + } = *self; + let step = PART_ALIGNMENT / gcd(row_bytes, PART_ALIGNMENT); + let by_current = match range.checked_sub(PART_ALIGNMENT + row_bytes) { + Some(rest) => rest / pitch + 1, + None => 0, + }; + let most = rows.min(by_current).min(range / row_bytes).min(dispatched); + let band = match most == rows { + true => rows, + false => most / step * step, + }; + (band > 0).then_some(band) + } +} + +/// The cut of `copies`'s shadow to the texels inside `area` (`[x0, y0, x1, y1)`; `None` every +/// texel), each row widened to whole words of the buffer, and where its rows lie: for one region +/// of one slice over the buffer's bytes in place, whose rows' pitch is whole words and whose +/// texels inside `area` take whole words from the first of a row to the last; `None` otherwise, +/// or where `area` holds no texel. +fn cut_of(copies: &ShadowCopies, area: Option<[u32; 4]>) -> Option<(Cut, Geometry)> { + let [x0, y0, x1, y1] = area.unwrap_or([0, 0, u32::MAX, u32::MAX]); + let ShadowSource::Bytes { + target: + ShadowTarget::Image { + image, + regions, + staging: None, + texel: Some(texel), + .. + }, + .. + } = &copies.source + else { + return None; + }; + let [region] = regions.as_slice() else { + return None; + }; + let extent = region.image_extent; + if extent.depth != 1 || region.image_subresource.layer_count != 1 { + return None; + } + let row = match region.buffer_row_length { + 0 => extent.width, + row => row, + }; + let pitch = u64::from(row) * texel; + // The texels of a whole number of words: a row's first texel's byte a whole word, as the + // texture's first byte and its pitch are. + let step = (4 / gcd(*texel, 4)) as u32; + let x0 = x0 / step * step; + let x1 = x1.min(extent.width).next_multiple_of(step); + let y1 = y1.min(extent.height); + if x1 > extent.width || x0 >= x1 || y0 >= y1 || !pitch.is_multiple_of(4) { + return None; + } + let first = region.buffer_offset + (u64::from(y0) * u64::from(row) + u64::from(x0)) * texel; + let geometry = Geometry { + first, + row_bytes: u64::from(x1 - x0) * texel, + pitch, + rows: u64::from(y1 - y0), + }; + if !first.is_multiple_of(4) || !geometry.row_bytes.is_multiple_of(4) { + return None; + } + let cut = Cut { + area: [x0, y0, x1, y1], + whole: area.is_none(), + image: *image, + region: vk::BufferImageCopy { + buffer_offset: 0, + buffer_row_length: x1 - x0, + buffer_image_height: y1 - y0, + image_subresource: region.image_subresource, + image_offset: vk::Offset3D { + x: region.image_offset.x + x0 as i32, + y: region.image_offset.y + y0 as i32, + z: region.image_offset.z, + }, + image_extent: vk::Extent3D { + width: x1 - x0, + height: y1 - y0, + depth: 1, + }, + }, + }; + Some((cut, geometry)) +} + fn transfer(access: vk::AccessFlags2) -> Access { Access::new(vk::PipelineStageFlags2::COPY, access) } diff --git a/crates/metal2vulkan-runtime/src/tests/blit_holds.rs b/crates/metal2vulkan-runtime/src/tests/blit_holds.rs index 0c3df6fc1..32adacec8 100644 --- a/crates/metal2vulkan-runtime/src/tests/blit_holds.rs +++ b/crates/metal2vulkan-runtime/src/tests/blit_holds.rs @@ -92,6 +92,16 @@ impl Host { self.words().iter().all(|&word| word == value) } + /// Its pages, for a no-copy buffer or a rebind. + /// + /// # Safety + /// + /// They outlive every buffer over them, which alone use them while it lives. + pub(super) unsafe fn memory(&self) -> HostMemory { + // SAFETY: the caller's contract; `BYTES` bytes, allocated in `new` aligned to a page. + unsafe { HostMemory::new(self.0) } + } + /// Set every word to `value`. pub(super) fn fill(&self, value: u32) { // SAFETY: as above; no command uses them now. diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 1db4aa808..872429118 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -111,6 +111,8 @@ mod noted_apart; mod numbered_samplers; mod options; mod own; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod owned_pushes; mod pipeline; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod pipeline_wait_order; diff --git a/crates/metal2vulkan-runtime/src/tests/owned_pushes.rs b/crates/metal2vulkan-runtime/src/tests/owned_pushes.rs new file mode 100644 index 000000000..a09064cf2 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/owned_pushes.rs @@ -0,0 +1,38 @@ +//! A crate-owned kernel whose set 0 is a push descriptor set's (`owned_kernel.rs`): Vulkan +//! forbids a set from such a layout (`VkDescriptorSetAllocateInfo`), so its dispatches bind +//! through `OwnedBinds`, which pushes them, and `OwnedSets` refuses the kernel rather than +//! allocate one (the shadow merge's kernel, which a linear attachment's merge dispatches too, +//! `linear_merge.rs`). +//! +//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`), on the kind of device the cfg selects. + +use super::blit_holds::{device, Scratch}; +use crate::owned_kernel::{OwnedBinds, OwnedModule, OwnedSet, OwnedSets}; +use crate::ResourceOptions; + +#[test] +fn a_pushed_kernel_s_sets_are_pushed_and_never_allocated() { + let scratch = Scratch::new("owned-pushes"); + let device = device(&scratch.0); + let pushes = device.shared().vk().push_descriptor().is_some(); + let buffer = device.new_buffer(4096, ResourceOptions::private()).unwrap(); + let (raw, at) = buffer.at(0); + for module in [OwnedModule::ShadowMerge, OwnedModule::RowsCopy] { + let kernel = device.owned_kernel(module).unwrap(); + assert_eq!(kernel.pushed, pushes, "{module:?}"); + let set = || OwnedSet { + images: Vec::new(), + storage_images: Vec::new(), + buffers: vec![(raw, at, 256); kernel.buffers as usize], + }; + let binds = OwnedBinds::new(&device, &kernel, &[set()]).unwrap(); + assert_eq!(matches!(binds, OwnedBinds::Pushed(_)), pushes, "{module:?}"); + let sets = OwnedSets::write_each(&device, &[kernel], &[set()]); + assert_eq!( + sets.is_err(), + pushes, + "{module:?}: a set from a pushed layout" + ); + } +} diff --git a/crates/metal2vulkan-runtime/src/tests/shadow.rs b/crates/metal2vulkan-runtime/src/tests/shadow.rs index 73fa8d85a..2cfec9e7c 100644 --- a/crates/metal2vulkan-runtime/src/tests/shadow.rs +++ b/crates/metal2vulkan-runtime/src/tests/shadow.rs @@ -5,15 +5,33 @@ use super::super::host_aliases::{self, Alias}; use super::super::key_hash::KeyMap; use super::super::resource::ResourceKey; use super::super::shadow::{ - self, ShadowBuffer, ShadowCopies, ShadowCopy, ShadowSource, ShadowSync, ShadowTarget, - ShadowUse, Step, Within, + self, Backing, CopyCause, KeptArea, Lost, ShadowBuffer, ShadowCopies, ShadowCopy, ShadowSource, + ShadowSync, ShadowTarget, ShadowUse, Step, Within, }; +use super::super::shadow_merge::ScratchSpares; use super::super::tracker::{Access, Use, UseRange}; use ash::vk; use metal2vulkan::error::Feature; use std::ops::Range; use std::sync::Arc; +/// A merge's scratch, numbered, keeping every texel. +impl KeptArea for u32 { + fn kept_area(&self) -> Option<[u32; 4]> { + None + } +} + +/// A merge's scratch, numbered, keeping the texels of its rectangle (`None` every texel). +#[derive(Clone, Debug, PartialEq, Eq)] +struct Boxed(u32, Option<[u32; 4]>); + +impl KeptArea for Boxed { + fn kept_area(&self) -> Option<[u32; 4]> { + self.1 + } +} + /// A shadowed texture over `bytes` of the buffer `buffer`. fn shadow(buffer: ResourceKey, bytes: Range) -> Arc { shadow_joined(buffer, None, bytes) @@ -25,6 +43,15 @@ fn shadow_joined( buffer: ResourceKey, alias: Option, bytes: Range, + ShadowBuffer::Fixed(vk::Buffer::null(), 0), +/// `texture` over a `Private` buffer's bytes, tracked where `tracked`: the CPU writes none, and +/// another queue's commands write them while a command buffer runs only where it is untracked +/// (`ShadowCopies::merges_back`). +fn over_private(texture: Arc, tracked: bool) -> Arc { + let mut copies = Arc::into_inner(texture).expect("one holder"); + copies.backing = Backing::PrivateBuffer; + copies.tracked = tracked; + Arc::new(copies) ) -> Arc { Arc::new(ShadowCopies { source: ShadowSource::Bytes { @@ -48,6 +75,8 @@ fn shadow_joined( }, tracked: true, drops_writes: false, + backing: Backing::MappedBuffer, + merge_scratch: ScratchSpares::default(), }) } @@ -148,7 +177,7 @@ fn planned( ) -> Vec> { let (shadows, uses) = command_uses(textures, others); let copies = sync - .before(&shadows, &uses, |_| { + .before(&shadows, &uses, |_, _, _| { *made += 1; Ok(*made) }) @@ -167,24 +196,28 @@ fn command( named(&planned(sync, &mut 0, textures, others)) } +/// An encoder copies a texture over a buffer's bytes in before its first use, keeps it before +/// the first command that writes through it, and merges what its commands wrote back as it ends. +/// A texture only read is not merged back. #[test] -fn an_encoder_copies_a_texture_in_before_its_first_use_and_back_after_its_writes() { +fn an_encoder_copies_a_texture_in_before_its_first_use_and_merges_its_writes_back() { let buffer = ResourceKey::new(); let t = shadow(buffer, 256..1280); + let k = t.shadow_key; + let mut made = 0; + let mut run = |sync: &mut ShadowSync, textures: &[(&Arc, bool)]| { + moved(&planned(sync, &mut made, textures, &[])) + }; let mut sync = ShadowSync::default(); - assert_eq!( - command(&mut sync, &[(&t, false)], &[]), - [(t.shadow_key, true)] - ); - assert_eq!(command(&mut sync, &[(&t, false)], &[]), []); - assert_eq!(command(&mut sync, &[(&t, true)], &[]), []); - assert_eq!(command(&mut sync, &[(&t, true)], &[]), []); - assert_eq!(named(&sync.finish()), [(t.shadow_key, false)]); - assert_eq!(named(&sync.finish()), []); - // A texture only read is not copied back. + assert_eq!(run(&mut sync, &[(&t, false)]), [Moved::Into(k)]); + assert_eq!(run(&mut sync, &[(&t, false)]), []); + assert_eq!(run(&mut sync, &[(&t, true)]), [Moved::Keep(k, 1)]); + assert_eq!(run(&mut sync, &[(&t, true)]), []); + assert_eq!(moved(&sync.finish()), [Moved::Merge(k, 1)]); + assert_eq!(moved(&sync.finish()), []); let mut sync = ShadowSync::default(); - command(&mut sync, &[(&t, false)], &[]); - assert_eq!(named(&sync.finish()), []); + run(&mut sync, &[(&t, false)]); + assert_eq!(moved(&sync.finish()), []); } /// The areas of the copies back `sync` makes as its encoder ends. @@ -192,14 +225,14 @@ fn back_areas(sync: &mut ShadowSync) -> Vec> { sync.finish().iter().map(|copy| copy.area).collect() } -/// A copy back covers only where the commands since the last wrote through the texture, where -/// each bounds its writes (a pass's attachment it loads, inside its draws' scissors): the -/// rectangle bounding their areas, or every texel where one does not bound them. A copy in is of -/// every texel, and joining a use that reads keeps the area of the one that writes. +/// A copy back (an image's shadow's: a buffer's bytes' shadow is merged back) covers only where +/// the commands since the last wrote through the texture, where each bounds its writes (a pass's +/// attachment it loads, inside its draws' scissors): the rectangle bounding their areas, or every +/// texel where one does not bound them. A copy in is of every texel, and joining a use that reads +/// keeps the area of the one that writes. #[test] fn a_copy_back_covers_only_where_the_commands_wrote() { - let buffer = ResourceKey::new(); - let t = shadow(buffer, 256..1280); + let t = image_shadow(ResourceKey::new(), 0, 1); let writing = |area: Option<[u32; 4]>| ShadowUse { copies: Arc::clone(&t), writes: true, @@ -214,7 +247,7 @@ fn a_copy_back_covers_only_where_the_commands_wrote() { for &area in areas { let shadows = [writing(area)]; let uses = [written.clone()]; - let copies = sync.before(&shadows, &uses, |_| Ok(0)).unwrap(); + let copies = sync.before(&shadows, &uses, |_, _, _| Ok(0)).unwrap(); assert!(copies.iter().all(|copy| copy.area.is_none()), "a copy in"); sync.after(&shadows, &uses, &[]); } @@ -242,7 +275,12 @@ fn a_copy_back_covers_only_where_the_commands_wrote() { /// A shadowed texture over `bytes` of the buffer `buffer` whose copies are cut to a rectangle /// (`ShadowCopies::cuts`): one region of a 64x32 image, 4 bytes a texel, rows 320 bytes apart. fn cut_shadow(buffer: ResourceKey, bytes: Range) -> Arc { - let mut copies = Arc::into_inner(shadow(buffer, bytes)).expect("one holder"); + cut_shadow_in(ShadowBuffer::Fixed(vk::Buffer::null(), 0), buffer, bytes) +} + +/// [`cut_shadow`]'s texture, its bytes in `raw`. +fn cut_shadow_in(raw: ShadowBuffer, buffer: ResourceKey, bytes: Range) -> Arc { + let mut copies = Arc::into_inner(shadow_in(raw, buffer, None, bytes)).expect("one holder"); if let ShadowSource::Bytes { target: ShadowTarget::Image { regions, .. }, .. @@ -271,27 +309,34 @@ fn cut_shadow(buffer: ResourceKey, bytes: Range) -> Arc { } /// The copies `sync` plans before a command of `shadows` with `uses`, then the command noted: -/// each copy's step (into the image, or back) and area. +/// each copy's step (`'i'` into the image, `'b'` back, `'k'` a keep, `'m'` a merge) and area. fn planned_areas( sync: &mut ShadowSync, shadows: &[ShadowUse], uses: &[Use], -) -> Vec<(bool, Option<[u32; 4]>)> { - let copies = sync.before(shadows, uses, |_| Ok(0)).unwrap(); +) -> Vec<(char, Option<[u32; 4]>)> { + let copies = sync.before(shadows, uses, |_, _, _| Ok(0)).unwrap(); sync.after(shadows, uses, &[]); - copies - .iter() - .map(|copy| (matches!(copy.step, Step::Into), copy.area)) - .collect() + copies.iter().map(|copy| (step(copy), copy.area)).collect() +} + +/// A copy's step: `'i'` into the image, `'b'` back, `'k'` a keep, `'m'` a merge. +fn step(copy: &ShadowCopy) -> char { + match copy.step { + Step::Into => 'i', + Step::Back => 'b', + Step::Keep(_) => 'k', + Step::Merge(_) => 'm', + } } /// A use that reads and writes a texture only inside a rectangle (`ShadowUse::loads`, a pass's /// attachment it loads and takes no other way, inside its draws' scissors) copies in only the -/// texels there, and its writes are copied back there alone. A later command of the encoder that -/// reads past them first takes a copy back of what was written and a copy in of every texel, so -/// no texel the image did not take from the buffer is read or copied back. A shadow whose copies -/// are not cut to a rectangle, a use joined with one that reads anywhere, and a texture written -/// two ways copy every texel in; a use inside the rectangle the image holds copies nothing in. +/// texels there, and is kept for its merge back. A later command of the encoder that reads past +/// them first takes the merge of what was written and a copy in of every texel, so no texel the +/// image did not take from the buffer is read. A shadow whose copies are not cut to a rectangle, +/// a use joined with one that reads anywhere, and a texture written two ways copy every texel in; +/// a use inside the rectangle the image holds copies nothing in. #[test] fn a_copy_in_covers_only_where_the_command_reads_and_writes() { let buffer = ResourceKey::new(); @@ -311,21 +356,21 @@ fn a_copy_in_covers_only_where_the_command_reads_and_writes() { let uses = [written.clone()]; assert_eq!( planned_areas(&mut sync, &[inside(a, true)], &uses), - [(true, Some(a))] + [('i', Some(a)), ('k', None)] ); // Inside what the image holds: nothing more is copied in. assert_eq!( planned_areas(&mut sync, &[inside([10, 5, 20, 10], true)], &uses), [] ); - assert_eq!(back_areas(&mut sync), [Some(a)]); - // Past it: what was written goes back, then every texel comes in. + assert_eq!(moved(&sync.finish()), [Moved::Merge(t.shadow_key, 0)]); + // Past it: what was written is merged back, then every texel comes in. let mut sync = ShadowSync::::default(); planned_areas(&mut sync, &[inside(a, true)], &uses); let (anywhere, _) = through(&t, false); assert_eq!( planned_areas(&mut sync, &[anywhere], std::slice::from_ref(&read)), - [(false, Some(a)), (true, None)] + [('m', None), ('i', None)] ); assert_eq!(back_areas(&mut sync), []); // Past it, unwritten: only the copy in. @@ -333,14 +378,17 @@ fn a_copy_in_covers_only_where_the_command_reads_and_writes() { planned_areas(&mut sync, &[inside(a, false)], std::slice::from_ref(&read)); assert_eq!( planned_areas(&mut sync, &[inside([0, 0, 64, 32], false)], &[read]), - [(true, Some([0, 0, 64, 32]))] + [('i', Some([0, 0, 64, 32]))] ); // Joined with a use that reads anywhere, a use reads anywhere. let mut joined = vec![inside(a, true)]; shadow::join(&mut joined, &through(&t, false).0); assert_eq!((joined[0].loads, joined[0].area), (None, Some(a))); let mut sync = ShadowSync::::default(); - assert_eq!(planned_areas(&mut sync, &joined, &uses), [(true, None)]); + assert_eq!( + planned_areas(&mut sync, &joined, &uses), + [('i', None), ('k', None)] + ); // Two uses inside rectangles read inside the one bounding both. let mut joined = vec![inside(a, true)]; shadow::join(&mut joined, &inside([30, 10, 50, 30], false)); @@ -353,11 +401,14 @@ fn a_copy_in_covers_only_where_the_command_reads_and_writes() { ..inside(a, true) }; let uses = [through(&whole, true).1]; - assert_eq!(planned_areas(&mut sync, &[uncut], &uses), [(true, None)]); + assert_eq!( + planned_areas(&mut sync, &[uncut], &uses), + [('i', None), ('k', None)] + ); // Written two ways: kept, and every texel copied in for the merge to compare. let mut sync = ShadowSync::::default(); let uses = [written, bytes(buffer, 256..512, true)]; - let copies = sync.before(&[inside(a, true)], &uses, |_| Ok(7)).unwrap(); + .before(&[inside(a, true)], &uses, |_, _, _| Ok(7)) assert_eq!( moved(&copies), [Moved::Into(t.shadow_key), Moved::Keep(t.shadow_key, 7)] @@ -369,9 +420,173 @@ fn a_copy_in_covers_only_where_the_command_reads_and_writes() { step: Step::Into, kept: false, area: Some(a), - bounded: false, + cause: Some(CopyCause::First), }; assert_eq!((copy.texels_in(), copy.texels_back()), (32 * 16, 0)); + assert_eq!(copy.texels_copied_in(), 32 * 16); +} + +/// Whether each copy is a copy in that is the encoder's first of its texture +/// (`CopyCause::First`). +fn firsts(copies: &[ShadowCopy]) -> Vec<(ResourceKey, bool)> { + let into = copies.iter().filter(|copy| matches!(copy.step, Step::Into)); + into.map(|copy| { + let first = copy.cause == Some(CopyCause::First); + (copy.copies.shadow_key, first) + }) + .collect() +} + +/// An encoder's first copy in of a texture is the one before the first command that uses it, or +/// the first after work it records apart (`ShadowSync::leave`), which forgets every texture; a +/// copy in after a write of the bytes, or before a command needing texels the image does not +/// hold, is not (`WorkCounts::shadow_texels_first_copied_in`). +#[test] +fn an_encoders_first_copy_in_of_a_texture_is_counted_apart() { + let buffer = ResourceKey::new(); + let t = cut_shadow(buffer, 256..256 + 320 * 32); + let u = shadow(ResourceKey::new(), 0..1024); + let mut sync = ShadowSync::default(); + let first = |sync: &mut ShadowSync, textures: &[_], others: &[_]| { + firsts(&planned(sync, &mut 0, textures, others)) + }; + assert_eq!( + first(&mut sync, &[(&t, false)], &[]), + [(t.shadow_key, true)] + ); + assert_eq!(first(&mut sync, &[(&t, false)], &[]), []); + // A write of the bytes another way: the next copy in is a later one; a texture the encoder + // meets with it takes its first. + assert_eq!(first(&mut sync, &[], &[bytes(buffer, 256..512, true)]), []); + assert_eq!( + first(&mut sync, &[(&t, false), (&u, false)], &[]), + [(t.shadow_key, false), (u.shadow_key, true)] + ); + // A command reading past the rectangle the image holds. + let inside = ShadowUse { + loads: Some([0, 0, 8, 8]), + ..through(&t, false).0 + }; + let mut cut = ShadowSync::::default(); + let uses = [through(&t, false).1]; + let copies = cut.before(&[inside], &uses, |_, _, _| Ok(0)).unwrap(); + assert_eq!(firsts(&copies), [(t.shadow_key, true)]); + let copies = cut + .before(&[through(&t, false).0], &uses, |_, _, _| Ok(0)) + .unwrap(); + assert_eq!(firsts(&copies), [(t.shadow_key, false)]); + // Work recorded apart: the encoder forgets every texture. + assert_eq!(named(&sync.leave()), []); + assert_eq!( + first(&mut sync, &[(&t, false)], &[]), + [(t.shadow_key, true)] + ); + // An image's shadow's first copy in moves every texel of its regions, which + // `texels_in` (a buffer's texture's) leaves out. + let mut copies = Arc::into_inner(view_of(ResourceKey::new(), 0..1, 0..2)).expect("one"); + if let ShadowSource::Image { regions, .. } = &mut copies.source { + regions.push(vk::ImageCopy { + src_subresource: vk::ImageSubresourceLayers { + aspect_mask: vk::ImageAspectFlags::COLOR, + mip_level: 0, + base_array_layer: 0, + layer_count: 2, + }, + dst_subresource: vk::ImageSubresourceLayers { + aspect_mask: vk::ImageAspectFlags::COLOR, + mip_level: 0, + base_array_layer: 0, + layer_count: 2, + }, + extent: vk::Extent3D { + width: 8, + height: 4, + depth: 1, + }, + ..Default::default() + }); + } + let v = Arc::new(copies); + let copies = planned(&mut ShadowSync::default(), &mut 0, &[(&v, false)], &[]); + let moved: Vec<(u64, u64)> = (copies.iter()) + .map(|copy| (copy.texels_in(), copy.texels_copied_in())) + .collect(); + assert_eq!(moved, [(0, 8 * 4 * 2)]); + // Host pages the texture's own image lies in too are told apart; nothing else changes. + assert_eq!(Backing::HostPages.aliased(), Backing::AliasedHostPages); + assert_eq!(Backing::MappedBuffer.aliased(), Backing::MappedBuffer); +} + +/// Why each copy in is made (`ShadowCopy::cause`). A texture over a buffer's bytes that merges +/// back, first written through in the encoder, takes the encoder's first copy in, before its keep, +/// though the keep's scratch made the encoder meet the texture first. Every later copy in after a +/// change of the truth names the change that came first: a merge of another texture over the same +/// bytes, the texture's own merge after a command that wrote them through it and through another +/// texture, a write of them another way, and writes Metal drops. Two textures over the same bytes +/// count once as sharing their truth (`ShadowSync::sharing_truth`). +#[test] +fn each_copy_in_names_why_it_is_made() { + let buffer = ResourceKey::new(); + let t = shadow(buffer, 256..1280); + let u = shadow(buffer, 256..1280); + let other = shadow(ResourceKey::new(), 0..1024); + let (kt, ku) = (t.shadow_key, u.shadow_key); + assert!(t.merges_back()); + let into = |copies: &[ShadowCopy]| -> Vec<(ResourceKey, Option)> { + (copies.iter()) + .filter(|copy| matches!(copy.step, Step::Into)) + .map(|copy| (copy.copies.shadow_key, copy.cause)) + .collect() + }; + let changed = |lost| Some(CopyCause::Changed(lost)); + let mut made = 0; + let mut sync = ShadowSync::default(); + let copies = planned(&mut sync, &mut made, &[(&t, true)], &[]); + assert_eq!(moved(&copies), [Moved::Into(kt), Moved::Keep(kt, 1)]); + assert_eq!(into(&copies), [(kt, Some(CopyCause::First))]); + // Another texture over the bytes, read: its own first copy in, after the merge of the first. + let copies = planned(&mut sync, &mut made, &[(&u, false), (&other, false)], &[]); + assert_eq!( + into(&copies), + [ + (ku, Some(CopyCause::First)), + (other.shadow_key, Some(CopyCause::First)) + ] + ); + assert_eq!(sync.sharing_truth(), 1); + // Written through the first again, then the second read: the first's merge changed the bytes. + planned(&mut sync, &mut made, &[(&t, true)], &[]); + let copies = planned(&mut sync, &mut made, &[(&u, false)], &[]); + assert_eq!(into(&copies), [(ku, changed(Lost::OtherShadow))]); + // Written through both in one command: two ways, each merged before the next command. + planned(&mut sync, &mut made, &[(&t, true), (&u, true)], &[]); + let copies = planned(&mut sync, &mut made, &[(&t, false)], &[]); + assert_eq!(into(&copies), [(kt, changed(Lost::TwoWays))]); + // Its bytes written another way. + planned(&mut sync, &mut made, &[], &[bytes(buffer, 256..512, true)]); + let copies = planned(&mut sync, &mut made, &[(&t, false)], &[]); + assert_eq!(into(&copies), [(kt, changed(Lost::Written))]); + // Writes Metal drops. + let mut dropping = Arc::into_inner(shadow(ResourceKey::new(), 0..1024)).expect("one holder"); + dropping.drops_writes = true; + let dropping = Arc::new(dropping); + let mut sync = ShadowSync::default(); + let copies = planned(&mut sync, &mut made, &[(&dropping, true)], &[]); + assert_eq!( + into(&copies), + [(dropping.shadow_key, Some(CopyCause::First))] + ); + let copies = planned(&mut sync, &mut made, &[(&dropping, false)], &[]); + assert_eq!( + into(&copies), + [(dropping.shadow_key, changed(Lost::Dropped))] + ); + assert_eq!(sync.sharing_truth(), 0); +} + +/// Whether `copy` is a copy in of what changed within a rectangle (`CopyCause::Bounded`). +fn bounded(copy: &ShadowCopy) -> bool { + copy.cause == Some(CopyCause::Bounded) } /// Each copy's step (into the image, or not), area, and whether it is a copy in of what changed @@ -379,7 +594,7 @@ fn a_copy_in_covers_only_where_the_command_reads_and_writes() { fn steps(copies: &[ShadowCopy]) -> Vec<(bool, Option<[u32; 4]>, bool)> { copies .iter() - .map(|copy| (matches!(copy.step, Step::Into), copy.area, copy.bounded)) + .map(|copy| (matches!(copy.step, Step::Into), copy.area, bounded(copy))) .collect() } @@ -391,7 +606,7 @@ fn read_anywhere( let (shadow, used) = through(texture, false); let shadows = [shadow]; let uses = [used]; - let copies = sync.before(&shadows, &uses, |_| Ok(0)).unwrap(); + let copies = sync.before(&shadows, &uses, |_, _, _| Ok(0)).unwrap(); sync.after(&shadows, &uses, &[]); steps(&copies) } @@ -407,7 +622,7 @@ fn within_command( ) -> Vec<(bool, Option<[u32; 4]>, bool)> { let mut uses = others.to_vec(); uses.extend(parts.iter().flat_map(|part| part.uses.iter().cloned())); - let copies = sync.before(shadows, &uses, |_| Ok(0)).unwrap(); + let copies = sync.before(shadows, &uses, |_, _, _| Ok(0)).unwrap(); sync.after(shadows, others, parts); steps(&copies) } @@ -503,17 +718,91 @@ fn writes_within_a_rectangle_copy_in_only_the_texels_they_changed() { assert_eq!(read_anywhere(&mut sync, &t), [(false, None, false), whole]); } -/// A copy back of a part of a shadowed attachment's image (a pass's attachment of a texture whose -/// own image is a shadow, written inside its draws' scissors) leaves another image laid out as -/// it, texel for texel, current but inside the part: the next command that reads that image -/// copies in those texels alone. An image laid out otherwise copies every texel in. +/// A command that reads a texture only inside a rectangle and writes none (a draw that reads it +/// at its own pixels alone, `ShadowUse::loads`) takes in the texels writes within a rectangle +/// changed there alone, and leaves the others it did not move to the next command that reads +/// them: one that reads anywhere copies in the rectangle bounding those, never every texel, as +/// the image holds the bytes everywhere else. +#[test] +fn a_read_inside_a_rectangle_leaves_the_other_changed_texels_to_the_next_read() { + let buffer = ResourceKey::new(); + let bytes_of = 256..256 + 320 * 32; + let t = cut_shadow(buffer, bytes_of.clone()); + let attachment = bytes(buffer, bytes_of, true); + let (_, read) = through(&t, false); + let mut sync = ShadowSync::::default(); + let drawn = |sync: &mut ShadowSync, area: [u32; 4]| { + let part = Within { + uses: vec![attachment.clone()], + texels: Some(Arc::clone(&t)), + area, + }; + within_command(sync, &[], &[part], &[]) + }; + let read_inside = |sync: &mut ShadowSync, area: [u32; 4]| { + let reader = ShadowUse { + copies: Arc::clone(&t), + writes: false, + overwrites: false, + kept: false, + area: None, + loads: Some(area), + }; + within_command(sync, &[reader], &[], std::slice::from_ref(&read)) + }; + assert_eq!(read_anywhere(&mut sync, &t), [(true, None, false)]); + // Read inside a part of what changed: that part, then the rest of it for a read anywhere. + drawn(&mut sync, [8, 4, 40, 20]); + assert_eq!( + read_inside(&mut sync, [10, 5, 20, 10]), + [(true, Some([10, 5, 20, 10]), true)] + ); + assert_eq!( + read_anywhere(&mut sync, &t), + [(true, Some([8, 4, 40, 20]), true)] + ); + assert_eq!(read_anywhere(&mut sync, &t), []); + // A read across it from top to bottom leaves the columns beside it; one from side to side, + // the rows; one past it, nothing. + drawn(&mut sync, [8, 4, 40, 20]); + assert_eq!( + read_inside(&mut sync, [0, 0, 20, 32]), + [(true, Some([8, 4, 20, 20]), true)] + ); + assert_eq!( + read_anywhere(&mut sync, &t), + [(true, Some([20, 4, 40, 20]), true)] + ); + drawn(&mut sync, [8, 4, 40, 20]); + read_inside(&mut sync, [0, 10, 64, 32]); + assert_eq!( + read_anywhere(&mut sync, &t), + [(true, Some([8, 4, 40, 10]), true)] + ); + drawn(&mut sync, [8, 4, 40, 20]); + read_inside(&mut sync, [0, 0, 64, 32]); + assert_eq!(read_anywhere(&mut sync, &t), []); + // A read apart from it moves nothing, and leaves all of it. + drawn(&mut sync, [8, 4, 12, 6]); + assert_eq!(read_inside(&mut sync, [30, 20, 40, 30]), []); + assert_eq!( + read_anywhere(&mut sync, &t), + [(true, Some([8, 4, 12, 6]), true)] + ); +} + +/// A copy back of a part of a shadowed attachment's image (a pass's attachment of a texture over a +/// tracked `Private` buffer whose own image is a shadow, written inside its draws' scissors) +/// leaves another image laid out as it, texel for texel, current but inside the part: the next +/// command that reads that image copies in those texels alone. An image laid out otherwise copies +/// every texel in. #[test] fn a_copy_back_of_a_part_leaves_a_twin_stale_there_alone() { let buffer = ResourceKey::new(); let bytes_of = 256..256 + 320 * 32; - let attachment = cut_shadow(buffer, bytes_of.clone()); - let read = cut_shadow(buffer, bytes_of.clone()); - let other = shadow(buffer, bytes_of); + let attachment = over_private(cut_shadow(buffer, bytes_of.clone()), true); + let read = over_private(cut_shadow(buffer, bytes_of.clone()), true); + let other = over_private(shadow(buffer, bytes_of), true); let (_, written) = through(&attachment, true); let instance = |sync: &mut ShadowSync, area: [u32; 4], also: &[&Arc]| { let mut shadows = vec![ShadowUse { @@ -530,7 +819,7 @@ fn a_copy_back_of_a_part_leaves_a_twin_stale_there_alone() { shadows.push(shadow); uses.push(used); } - let copies = sync.before(&shadows, &uses, |_| Ok(0)).unwrap(); + let copies = sync.before(&shadows, &uses, |_, _, _| Ok(0)).unwrap(); sync.after(&shadows, &uses, &[]); copies .iter() @@ -540,7 +829,7 @@ fn a_copy_back_of_a_part_leaves_a_twin_stale_there_alone() { key, matches!(copy.step, Step::Into), copy.area, - copy.bounded, + bounded(copy), ) }) .collect::>() @@ -571,6 +860,71 @@ fn a_copy_back_of_a_part_leaves_a_twin_stale_there_alone() { ); } +/// A shadowed attachment over a buffer's bytes another writer may write (a pass's attachment of a +/// texture whose own image is a shadow), written inside its draws' scissors, is kept and merged +/// back: the merge changes only words the draws changed, inside the part they wrote, so it leaves +/// another image laid out as the attachment's current but inside that part, as a copy back of the +/// part does ([`a_copy_back_of_a_part_leaves_a_twin_stale_there_alone`]): the next command that +/// reads that image copies in those texels alone. An image laid out otherwise copies every texel +/// in. +#[test] +fn a_merge_of_a_part_leaves_a_twin_stale_there_alone() { + let buffer = ResourceKey::new(); + let bytes_of = 256..256 + 320 * 32; + let attachment = cut_shadow(buffer, bytes_of.clone()); + let read = cut_shadow(buffer, bytes_of.clone()); + let other = shadow(buffer, bytes_of); + assert!(attachment.merges_back()); + let (_, written) = through(&attachment, true); + let instance = |sync: &mut ShadowSync, area: [u32; 4], also: &[&Arc]| { + let mut shadows = vec![ShadowUse { + copies: Arc::clone(&attachment), + writes: true, + overwrites: false, + kept: false, + area: Some(area), + loads: Some([0, 0, 64, 32]), + }]; + let mut uses = vec![written.clone()]; + for texture in also { + let (shadow, used) = through(texture, false); + shadows.push(shadow); + uses.push(used); + } + let copies = sync.before(&shadows, &uses, |_, _, _| Ok(0)).unwrap(); + sync.after(&shadows, &uses, &[]); + copies + .iter() + .map(|copy| (copy.copies.shadow_key, step(copy), copy.area, bounded(copy))) + .collect::>() + }; + let all = Some([0, 0, 64, 32]); + let a = attachment.shadow_key; + let (r, o) = (read.shadow_key, other.shadow_key); + assert_eq!( + instance(&mut sync, [8, 4, 12, 6], &[]), + [(a, 'i', all, false), (a, 'k', None, false)] + ); + assert_eq!( + instance(&mut sync, [20, 4, 24, 6], &[&read, &other]), + [ + (a, 'm', None, false), + (r, 'i', None, false), + (o, 'i', None, false), + (a, 'k', None, false), + ] + ); + assert_eq!( + instance(&mut sync, [0, 0, 1, 1], &[&read, &other]), + [ + (a, 'm', None, false), + (r, 'i', Some([20, 4, 24, 6]), true), + (o, 'i', None, false), + (a, 'k', None, false), + ] + ); +} + /// A copy back of a part of a one-level, one-slice texture's image is its region cut to the /// rectangle: the buffer's offset moved to the rectangle's first texel at the region's row length, /// clamped to the image, and nothing where no texel lies inside. @@ -656,10 +1010,11 @@ fn a_shadow_whose_writes_are_dropped_is_copied_in_again_and_never_back() { } /// A use that replaces every texel before it reads any (a pass's attachment that clears the -/// whole of a one-level, one-slice texture, `ShadowUse::overwrites`) takes no copy in, and the -/// image is current after it: storing it, the pass's writes are copied back as the encoder ends; -/// not storing it, nothing is, and the buffer keeps its bytes. Joined with a use that reads, it -/// is copied in (`shadow::join`), and a texture kept to merge a write two ways still copies in. +/// whole of a one-level, one-slice texture, `ShadowUse::overwrites`) takes no copy in and no +/// keep, and the image is current after it: storing it, the pass's writes are copied back as the +/// encoder ends; not storing it, nothing is, and the buffer keeps its bytes. Joined with a use +/// that reads, it is copied in and kept for its merge back (`shadow::join`), and a texture kept +/// to merge a write two ways still copies in. #[test] fn a_use_that_overwrites_every_texel_takes_no_copy_in() { let buffer = ResourceKey::new(); @@ -677,7 +1032,7 @@ fn a_use_that_overwrites_every_texel_takes_no_copy_in() { let mut sync = ShadowSync::::default(); let shadows = [overwriting(stores)]; let uses = [written.clone()]; - let copies = sync.before(&shadows, &uses, |_| Ok(0)).unwrap(); + let copies = sync.before(&shadows, &uses, |_, _, _| Ok(0)).unwrap(); assert_eq!(named(&copies), [], "stores {stores}"); sync.after(&shadows, &uses, &[]); assert_eq!( @@ -697,71 +1052,92 @@ fn a_use_that_overwrites_every_texel_takes_no_copy_in() { assert!(!joined[0].overwrites && joined[0].writes); let mut sync = ShadowSync::::default(); let copies = sync - .before(&joined, std::slice::from_ref(&written), |_| Ok(0)) + .before(&joined, std::slice::from_ref(&written), |_, _, _| Ok(0)) .unwrap(); - assert_eq!(named(&copies), [(t.shadow_key, true)]); + assert_eq!( + moved(&copies), + [Moved::Into(t.shadow_key), Moved::Keep(t.shadow_key, 0)] + ); // Written two ways (the bytes too), the texture is kept and copied in. let mut sync = ShadowSync::::default(); let uses = [written, bytes(buffer, 256..512, true)]; - let copies = sync.before(&[overwriting(true)], &uses, |_| Ok(7)).unwrap(); + .before(&[overwriting(true)], &uses, |_, _, _| Ok(7)) assert_eq!( moved(&copies), [Moved::Into(t.shadow_key), Moved::Keep(t.shadow_key, 7)] ); } +/// A command that touches a texture's bytes another way takes the merge of what was written +/// through it first: a read of the bytes leaves the image current, a write leaves it to copy in +/// again at its next use. Bytes elsewhere, or another buffer's, take nothing. #[test] fn a_command_touching_the_bytes_another_way_orders_the_copies_around_it() { let buffer = ResourceKey::new(); let t = shadow(buffer, 256..1280); + let k = t.shadow_key; + let mut made = 0; + let mut run = |sync: &mut ShadowSync, + textures: &[(&Arc, bool)], + others: &[Use]| { + moved(&planned(sync, &mut made, textures, others)) + }; let mut sync = ShadowSync::default(); - command(&mut sync, &[(&t, true)], &[]); + assert_eq!( + run(&mut sync, &[(&t, true)], &[]), + [Moved::Into(k), Moved::Keep(k, 1)] + ); // Bytes elsewhere in the buffer, or another buffer's: nothing to copy. - assert_eq!(command(&mut sync, &[], &[bytes(buffer, 0..256, true)]), []); + assert_eq!(run(&mut sync, &[], &[bytes(buffer, 0..256, true)]), []); let other = ResourceKey::new(); - assert_eq!(command(&mut sync, &[], &[bytes(other, 0..4096, true)]), []); + assert_eq!(run(&mut sync, &[], &[bytes(other, 0..4096, true)]), []); // A read of the bytes: the texture's writes first; the image stays current. assert_eq!( - command(&mut sync, &[], &[bytes(buffer, 0..4096, false)]), - [(t.shadow_key, false)] + run(&mut sync, &[], &[bytes(buffer, 0..4096, false)]), + [Moved::Merge(k, 1)] ); - assert_eq!(command(&mut sync, &[(&t, false)], &[]), []); + assert_eq!(run(&mut sync, &[(&t, false)], &[]), []); // A write of the bytes: the next use copies them in again. - command(&mut sync, &[(&t, true)], &[]); + assert_eq!(run(&mut sync, &[(&t, true)], &[]), [Moved::Keep(k, 1)]); assert_eq!( - command(&mut sync, &[], &[bytes(buffer, 1024..1028, true)]), - [(t.shadow_key, false)] + run(&mut sync, &[], &[bytes(buffer, 1024..1028, true)]), + [Moved::Merge(k, 1)] ); - assert_eq!( - command(&mut sync, &[(&t, false)], &[]), - [(t.shadow_key, true)] - ); - assert_eq!(named(&sync.finish()), []); + assert_eq!(run(&mut sync, &[(&t, false)], &[]), [Moved::Into(k)]); + assert_eq!(moved(&sync.finish()), []); } +/// Textures over the same bytes see each other's writes: one written is merged back before +/// another over its bytes is copied in, and leaves the other to copy in again at its next use. A +/// texture over other bytes is left alone. #[test] fn textures_over_the_same_bytes_see_each_others_writes() { let buffer = ResourceKey::new(); let a = shadow(buffer, 0..1024); let b = shadow(buffer, 512..2048); let apart = shadow(buffer, 4096..8192); + let (ka, kb, kapart) = (a.shadow_key, b.shadow_key, apart.shadow_key); + let mut made = 0; + let mut run = |sync: &mut ShadowSync, textures: &[(&Arc, bool)]| { + moved(&planned(sync, &mut made, textures, &[])) + }; let mut sync = ShadowSync::default(); assert_eq!( - command(&mut sync, &[(&a, true), (&apart, false)], &[]), - [(a.shadow_key, true), (apart.shadow_key, true)] + run(&mut sync, &[(&a, true), (&apart, false)]), + [Moved::Into(ka), Moved::Into(kapart), Moved::Keep(ka, 1)] ); - // `a` written: `b` is copied in after `a` is copied back. + // `a` written: `b` is copied in after `a` is merged back. assert_eq!( - command(&mut sync, &[(&b, false)], &[]), - [(a.shadow_key, false), (b.shadow_key, true)] + run(&mut sync, &[(&b, false)]), + [Moved::Merge(ka, 1), Moved::Into(kb)] ); - // `b` written: `a` is copied in again at its next use, after `b`'s copy back. - command(&mut sync, &[(&b, true)], &[]); + // `b` written: `a` is copied in again at its next use, after `b`'s merge. + assert_eq!(run(&mut sync, &[(&b, true)]), [Moved::Keep(kb, 2)]); assert_eq!( - command(&mut sync, &[(&a, false), (&apart, false)], &[]), - [(b.shadow_key, false), (a.shadow_key, true)] + run(&mut sync, &[(&a, false), (&apart, false)]), + [Moved::Merge(kb, 2), Moved::Into(ka)] ); - assert_eq!(named(&sync.finish()), []); + assert_eq!(moved(&sync.finish()), []); } /// Two textures over two no-copy buffers made over the same host memory, the second of which @@ -782,42 +1158,49 @@ fn textures_over_two_buffers_of_one_memory_see_each_others_writes() { false => uses.to_vec(), } }; + let (ka, kb, kc) = (a.shadow_key, b.shadow_key, c.shadow_key); + let mut made = 0; + let mut run = |sync: &mut ShadowSync, + textures: &[(&Arc, bool)], + others: &[Use]| { + moved(&planned(sync, &mut made, textures, others)) }; let mut sync = ShadowSync::default(); assert_eq!( - command(&mut sync, &[(&a, true), (&c, false)], &[]), - [(a.shadow_key, true), (c.shadow_key, true)] + run(&mut sync, &[(&a, true), (&c, false)], &[]), + [Moved::Into(ka), Moved::Into(kc), Moved::Keep(ka, 1)] ); - // `a` written: `b` is copied in after `a` is copied back; `c` lies elsewhere. + // `a` written: `b` is copied in after `a` is merged back; `c` lies elsewhere. assert_eq!( - command(&mut sync, &[(&b, false), (&c, false)], &[]), - [(a.shadow_key, false), (b.shadow_key, true)] + run(&mut sync, &[(&b, false), (&c, false)], &[]), + [Moved::Merge(ka, 1), Moved::Into(kb)] ); - // `b` written: `a` is copied in again at its next use, after `b`'s copy back. - command(&mut sync, &[(&b, true)], &[]); + // `b` written: `a` is copied in again at its next use, after `b`'s merge. + assert_eq!(run(&mut sync, &[(&b, true)], &[]), [Moved::Keep(kb, 2)]); assert_eq!( - command(&mut sync, &[(&a, false)], &[]), - [(b.shadow_key, false), (a.shadow_key, true)] + run(&mut sync, &[(&a, false)], &[]), + [Moved::Merge(kb, 2), Moved::Into(ka)] ); // The second buffer's bytes written: `a` copies in again, and so does `b`. let written = augmented(&[bytes(second, 0..64, true)]); assert_eq!(written.len(), 2); - assert_eq!(command(&mut sync, &[], &written), []); + assert_eq!(run(&mut sync, &[], &written), []); assert_eq!( - command(&mut sync, &[(&a, false), (&b, false)], &[]), - [(a.shadow_key, true), (b.shadow_key, true)] + run(&mut sync, &[(&a, false), (&b, false)], &[]), + [Moved::Into(ka), Moved::Into(kb)] ); // The third buffer's bytes written: neither does. - command(&mut sync, &[], &augmented(&[bytes(other, 0..64, true)])); - assert_eq!(command(&mut sync, &[(&a, false), (&b, false)], &[]), []); - assert_eq!(named(&sync.finish()), []); + run(&mut sync, &[], &augmented(&[bytes(other, 0..64, true)])); + assert_eq!(run(&mut sync, &[(&a, false), (&b, false)], &[]), []); + assert_eq!(moved(&sync.finish()), []); } /// One command that writes through a texture and its bytes another way (the buffer, or another -/// texture over them) keeps the texture after its copies in, and the merge goes before the next -/// command, whatever it touches, or at the end, after which the texture is copied in again at -/// its next use. Reading the bytes, writing bytes the texture does not lie in, or reading the -/// other texture is one way. +/// texture over them) keeps the texture after its copies in, in a scratch of its own, and the +/// merge goes before the next command, whatever it touches, or at the end, after which the +/// texture is copied in again at its next use. Reading the bytes, writing bytes the texture does +/// not lie in, or reading the other texture is one way: kept in the encoder's scratch, and merged +/// back at the end. #[test] fn one_command_writing_a_texture_and_its_bytes_another_way_keeps_and_merges_it() { let buffer = ResourceKey::new(); @@ -860,22 +1243,70 @@ fn one_command_writing_a_texture_and_its_bytes_another_way_keeps_and_merges_it() [Moved::Merge(ka, 4), Moved::Into(ka), Moved::Keep(ka, 5)] ); assert_eq!(moved(&sync.finish()), [Moved::Merge(ka, 5)]); - // One way: no keep, and a copy back at the end. - for others in [ - vec![bytes(buffer, 0..4096, false)], - vec![bytes(buffer, 1024..4096, true)], + // One way: the encoder's scratch, merged at the end. + for (n, others) in [ + (6, vec![bytes(buffer, 0..4096, false)]), + (7, vec![bytes(buffer, 1024..4096, true)]), ] { let mut sync = ShadowSync::default(); - assert_eq!(run(&mut sync, &[(&a, true)], &others), [Moved::Into(ka)]); - assert_eq!(moved(&sync.finish()), [Moved::Back(ka)]); + assert_eq!( + run(&mut sync, &[(&a, true)], &others), + [Moved::Into(ka), Moved::Keep(ka, n)] + ); + assert_eq!(moved(&sync.finish()), [Moved::Merge(ka, n)]); } let mut sync = ShadowSync::default(); assert_eq!( run(&mut sync, &[(&a, true), (&b, false)], &[]), - [Moved::Into(ka), Moved::Into(kb)] + [Moved::Into(ka), Moved::Into(kb), Moved::Keep(ka, 8)] ); } +/// A texture over a buffer's bytes (`ShadowCopies::merges_back`): the image is kept after its copy +/// in, before the first command since the last copy back that writes through it, and that copy +/// back is a merge, in one scratch of the encoder's, after which the image still holds the bytes: +/// a later read takes no copy in, and a later write keeps it again in the same scratch. A command +/// that touches its bytes another way takes the merge first. A command that replaces every texel +/// keeps nothing and is copied back, before the keep of a later command that writes through it +/// without replacing them; one that writes the bytes two ways is kept in a scratch of its own and +/// merged before the next command. An image's shadow, one whose writes Metal drops, and one over a +/// tracked `Private` buffer's bytes, which no other writer writes while a command buffer runs, +/// merge nothing back: the last is copied in and back; an untracked `Private` buffer's merges. +fn a_texture_over_a_buffer_s_bytes_is_merged_where_it_would_be_copied_back() { + let a = shadow(buffer, 0..1024); + assert!(a.merges_back()); + assert!(!image_shadow(ResourceKey::new(), 0, 1).merges_back()); + assert!(over_private(shadow(buffer, 0..1024), false).merges_back()); + let private = over_private(shadow(buffer, 0..1024), true); + assert!(!private.merges_back()); + let mut dropped = Arc::into_inner(shadow(buffer, 0..1024)).expect("one holder"); + dropped.drops_writes = true; + assert!(!dropped.merges_back()); + // Over a tracked `Private` buffer's bytes: copied in and back, nothing kept. + let kp = private.shadow_key; + let mut sync = ShadowSync::default(); + assert_eq!(run(&mut sync, &[(&private, true)], &[]), [Moved::Into(kp)]); + assert_eq!(run(&mut sync, &[(&private, true)], &[]), []); + assert_eq!(moved(&sync.finish()), [Moved::Back(kp)]); + .before(std::slice::from_ref(&replacing), &uses, |_, _, _| Ok(9)) + // Every texel replaced, then written through without replacing them: the first command's + // writes are copied back before the keep, as the merge after it takes only the words changed + // since the keep. + let mut sync = ShadowSync::::default(); + sync.before(std::slice::from_ref(&replacing), &uses, |_, _, _| Ok(9)) + .unwrap(); + sync.after(std::slice::from_ref(&replacing), &uses, &[]); + assert_eq!( + run(&mut sync, &[(&a, true)], &[]), + [Moved::Back(ka), Moved::Keep(ka, 3)] + ); + assert_eq!(moved(&sync.finish()), [Moved::Merge(ka, 3)]); + [Moved::Into(ka), Moved::Keep(ka, 4)] + [Moved::Merge(ka, 4), Moved::Into(ka), Moved::Keep(ka, 5)] + ); + assert_eq!(moved(&sync.finish()), [Moved::Merge(ka, 5)]); +} + /// A command whose scratch is refused changes nothing: the next command copies the texture in. #[test] fn a_refused_scratch_changes_nothing() { @@ -883,7 +1314,7 @@ fn a_refused_scratch_changes_nothing() { let a = shadow(buffer, 0..1024); let mut sync = ShadowSync::::default(); let (shadows, uses) = command_uses(&[(&a, true)], &[bytes(buffer, 0..4096, true)]); - let refused = sync.before(&shadows, &uses, |_| Err(internal("no scratch"))); + let refused = sync.before(&shadows, &uses, |_, _, _| Err(internal("no scratch"))); assert!( matches!(refused, Err(Error::Compile(_))), "{:?}", @@ -916,6 +1347,8 @@ fn view_of(image: ResourceKey, levels: Range, layers: Range) -> Arc::default(); let (shadows, uses) = command_uses(textures, &others); - let refused = sync.before(&shadows, &uses, |_| panic!("a merge of an image's shadow")); + let refused = sync.before(&shadows, &uses, |_, _, _| { match refused { Err(Error::Unsupported(gap)) => { assert_eq!(gap.feature, Feature::ViewFormatReinterpretation) @@ -1023,7 +1456,7 @@ fn a_command_writing_an_image_through_a_views_shadow_and_another_way_is_refused( let mut sync = ShadowSync::::default(); let (shadows, uses) = command_uses(textures, &others); let copies = sync - .before(&shadows, &uses, |_| panic!("a merge of an image's shadow")) + .before(&shadows, &uses, |_, _, _| { .unwrap(); let into: Vec<(ResourceKey, bool)> = textures .iter() @@ -1032,3 +1465,250 @@ fn a_command_writing_an_image_through_a_views_shadow_and_another_way_is_refused( assert_eq!(named(&copies), into); } } + +/// A shadow of level `level` and slice 0 of the image `image`, 64x32 there, copied image to image +/// (a 2D texture's own image's, `texture/usage_shadow.rs`), with `layers` slices in its one region. +fn image_shadow(image: ResourceKey, level: u32, layers: u32) -> Arc { + let mut copies = + Arc::into_inner(view_of(image, level..level + 1, 0..layers)).expect("one holder"); + if let ShadowSource::Image { regions, .. } = &mut copies.source { + let subresource = vk::ImageSubresourceLayers { + aspect_mask: vk::ImageAspectFlags::COLOR, + mip_level: level, + base_array_layer: 0, + layer_count: layers, + }; + regions.push(vk::ImageCopy { + src_subresource: subresource, + dst_subresource: subresource, + extent: vk::Extent3D { + width: 64, + height: 32, + depth: 1, + }, + ..Default::default() + }); + } + Arc::new(copies) +} + +/// Each copy's step (into the shadow, or not), area, and why a copy in is made. +fn causes(copies: &[ShadowCopy]) -> Vec<(bool, Option<[u32; 4]>, Option)> { + copies + .iter() + .map(|copy| (matches!(copy.step, Step::Into), copy.area, copy.cause)) + .collect() +} + +/// A shadow of one level and one slice of an image, copied image to image, is cut to rectangles +/// as a one-level, one-slice texture's over a buffer is (`ShadowCopies::cuts`): a read inside a +/// rectangle copies in the texels there, a later read anywhere every texel (beyond what the +/// shadow held), writes within a rectangle of the image the texels they changed alone, and each +/// cut copy moves the texels inside its rectangle. Its copies back move every texel, so a command +/// that writes through it copies every texel in first. A shadow of several slices is not cut. +#[test] +fn an_images_shadow_of_one_level_and_slice_is_cut_as_a_buffers_texture_is() { + let image = ResourceKey::new(); + let s = image_shadow(image, 2, 1); + assert!(s.cuts()); + assert_eq!(s.texels(), 64 * 32); + assert!(!image_shadow(image, 2, 2).cuts()); + let (_, read) = through(&s, false); + let reader = |area: [u32; 4]| ShadowUse { + loads: Some(area), + ..through(&s, false).0 + }; + let attachment = texels(image, 2..3, 0..1, true); + let drawn = |area: [u32; 4]| Within { + uses: vec![attachment.clone()], + texels: Some(Arc::clone(&s)), + area, + }; + let command = |sync: &mut ShadowSync, shadows: &[ShadowUse], parts: &[Within]| { + let mut uses = vec![read.clone()]; + uses.extend(parts.iter().flat_map(|part| part.uses.iter().cloned())); + let copies = sync.before(shadows, &uses, |_, _, _| Ok(0)).unwrap(); + sync.after(shadows, std::slice::from_ref(&read), parts); + copies + }; + let mut sync = ShadowSync::::default(); + let a = [8, 4, 12, 6]; + let copies = command(&mut sync, &[reader(a)], &[]); + assert_eq!(causes(&copies), [(true, Some(a), Some(CopyCause::First))]); + assert_eq!(copies[0].texels_copied_in(), 4 * 2); + // Inside what the shadow holds: nothing. + assert!(command(&mut sync, &[reader([9, 4, 10, 5])], &[]).is_empty()); + // A read anywhere: every texel, beyond what the shadow held. + let anywhere = through(&s, false).0; + let copies = command(&mut sync, std::slice::from_ref(&anywhere), &[]); + assert_eq!(causes(&copies), [(true, None, Some(CopyCause::BeyondHeld))]); + assert_eq!(copies[0].texels_copied_in(), 64 * 32); + // Draws within a rectangle of the image's level: the texels they changed alone. + command(&mut sync, &[], &[drawn([20, 10, 30, 14])]); + let copies = command(&mut sync, std::slice::from_ref(&anywhere), &[]); + assert_eq!( + causes(&copies), + [(true, Some([20, 10, 30, 14]), Some(CopyCause::Bounded))] + ); + assert_eq!(copies[0].texels_copied_in(), 10 * 4); + // A write of the level another way: every texel, after the change. + sync.after(&[], &[texels(image, 2..3, 0..1, true)], &[]); + let copies = command(&mut sync, std::slice::from_ref(&anywhere), &[]); + let written = Some(CopyCause::Changed(Lost::Written)); + assert_eq!(causes(&copies), [(true, None, written)]); + // Writes within a rectangle whose texels are a shadow's laid out otherwise (another level's): + // every texel. + let other_level = image_shadow(image, 1, 1); + let elsewhere = Within { + uses: vec![texels(image, 2..3, 0..1, true)], + texels: Some(Arc::clone(&other_level)), + area: a, + }; + command(&mut sync, &[], &[elsewhere]); + let copies = command(&mut sync, std::slice::from_ref(&anywhere), &[]); + let within = Some(CopyCause::Changed(Lost::Within)); + assert_eq!(causes(&copies), [(true, None, within)]); + // A command writing through it reads and writes inside a rectangle, yet takes every texel in: + // its copy back moves every texel. + let mut sync = ShadowSync::::default(); + command(&mut sync, &[reader(a)], &[]); + let writer = ShadowUse { + writes: true, + area: Some(a), + loads: Some(a), + ..through(&s, true).0 + }; + let written = through(&s, true).1; + let copies = sync + .before( + std::slice::from_ref(&writer), + std::slice::from_ref(&written), + |_, _, _| Ok(0), + ) + .unwrap(); + assert_eq!(causes(&copies), [(true, None, Some(CopyCause::BeyondHeld))]); + sync.after(std::slice::from_ref(&writer), &[written], &[]); + assert_eq!(named(&sync.finish()), [(s.shadow_key, false)]); + // Two shadows of one level and slice of one image hold its texels alike; another level's do + // not, nor another image's. + assert!(s.same_texels(&image_shadow(image, 2, 1))); + assert!(!s.same_texels(&other_level)); + assert!(!s.same_texels(&image_shadow(ResourceKey::new(), 2, 1))); +} + +/// A part of an image's region is the same texels of both images, offset alike, clamped to the +/// region, and nothing where no texel lies inside. +#[test] +fn a_part_of_an_images_region_moves_both_offsets() { + let layers = vk::ImageSubresourceLayers { + aspect_mask: vk::ImageAspectFlags::COLOR, + mip_level: 1, + base_array_layer: 3, + layer_count: 1, + }; + let region = vk::ImageCopy { + src_subresource: layers, + src_offset: vk::Offset3D { x: 0, y: 0, z: 0 }, + dst_subresource: layers, + dst_offset: vk::Offset3D { x: 0, y: 0, z: 0 }, + extent: vk::Extent3D { + width: 16, + height: 8, + depth: 1, + }, + }; + let part = shadow::image_part_of(®ion, [2, 1, 6, 3]).unwrap(); + let at = |o: vk::Offset3D| (o.x, o.y, o.z); + assert_eq!( + (at(part.src_offset), at(part.dst_offset)), + ((2, 1, 0), (2, 1, 0)) + ); + assert_eq!( + (part.extent.width, part.extent.height, part.extent.depth), + (4, 2, 1) + ); + assert_eq!( + ( + part.src_subresource.mip_level, + part.dst_subresource.base_array_layer + ), + (1, 3) + ); + let clamped = shadow::image_part_of(®ion, [12, 6, 40, 40]).unwrap(); + assert_eq!((clamped.extent.width, clamped.extent.height), (4, 2)); + assert!(shadow::image_part_of(®ion, [16, 0, 20, 8]).is_none()); + assert!(shadow::image_part_of(®ion, [3, 3, 3, 5]).is_none()); +} + +/// The encoder's scratch keeps the rectangle its commands write in, where they bound it and the +/// copies are cut to rectangles: a later command that writes inside it +/// keeps nothing more; one that writes outside it takes the merge of what was kept, and a scratch +/// of the rectangle bounding both, kept again after its copy in; one that writes anywhere, a +/// scratch of every texel, which then holds every later write. +#[test] +fn a_keep_holds_the_rectangle_its_commands_write_in() { + let buffer = ResourceKey::new(); + let a = cut_shadow(buffer, 0..8192); + assert!(a.merges_back()); + let written = through(&a, true).1; + let mut made = 0; + let mut run = |sync: &mut ShadowSync, area: Option<[u32; 4]>| { + let writer = ShadowUse { + writes: true, + area, + loads: area, + ..through(&a, true).0 + }; + let copies = sync + .before( + std::slice::from_ref(&writer), + std::slice::from_ref(&written), + |_, _, kept| { + made += 1; + Ok(Boxed(made, kept)) + }, + ) + .unwrap(); + sync.after( + std::slice::from_ref(&writer), + std::slice::from_ref(&written), + &[], + ); + kept_steps(&copies) + }; + let mut sync = ShadowSync::default(); + assert_eq!( + run(&mut sync, Some([8, 4, 24, 12])), + ["into Some([8, 4, 24, 12])", "keep 1 Some([8, 4, 24, 12])"] + ); + assert!(run(&mut sync, Some([10, 5, 20, 10])).is_empty(), "inside"); + assert_eq!( + run(&mut sync, Some([30, 0, 40, 8])), + [ + "merge 1 Some([8, 4, 24, 12])", + "into Some([30, 0, 40, 8])", + "keep 2 Some([8, 0, 40, 12])" + ], + "outside" + ); + assert_eq!( + run(&mut sync, None), + ["merge 2 Some([8, 0, 40, 12])", "into None", "keep 3 None"], + "anywhere" + ); + assert!(run(&mut sync, Some([0, 0, 4, 4])).is_empty(), "held"); + assert_eq!(kept_steps(&sync.finish()), ["merge 3 None"]); +} + +/// Each copy's step, with its area, or its scratch's number and rectangle. +fn kept_steps(copies: &[ShadowCopy]) -> Vec { + copies + .iter() + .map(|copy| match ©.step { + Step::Into => format!("into {:?}", copy.area), + Step::Back => format!("back {:?}", copy.area), + Step::Keep(Boxed(n, area)) => format!("keep {n} {area:?}"), + Step::Merge(Boxed(n, area)) => format!("merge {n} {area:?}"), + }) + .collect() +} diff --git a/crates/metal2vulkan-runtime/src/tests/shadow_host_writes.rs b/crates/metal2vulkan-runtime/src/tests/shadow_host_writes.rs new file mode 100644 index 000000000..d430c2b73 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/shadow_host_writes.rs @@ -0,0 +1,29 @@ +//! A shadow's bytes over host pages lie in no `VkBuffer` while they are detached +//! (`ShadowBuffer::raw`): the device's stand-in, which holds none of them, is never what a copy +//! or a merge's window takes, and a rebind gives the new pages' `VkBuffer`. +//! +use crate::shadow::ShadowBuffer; +use ash::vk; + +/// A shadow's bytes over a no-copy buffer's host pages, detached, lie in no `VkBuffer` (a merge +/// planned then bound a window of the device's 256-byte stand-in past its size, +/// `VUID-VkDescriptorBufferInfo-range-00342`), and in the new pages' once a rebind gives them. +#[test] +fn a_shadow_over_detached_host_pages_takes_no_buffer_until_a_rebind() { + let scratch = Scratch::new("shadow-host-writes-detached"); + let (host, other) = (Host::new(), Host::new()); + let runs = Arc::new(AtomicUsize::new(0)); + let Some(buffer) = over_host(&device, &host, &runs) else { + return; + }; + let shadow = ShadowBuffer::of(&buffer, buffer.at(0).0); + assert_eq!(shadow.raw(), buffer.at(0).0, "in pages"); + assert_eq!(buffer.detach_backing(), Ok(true), "the detach"); + assert_eq!(shadow.raw(), vk::Buffer::null(), "detached"); + // SAFETY: `other` outlives the buffer (dropped after the device), which alone uses it. + unsafe { buffer.rebind_bytes_no_copy(other.memory(), None, None) }.unwrap(); + assert_ne!(shadow.raw(), vk::Buffer::null(), "given pages again"); + assert_eq!(shadow.raw(), buffer.at(0).0, "given pages again"); + drop(buffer); + drop(device); +} diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 86c96bee0..634b9e2ee 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -2174,7 +2174,7 @@ impl Device { // Where the device copies a shadow back faster by a dispatch, the image takes the // integer view the dispatch reads (`shadow_copy_back.rs`). let (plan, word) = match shadow_copy_back::dispatches(self) { - true => with_word_view(plan, &facts), + true => with_word_view(plan, &facts, shadow_copy_back::dispatches_in(self)), false => (plan, None), }; let hazard = texels.options().hazard_tracking_mode()?; @@ -2201,7 +2201,11 @@ impl Device { }; // A view the device does not make leaves the copies back copies. The copies hold it as // long as the image, which keeps it through a detach (`Image::own_view`). - let words = word.and_then(|(format, words)| { + let words = word.and_then(|(format, texel, stores)| { + let usage = match stores { + true => ImageUsageFlags::SAMPLED | ImageUsageFlags::STORAGE, + false => ImageUsageFlags::SAMPLED, + }; let view = image.own_view(&VkView { view_type: ImageViewType::TYPE_2D, format, @@ -2211,9 +2215,13 @@ impl Device { level_count: 1, base_layer: 0, layer_count: 1, - usage: ImageUsageFlags::SAMPLED, + usage, }); - view.ok().map(|view| WordView { view, words }) + view.ok().map(|view| WordView { + view, + texel, + stores, + }) }); let copies = texels.shadow_copies(image.raw.get(), image.identity, aspects, words)?; // Its copies keep its own image, which it presents again once the bytes lie in pages. diff --git a/crates/metal2vulkan-runtime/src/texture/attached_reads.rs b/crates/metal2vulkan-runtime/src/texture/attached_reads.rs index 10ea412ef..9f1316b3d 100644 --- a/crates/metal2vulkan-runtime/src/texture/attached_reads.rs +++ b/crates/metal2vulkan-runtime/src/texture/attached_reads.rs @@ -40,16 +40,16 @@ //! (`WorkCounts::attachment_reads_through_copies`, the shadow served or not), and so does each //! copy (`WorkCounts::shadow_copies`). It is exact and announces nothing. //! - **Only what the instances drew.** A copy after the pass's first instance, of a buffer's -//! bytes, where the instances since the last copy changed them only by their draws into a -//! color attachment the pass loads (the encoder's load, single-sampled, resolved nowhere, -//! rendered in place, the whole of a one-level, one-slice texture), moves only the texels -//! inside the rectangle bounding those instances' draws' scissors: a draw changes no texel -//! outside its scissors, and the load and store write back what they read -//! (`render/shadows.rs`). Every other texel of the shadow holds the bytes from the last copy -//! (`shadow.rs`, `WorkCounts::bounded_shadow_copies`). Any other write of the bytes (a clear, -//! a `DontCare` load, a resolve, a stand-in, a storage write, a tile dispatch, an execution, a -//! rasterization-rate map), a texture's image as the truth, and the first copy of each -//! encoder copy every texel. +//! bytes or of an image's one level and slice, where the instances since the last copy changed +//! them only by their draws into a color attachment the pass loads (the encoder's load, +//! single-sampled, resolved nowhere, rendered in place, the whole of a one-level, one-slice +//! texture), moves only the texels inside the rectangle bounding those instances' draws' +//! scissors: a draw changes no texel outside its scissors, and the load and store write back +//! what they read (`render/shadows.rs`). Every other texel of the shadow holds the truth's from +//! the last copy (`shadow.rs`, `WorkCounts::bounded_shadow_copies`). Any other write of the +//! truth (a clear, a `DontCare` load, a resolve, a stand-in, a storage write, a tile dispatch, +//! an execution, a rasterization-rate map), an image's several levels or slices as the truth, +//! and the first copy of each encoder copy every texel. //! - **Only what a draw reads at its own pixels.** A draw every binding of whose texture is a //! fragment slot its function reads at the fragment's own pixel alone //! (`StageModule::own_pixel_textures`: an `OpImageFetch` at level 0 of Metal's saturating diff --git a/crates/metal2vulkan-runtime/src/texture/heap.rs b/crates/metal2vulkan-runtime/src/texture/heap.rs index ed3e73d4e..86237f5a7 100644 --- a/crates/metal2vulkan-runtime/src/texture/heap.rs +++ b/crates/metal2vulkan-runtime/src/texture/heap.rs @@ -175,7 +175,8 @@ use crate::memory::{Memory, MemoryClass, Placement}; use crate::metal_level::MetalLevel; use crate::release; use crate::resource::{Identity, ResourceKey}; -use crate::shadow::{ShadowBuffer, ShadowCopies, ShadowSource, ShadowTarget}; +use crate::shadow::{Backing, ShadowBuffer, ShadowCopies, ShadowSource, ShadowTarget}; +use crate::shadow_merge::ScratchSpares; use crate::texture_descriptor::{effective_usage, Creator, TextureLayout, TextureProblem}; use crate::tracker::UseRange; use crate::two_planes; @@ -2601,6 +2602,8 @@ impl Device { shadow_range, tracked: identity.tracked, drops_writes: false, + backing: Backing::of(bytes, false), + merge_scratch: ScratchSpares::default(), }; Owner::HeapShadow(Box::new(HeapShadow { placement, @@ -2687,6 +2690,8 @@ impl Device { shadow_range, tracked: identity.tracked, drops_writes: false, + backing: Backing::of(bytes, false), + merge_scratch: ScratchSpares::default(), }; Owner::HeapShadow(Box::new(HeapShadow { placement, @@ -2764,6 +2769,8 @@ impl Device { shadow_range, tracked: identity.tracked, drops_writes: false, + backing: Backing::of(bytes, false), + merge_scratch: ScratchSpares::default(), }; Owner::HeapShadow(Box::new(HeapShadow { placement, diff --git a/crates/metal2vulkan-runtime/src/texture/surface_depth.rs b/crates/metal2vulkan-runtime/src/texture/surface_depth.rs index b2793c9eb..7bd8f8c54 100644 --- a/crates/metal2vulkan-runtime/src/texture/surface_depth.rs +++ b/crates/metal2vulkan-runtime/src/texture/surface_depth.rs @@ -29,6 +29,7 @@ use super::super::copy_plan::{surface_depth_unit, CopyUnit}; use super::super::error::{internal, Error, RuntimeGap}; use super::super::image_plan::{plan_image, ImagePlan}; use super::super::shadow::{ShadowBuffer, ShadowCopies, ShadowSource, ShadowTarget}; +use super::super::shadow_merge::ScratchSpares; use super::super::texture_descriptor::{texture_usage, TextureDescriptor, TextureLayout}; use super::super::tracker::UseRange; use super::super::values::ResourceOptions; @@ -163,6 +164,8 @@ impl Texture { }, tracked: texels.tracked(), drops_writes: false, + backing: texels.backing(), + merge_scratch: ScratchSpares::default(), }; let storage = Storage::Shadow { image: image.shared(), diff --git a/crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs b/crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs index 44931f573..98687ea94 100644 --- a/crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs +++ b/crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs @@ -59,6 +59,7 @@ use crate::error::{Error, RuntimeGap}; use crate::image_plan::plan_image; use crate::linear_plan::{BufferLayout, LINEAR_ALIGNMENT}; use crate::shadow::{ShadowBuffer, ShadowCopies, ShadowSource, ShadowTarget}; +use crate::shadow_merge::ScratchSpares; use crate::texture_descriptor::{texture_usage, TextureDescriptor, TextureLayout}; use crate::tracker::UseRange; use crate::view_plan::ViewRecord; @@ -234,6 +235,8 @@ impl Device { }, tracked: texels.tracked(), drops_writes: false, + backing: texels.backing(), + merge_scratch: ScratchSpares::default(), }; self.degrade(Degradation::ShadowedTexture, || { let [width, height, _] = layout.extent; diff --git a/crates/metal2vulkan-runtime/src/texture/usage_shadow.rs b/crates/metal2vulkan-runtime/src/texture/usage_shadow.rs index b414a5367..a15b6349d 100644 --- a/crates/metal2vulkan-runtime/src/texture/usage_shadow.rs +++ b/crates/metal2vulkan-runtime/src/texture/usage_shadow.rs @@ -285,12 +285,16 @@ impl Texture { descriptor.resource_options = ResourceOptions::new(StorageMode::Private, CpuCacheMode::DefaultCache, hazard); let image = device.new_image(plan, &layout, &descriptor, hazard)?; - let copies = texels.shadow_copies( + let mut copies = texels.shadow_copies( image.raw.get(), image.identity, texture_aspects(image.plan()), None, )?; + // The texture's own image lies in the bytes too where it aliases them. + if matches!(self.0.storage, Storage::Alias { .. }) { + copies.backing = copies.backing.aliased(); + } ( image.shared(), Arc::new(copies), diff --git a/crates/metal2vulkan-runtime/src/texture/view_shadow.rs b/crates/metal2vulkan-runtime/src/texture/view_shadow.rs index 4a0ce7f00..7ca706727 100644 --- a/crates/metal2vulkan-runtime/src/texture/view_shadow.rs +++ b/crates/metal2vulkan-runtime/src/texture/view_shadow.rs @@ -61,7 +61,8 @@ use crate::image_plan::plan_image; use crate::image_plan::{copies_between, takes_views_of}; use crate::memory::Placement; use crate::resource::{Identity, ResourceKey}; -use crate::shadow::{ImageThrough, ShadowCopies, ShadowSource}; +use crate::shadow::{Backing, ImageThrough, ShadowCopies, ShadowSource}; +use crate::shadow_merge::ScratchSpares; use crate::texture::{copy_units, image_error, texture_aspects}; use crate::texture_descriptor::{TextureDescriptor, TextureLayout}; use crate::tracker::UseRange; @@ -478,6 +479,8 @@ impl Device { shadow_range, tracked: identity.tracked, drops_writes: false, + backing: Backing::Image, + merge_scratch: ScratchSpares::default(), }; Owner::ViewShadow(Box::new(ViewShadow { placement, diff --git a/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs b/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs index 5536bf557..5e52a924e 100644 --- a/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs +++ b/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs @@ -15,6 +15,7 @@ use crate::device::lock; use crate::error::{internal, Error}; use crate::image_plan::plan_image; use crate::shadow::{ShadowBuffer, ShadowCopies, ShadowSource}; +use crate::shadow_merge::ScratchSpares; use crate::texture_descriptor::{TextureDescriptor, TextureLayout}; use crate::tracker::UseRange; use crate::values::ResourceOptions; @@ -191,6 +192,8 @@ impl Device { tracked: texels.tracked(), // Metal drops a function's writes to the texture (EV XRR2-ycc1-m4). drops_writes: true, + backing: texels.backing(), + merge_scratch: ScratchSpares::default(), }; Ok(Storage::Shadow { image: image.shared(), @@ -346,6 +349,8 @@ impl Texture { }, tracked: texels.tracked(), drops_writes: false, + backing: texels.backing(), + merge_scratch: ScratchSpares::default(), }; Ok((image, copies)) } @@ -475,6 +480,8 @@ impl Texture { }, tracked: texels.tracked(), drops_writes: false, + backing: texels.backing(), + merge_scratch: ScratchSpares::default(), }; let storage = Storage::Shadow { image: image.shared(), diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 9bc5ed94b..331ace12b 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -8,9 +8,14 @@ use super::command_buffer::GroupEnd; use super::degradation::Degradation; use super::device::lock; +use super::shadow::{Backing, CopyCause, Lost, ShadowCopy, ShadowSource}; use super::Device; use ash::vk; use std::sync::atomic::{AtomicU64, Ordering}; +/// The texels of a texture over an IOSurface's plane from which its shadow's copies in count +/// apart (`WorkCounts::shadow_texels_first_copied_in_large_surfaces`, +/// `shadow_texels_recopied_in_large_surfaces`): 2^20, which a 1920x1080 framebuffer's exceed. +const LARGE_SURFACE_TEXELS: u64 = 1 << 20; /// A device's counters (`DeviceShared::counts`), each only ever added to. #[derive(Default)] @@ -175,8 +180,48 @@ pub(crate) struct Counters { shadows_zeroed: AtomicU64, shadow_copies: AtomicU64, shadow_texels_copied_in: AtomicU64, + shadow_texels_first_copied_in: AtomicU64, + shadow_texels_first_copied_in_images: AtomicU64, + shadow_texels_first_copied_in_private_buffers: AtomicU64, + shadow_texels_first_copied_in_mapped_buffers: AtomicU64, + shadow_texels_first_copied_in_host_pages: AtomicU64, + shadow_texels_first_copied_in_aliased_host_pages: AtomicU64, + shadow_texels_first_copied_in_surfaces: AtomicU64, + shadow_texels_first_copied_in_large_surfaces: AtomicU64, + shadow_texels_first_copied_in_again: AtomicU64, + shadow_texels_copied_in_images: AtomicU64, + shadow_texels_recopied_beyond_held: AtomicU64, + shadow_texels_recopied_after_changes: AtomicU64, + shadow_texels_recopied_after_other_shadows: AtomicU64, + shadow_texels_recopied_after_two_ways_merges: AtomicU64, + shadow_texels_recopied_after_writes: AtomicU64, + shadow_texels_recopied_after_writes_within: AtomicU64, + shadow_texels_recopied_after_dropped_writes: AtomicU64, + shadow_texels_bounded_copied_in: AtomicU64, + shadow_texels_recopied_in_images: AtomicU64, + shadow_texels_recopied_in_private_buffers: AtomicU64, + shadow_texels_recopied_in_mapped_buffers: AtomicU64, + shadow_texels_recopied_in_host_pages: AtomicU64, + shadow_texels_recopied_in_aliased_host_pages: AtomicU64, + shadow_texels_recopied_in_surfaces: AtomicU64, + shadow_texels_recopied_in_large_surfaces: AtomicU64, shadow_texels_copied_back: AtomicU64, shadow_copies_back_dispatched: AtomicU64, + shadow_copies_in_dispatched: AtomicU64, + shadow_merge_copies_dispatched: AtomicU64, + shadow_merge_scratches_reused: AtomicU64, + shadow_merge_scratches_zeroed: AtomicU64, + shadow_merges_fetched: AtomicU64, + shadow_attachment_loads_within: AtomicU64, + shadow_attachment_loads_whole: AtomicU64, + shadow_attachment_clears: AtomicU64, + shadow_attachment_clears_in_part: AtomicU64, + shadow_attachment_loads_untouched: AtomicU64, + shadow_attachment_tiles_covered: AtomicU64, + shadow_attachment_tiles_bounded: AtomicU64, + shadows_sharing_truth: AtomicU64, + owned_descriptor_pools: AtomicU64, + shadow_texels_kept: AtomicU64, bounded_shadow_copies: AtomicU64, views_through_swizzle: AtomicU64, view_shadows: AtomicU64, @@ -197,6 +242,23 @@ pub(crate) struct Counters { pipelines_linked: AtomicU64, dispatch_pipelines_pooled: AtomicU64, upload_chunks_in_device_memory: AtomicU64, + +/// How a render pass took a shadowed texture as a color attachment +/// (`WorkCounts::shadow_attachment_loads_within` and kin). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ColorTaken { + /// Loaded, its copies cut to the rectangle bounding the draws' scissors. + LoadedWithin, + /// Loaded (or neither loaded nor cleared), its every texel copied in. + Loaded, + /// Cleared over the whole texture: no copy in. + Cleared, + /// Cleared over part of the texture: its every texel copied in. + ClearedInPart, + /// Loaded in a pass that reaches no tile: no copy in or back. + Untouched, +} + /// What a `VkCommandBuffer` the runtime began was for (`WorkCounts::command_buffers_begun` and /// its parts, `command_buffers_begun_encoders` and kin). #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -1135,6 +1197,66 @@ impl Counters { .fetch_add(texels_back, Ordering::Relaxed); } + /// An encoder planned `copy`, a copy in of a shadowed texture: its texels + /// (`shadow::ShadowCopy::texels_copied_in`) counted by why it is made + /// (`shadow::ShadowCopy::cause`, a change of the truth by its reason), by what holds the truth (`shadow::Backing`), apart where + /// the truth is an IOSurface's plane under a texture of at least [`LARGE_SURFACE_TEXELS`] + /// texels, and apart where the shadow is an image's, copied image to image. Nothing for any + /// other step. + pub(crate) fn shadow_copy_in_planned(&self, copy: &ShadowCopy) { + let Some(cause) = copy.cause else { + return; + }; + let texels = copy.texels_copied_in(); + let add = |counter: &AtomicU64| { + counter.fetch_add(texels, Ordering::Relaxed); + }; + let copies = ©.copies; + if matches!(copies.source, ShadowSource::Image { .. }) { + add(&self.shadow_texels_copied_in_images); + } + let large = copies.backing == Backing::Surface && copies.texels() >= LARGE_SURFACE_TEXELS; + let first = cause == CopyCause::First; + match cause { + CopyCause::First => add(&self.shadow_texels_first_copied_in), + CopyCause::BeyondHeld => add(&self.shadow_texels_recopied_beyond_held), + CopyCause::Changed(lost) => { + add(&self.shadow_texels_recopied_after_changes); + add(match lost { + Lost::OtherShadow => &self.shadow_texels_recopied_after_other_shadows, + Lost::TwoWays => &self.shadow_texels_recopied_after_two_ways_merges, + Lost::Written => &self.shadow_texels_recopied_after_writes, + Lost::Within => &self.shadow_texels_recopied_after_writes_within, + Lost::Dropped => &self.shadow_texels_recopied_after_dropped_writes, + }); + } + CopyCause::Bounded => add(&self.shadow_texels_bounded_copied_in), + } + add(match (first, copies.backing) { + (true, Backing::Image) => &self.shadow_texels_first_copied_in_images, + (true, Backing::PrivateBuffer) => &self.shadow_texels_first_copied_in_private_buffers, + (true, Backing::MappedBuffer) => &self.shadow_texels_first_copied_in_mapped_buffers, + (true, Backing::HostPages) => &self.shadow_texels_first_copied_in_host_pages, + (true, Backing::AliasedHostPages) => { + &self.shadow_texels_first_copied_in_aliased_host_pages + } + (true, Backing::Surface) => &self.shadow_texels_first_copied_in_surfaces, + (false, Backing::Image) => &self.shadow_texels_recopied_in_images, + (false, Backing::PrivateBuffer) => &self.shadow_texels_recopied_in_private_buffers, + (false, Backing::MappedBuffer) => &self.shadow_texels_recopied_in_mapped_buffers, + (false, Backing::HostPages) => &self.shadow_texels_recopied_in_host_pages, + (false, Backing::AliasedHostPages) => { + &self.shadow_texels_recopied_in_aliased_host_pages + } + (false, Backing::Surface) => &self.shadow_texels_recopied_in_surfaces, + }); + match (large, first) { + (true, true) => add(&self.shadow_texels_first_copied_in_large_surfaces), + (true, false) => add(&self.shadow_texels_recopied_in_large_surfaces), + (false, _) => {} + } + } + /// An encoder planned `n` copies in of the texels only writes within a rectangle changed /// since a shadowed texture's copy in (`shadow.rs`, `shadow::Within`). pub(crate) fn bounded_shadow_copies_planned(&self, n: usize) { @@ -1149,6 +1271,88 @@ impl Counters { .fetch_add(1, Ordering::Relaxed); } + /// An encoder recorded a merged shadowed texture's copy in and keep as one dispatch + /// (`shadow_copy_in.rs`). + pub(crate) fn shadow_copy_in_dispatched(&self) { + self.shadow_copies_in_dispatched + .fetch_add(1, Ordering::Relaxed); + } + + /// An encoder planned `n` keeps and merges of shadowed textures whose copies of the shadow + /// into the merge's scratch are dispatches (`shadow_merge.rs`, `ShadowMerge::dispatches`). + pub(crate) fn shadow_merge_copies_dispatched(&self, n: usize) { + self.shadow_merge_copies_dispatched + .fetch_add(n as u64, Ordering::Relaxed); + } + + /// A merge of a shadowed texture took its scratch from its shadow's spares (`shadow_merge.rs`, + /// `ScratchSpares`). + pub(crate) fn shadow_merge_scratch_reused(&self) { + self.shadow_merge_scratches_reused + .fetch_add(1, Ordering::Relaxed); + } + + /// A merge of a shadowed texture made its scratch zero (`shadow_merge.rs`): one not cut. + pub(crate) fn shadow_merge_scratch_zeroed(&self) { + self.shadow_merge_scratches_zeroed + .fetch_add(1, Ordering::Relaxed); + } + + /// A merge of a shadowed texture fetches the texels after the commands through its shadow's + /// unsigned-integer view (`shadow_merge.rs`). + pub(crate) fn shadow_merge_fetched(&self) { + self.shadow_merges_fetched.fetch_add(1, Ordering::Relaxed); + } + + /// A render pass took a shadowed texture as a color attachment so (`render/shadows.rs`). + pub(crate) fn shadow_color_taken(&self, taken: ColorTaken) { + let counter = match taken { + ColorTaken::LoadedWithin => &self.shadow_attachment_loads_within, + ColorTaken::Loaded => &self.shadow_attachment_loads_whole, + ColorTaken::Cleared => &self.shadow_attachment_clears, + ColorTaken::ClearedInPart => &self.shadow_attachment_clears_in_part, + ColorTaken::Untouched => &self.shadow_attachment_loads_untouched, + }; + counter.fetch_add(1, Ordering::Relaxed); + } + + /// A render pass took a shadowed texture as a color attachment it loads, its copies cut to the + /// rectangle bounding its draws' scissors: of the `bounded` 32-pixel tiles that rectangle + /// reaches, the rectangles themselves reach `covered` (`render/shadows.rs`, + /// `clear_reach::DrawnArea::covered_tiles`). + pub(crate) fn shadow_attachment_tiles(&self, covered: u64, bounded: u64) { + self.shadow_attachment_tiles_covered + .fetch_add(covered, Ordering::Relaxed); + self.shadow_attachment_tiles_bounded + .fetch_add(bounded, Ordering::Relaxed); + } + + /// An ended encoder's first copies in of shadowed textures moved `texels` texels of textures + /// an earlier encoder of its command buffer copied in too (`shadow.rs`). + pub(crate) fn shadow_texels_first_copied_in_again(&self, texels: u64) { + self.shadow_texels_first_copied_in_again + .fetch_add(texels, Ordering::Relaxed); + } + + /// An ended encoder used `n` shadowed textures whose truth one it used before shares + /// (`shadow.rs`). + pub(crate) fn shadows_sharing_truth(&self, n: usize) { + self.shadows_sharing_truth + .fetch_add(n as u64, Ordering::Relaxed); + } + + /// A command made a descriptor pool for its dispatches of one of the runtime's own kernels + /// (`owned_kernel.rs`). + pub(crate) fn owned_descriptor_pool(&self) { + self.owned_descriptor_pools.fetch_add(1, Ordering::Relaxed); + } + + /// An encoder planned keeps of shadowed textures that copy `texels` texels into their merges' + /// scratch (`shadow_merge.rs`). + pub(crate) fn shadow_texels_kept(&self, texels: u64) { + self.shadow_texels_kept.fetch_add(texels, Ordering::Relaxed); + } + /// A texture view was made the image itself to its bindings, through a swizzle over the /// image's own format (`texture/view_shadow.rs`, `ViewRecord::read_as`). pub(crate) fn view_through_swizzle_made(&self) { @@ -1997,14 +2201,94 @@ pub struct WorkCounts { pub shadows_zeroed: u64, /// Copies between a shadowed texture's truth and its shadow that encoders planned /// (`shadow.rs`): copies in before a command, copies back after one or as the encoder ends, - /// and the keeps and merges of a command that writes the bytes two ways. Each is a command of - /// its encoder over the texture's texels. + /// and the keeps and merges of a command that writes the bytes two ways or writes through a + /// texture that merges back (`shadow_merge.rs`). Each is a command of its encoder over the + /// texture's texels. pub shadow_copies: u64, /// The texels those copies in move from a 2D texture's buffer's bytes to its image (a texture /// over a buffer, a no-copy buffer or an IOSurface plane): every texel, or those inside the /// rectangle bounding a pass's draws' scissors over an attachment it loads and takes in no /// other way. pub shadow_texels_copied_in: u64, + /// The texels every copy in of an image's shadow moves, image to image (a texture's own + /// image's, `texture/usage_shadow.rs`, or a view's, `texture/view_shadow.rs`): each region's, + /// or those inside a rectangle where the copy is cut as a buffer's texture's is. Those are not + /// among `shadow_texels_copied_in`. + pub shadow_texels_copied_in_images: u64, + /// The texels each encoder's first copy in of a texture moves: before the first command of the + /// encoder that uses it, or the first after work the encoder records apart. Those of a + /// buffer's texture are among `shadow_texels_copied_in`, those of an image's shadow among + /// `shadow_texels_copied_in_images`. Every other copy in is a later one, counted by why it is + /// made (`shadow_texels_recopied_beyond_held`, `shadow_texels_recopied_after_changes`, + /// `shadow_texels_bounded_copied_in`, which with this sum to both kinds' copies in). The six + /// counts after it split it by what holds the texture's truth. + pub shadow_texels_first_copied_in: u64, + /// Of `shadow_texels_first_copied_in`, those of a truth that is an image: a texture's own + /// (the shadow a binding beyond its usage or a read of its own pass's attachment takes, + /// `texture/usage_shadow.rs`), or the one a view presents (`texture/view_shadow.rs`). + pub shadow_texels_first_copied_in_images: u64, + /// Those of the bytes of a buffer of private or memoryless storage the device made. + pub shadow_texels_first_copied_in_private_buffers: u64, + /// Those of the bytes of a buffer of shared or managed storage the device made, which the + /// CPU maps. + pub shadow_texels_first_copied_in_mapped_buffers: u64, + /// Those of host pages a no-copy buffer imported (or the memory of the caller's `VkBuffer`) + /// that only the shadow's own image is copied from. + pub shadow_texels_first_copied_in_host_pages: u64, + /// Those of host pages that the texture's own image lies in too (an aliasing image, a + /// pitched host image among them). + pub shadow_texels_first_copied_in_aliased_host_pages: u64, + /// Those of an IOSurface's plane (`Buffer::new_texture_with_iosurface_plane`). + pub shadow_texels_first_copied_in_surfaces: u64, + /// Of `shadow_texels_first_copied_in_surfaces`, those under a texture of 2^20 texels or more + /// (a 1920x1080 framebuffer's among them). + pub shadow_texels_first_copied_in_large_surfaces: u64, + /// Of `shadow_texels_first_copied_in`, those of a texture an earlier encoder of the same + /// command buffer copied in too, counted as each encoder ends (not an indirect command + /// buffer's segment): the copies in a shadow kept across a command buffer's encoders could + /// leave out, at most. + pub shadow_texels_first_copied_in_again: u64, + /// The texels later copies in move (not an encoder's first) before a command that needs + /// texels outside the rectangle the shadow's last copy in moved (a pass's read at its own + /// pixels, then a read anywhere), the truth unchanged outside it or not. + pub shadow_texels_recopied_beyond_held: u64, + /// The texels later copies in move after the truth changed since the shadow's copy in, other + /// than by writes within a rectangle that left it stale there alone. The five counts after it + /// split it by the change that came first. + pub shadow_texels_recopied_after_changes: u64, + /// Of `shadow_texels_recopied_after_changes`, those after a copy back or merge of another + /// shadowed texture over the same truth. + pub shadow_texels_recopied_after_other_shadows: u64, + /// Those after the texture's own merge, after a command that wrote its truth two ways. + pub shadow_texels_recopied_after_two_ways_merges: u64, + /// Those after a command wrote the truth another way (a pass that clears it, a storage + /// write, a copy). + pub shadow_texels_recopied_after_writes: u64, + /// Those after a render pass instance's writes within a rectangle that left the image stale + /// nowhere alone: the attachment has no shadow laid out as this one, or this one was + /// written through or kept. + pub shadow_texels_recopied_after_writes_within: u64, + /// Those after a command wrote through the texture where Metal drops the writes. + pub shadow_texels_recopied_after_dropped_writes: u64, + /// The texels the copies of `bounded_shadow_copies` move: those inside the rectangle bounding + /// where writes within rectangles changed the truth since the shadow's copy in. + pub shadow_texels_bounded_copied_in: u64, + /// The texels of those later copies in (`shadow_texels_recopied_beyond_held`, + /// `shadow_texels_recopied_after_changes` and `shadow_texels_bounded_copied_in` together) of + /// a truth that is an image, split by what holds the truth as the first copies are. + pub shadow_texels_recopied_in_images: u64, + /// Those of the bytes of a buffer of private or memoryless storage the device made. + pub shadow_texels_recopied_in_private_buffers: u64, + /// Those of the bytes of a buffer of shared or managed storage the device made. + pub shadow_texels_recopied_in_mapped_buffers: u64, + /// Those of host pages a no-copy buffer imported (or the memory of the caller's `VkBuffer`). + pub shadow_texels_recopied_in_host_pages: u64, + /// Those of host pages that the texture's own image lies in too. + pub shadow_texels_recopied_in_aliased_host_pages: u64, + /// Those of an IOSurface's plane. + pub shadow_texels_recopied_in_surfaces: u64, + /// Of `shadow_texels_recopied_in_surfaces`, those under a texture of 2^20 texels or more. + pub shadow_texels_recopied_in_large_surfaces: u64, /// The texels those copies back move from a 2D texture's image to its buffer's bytes (a /// texture over a buffer, a no-copy buffer or an IOSurface plane): every texel, or those /// inside the rectangle bounding a pass's draws' scissors over an attachment it loads. @@ -2013,6 +2297,64 @@ pub struct WorkCounts { /// words, where the device runs one faster than its copy /// (`DriverFact::ShadowCopyBackDispatchFaster`): the same bytes either way. pub shadow_copies_back_dispatched: u64, + /// Of the copies in among `shadow_copies`, those recorded with their texture's keep after + /// them (one of `shadow_merge_copies_dispatched`) as one dispatch that stores the texels in + /// the shadow and in the merge's scratch, where the device runs them faster so + /// (`DriverFact::ShadowCopyInDispatchFaster`): the same bytes either way. + pub shadow_copies_in_dispatched: u64, + /// Of the keeps and merges among `shadow_copies`, those whose copy of the shadow's texels into + /// the merge's scratch is the dispatch a copy back takes, where the device runs one faster + /// than its copy (`DriverFact::ShadowCopyBackDispatchFaster`): the same bytes either way. + pub shadow_merge_copies_dispatched: u64, + /// The merges of shadowed textures whose scratch was a buffer their shadow kept from an + /// earlier merge whose command buffers completed (`shadow_merge.rs`): no buffer made. + pub shadow_merge_scratches_reused: u64, + /// The merges of shadowed textures whose scratch was made zero, as their kernel reads bytes + /// no copy writes (those between the texture's rows): a merge not cut to rows of whole words, + /// through a copy or of rows that start or end inside a word. A cut merge's copies write + /// every byte its kernel reads, so its scratch is not zeroed. + pub shadow_merge_scratches_zeroed: u64, + /// The merges of shadowed textures that fetch the texels after the commands from the shadow + /// through its unsigned-integer view, comparing them with the kept texels, in place of a copy + /// of them into the scratch (`shadow_merge.rs`): a cut merge whose shadow has the view. + pub shadow_merges_fetched: u64, + /// The shadowed textures render passes took as color attachments and loaded, each once a + /// pass, whose copies are cut to the rectangle bounding the pass's draws' scissors + /// (`render/shadows.rs`): the copy in moves the texels inside it alone, as do the copy back + /// or the keep and merge. + pub shadow_attachment_loads_within: u64, + /// Those loaded whose copies move every texel: the pass's draws are not bounded so, or the + /// attachment is not the whole of a one-level, one-slice 2D texture rendered itself. Those + /// neither loaded nor cleared are among them. + pub shadow_attachment_loads_whole: u64, + /// Those cleared over the whole texture: no copy in. + pub shadow_attachment_clears: u64, + /// Those cleared over part of the texture (a render area smaller than it): every texel + /// copied in. + pub shadow_attachment_clears_in_part: u64, + /// Those loaded in a pass that reaches no tile: no copy in or back. + pub shadow_attachment_loads_untouched: u64, + /// Of `shadow_attachment_tiles_bounded`, the tiles the pass's draws' scissor rectangles + /// themselves reach: what a copy cut to those rectangles' tiles would move, where one cut to + /// their bounding rectangle moves all of them. + pub shadow_attachment_tiles_covered: u64, + /// The 32-pixel tiles (from the render area's origin) the rectangle bounding the draws' + /// scissors reaches, for each count of `shadow_attachment_loads_within`. + pub shadow_attachment_tiles_bounded: u64, + /// The shadowed textures an encoder used whose truth one it used before shares (another + /// texture over the same bytes, or a view's shadow of the same image), counted as each + /// encoder ends (not an indirect command buffer's segment): each copies its texels in apart. + pub shadows_sharing_truth: u64, + /// The descriptor pools commands made for their dispatches of the runtime's own kernels + /// (`owned_kernel.rs`), one per command: none for a kernel whose set 0 is pushed, on a device + /// that pushes descriptor sets (`vkCmdPushDescriptorSet`): the rows copy's, and a shadowed + /// texture's copy back's and merges'. + pub owned_descriptor_pools: u64, + /// The texels the keeps among `shadow_copies` copy from a shadow into their merge's scratch: + /// those inside the rectangle the encoder's commands write in, each row widened to whole + /// words of the buffer, where the commands bound it and the merge goes in place; every texel + /// otherwise. + pub shadow_texels_kept: u64, /// Of `shadow_copies`, the copies in of the texels inside the rectangle bounding where the /// bytes changed since the image's copy in, where only writes inside rectangles of its texels /// changed them: a render pass instance's draws into a color attachment it loads, over a @@ -2355,10 +2697,120 @@ impl Device { shadows_zeroed: counters.shadows_zeroed.load(Ordering::Relaxed), shadow_copies: counters.shadow_copies.load(Ordering::Relaxed), shadow_texels_copied_in: counters.shadow_texels_copied_in.load(Ordering::Relaxed), + shadow_texels_first_copied_in: counters + .shadow_texels_first_copied_in + .load(Ordering::Relaxed), + shadow_texels_first_copied_in_images: counters + .shadow_texels_first_copied_in_images + .load(Ordering::Relaxed), + shadow_texels_first_copied_in_private_buffers: counters + .shadow_texels_first_copied_in_private_buffers + .load(Ordering::Relaxed), + shadow_texels_first_copied_in_mapped_buffers: counters + .shadow_texels_first_copied_in_mapped_buffers + .load(Ordering::Relaxed), + shadow_texels_first_copied_in_host_pages: counters + .shadow_texels_first_copied_in_host_pages + .load(Ordering::Relaxed), + shadow_texels_first_copied_in_aliased_host_pages: counters + .shadow_texels_first_copied_in_aliased_host_pages + .load(Ordering::Relaxed), + shadow_texels_first_copied_in_surfaces: counters + .shadow_texels_first_copied_in_surfaces + .load(Ordering::Relaxed), + shadow_texels_first_copied_in_large_surfaces: counters + .shadow_texels_first_copied_in_large_surfaces + .load(Ordering::Relaxed), + shadow_texels_first_copied_in_again: counters + .shadow_texels_first_copied_in_again + .load(Ordering::Relaxed), + shadow_texels_copied_in_images: counters + .shadow_texels_copied_in_images + .load(Ordering::Relaxed), + shadow_texels_recopied_beyond_held: counters + .shadow_texels_recopied_beyond_held + .load(Ordering::Relaxed), + shadow_texels_recopied_after_changes: counters + .shadow_texels_recopied_after_changes + .load(Ordering::Relaxed), + shadow_texels_recopied_after_other_shadows: counters + .shadow_texels_recopied_after_other_shadows + .load(Ordering::Relaxed), + shadow_texels_recopied_after_two_ways_merges: counters + .shadow_texels_recopied_after_two_ways_merges + .load(Ordering::Relaxed), + shadow_texels_recopied_after_writes: counters + .shadow_texels_recopied_after_writes + .load(Ordering::Relaxed), + shadow_texels_recopied_after_writes_within: counters + .shadow_texels_recopied_after_writes_within + .load(Ordering::Relaxed), + shadow_texels_recopied_after_dropped_writes: counters + .shadow_texels_recopied_after_dropped_writes + .load(Ordering::Relaxed), + shadow_texels_bounded_copied_in: counters + .shadow_texels_bounded_copied_in + .load(Ordering::Relaxed), + shadow_texels_recopied_in_images: counters + .shadow_texels_recopied_in_images + .load(Ordering::Relaxed), + shadow_texels_recopied_in_private_buffers: counters + .shadow_texels_recopied_in_private_buffers + .load(Ordering::Relaxed), + shadow_texels_recopied_in_mapped_buffers: counters + .shadow_texels_recopied_in_mapped_buffers + .load(Ordering::Relaxed), + shadow_texels_recopied_in_host_pages: counters + .shadow_texels_recopied_in_host_pages + .load(Ordering::Relaxed), + shadow_texels_recopied_in_aliased_host_pages: counters + .shadow_texels_recopied_in_aliased_host_pages + .load(Ordering::Relaxed), + shadow_texels_recopied_in_surfaces: counters + .shadow_texels_recopied_in_surfaces + .load(Ordering::Relaxed), + shadow_texels_recopied_in_large_surfaces: counters + .shadow_texels_recopied_in_large_surfaces + .load(Ordering::Relaxed), shadow_texels_copied_back: counters.shadow_texels_copied_back.load(Ordering::Relaxed), shadow_copies_back_dispatched: counters .shadow_copies_back_dispatched .load(Ordering::Relaxed), + shadow_copies_in_dispatched: counters + .shadow_copies_in_dispatched + .load(Ordering::Relaxed), + shadow_merge_copies_dispatched: counters + .shadow_merge_copies_dispatched + .load(Ordering::Relaxed), + shadow_merge_scratches_reused: counters + .shadow_merge_scratches_reused + .load(Ordering::Relaxed), + shadow_merge_scratches_zeroed: counters + .shadow_merge_scratches_zeroed + .load(Ordering::Relaxed), + shadow_merges_fetched: counters.shadow_merges_fetched.load(Ordering::Relaxed), + shadow_attachment_loads_within: counters + .shadow_attachment_loads_within + .load(Ordering::Relaxed), + shadow_attachment_loads_whole: counters + .shadow_attachment_loads_whole + .load(Ordering::Relaxed), + shadow_attachment_clears: counters.shadow_attachment_clears.load(Ordering::Relaxed), + shadow_attachment_clears_in_part: counters + .shadow_attachment_clears_in_part + .load(Ordering::Relaxed), + shadow_attachment_loads_untouched: counters + .shadow_attachment_loads_untouched + .load(Ordering::Relaxed), + shadow_attachment_tiles_covered: counters + .shadow_attachment_tiles_covered + .load(Ordering::Relaxed), + shadow_attachment_tiles_bounded: counters + .shadow_attachment_tiles_bounded + .load(Ordering::Relaxed), + shadows_sharing_truth: counters.shadows_sharing_truth.load(Ordering::Relaxed), + owned_descriptor_pools: counters.owned_descriptor_pools.load(Ordering::Relaxed), + shadow_texels_kept: counters.shadow_texels_kept.load(Ordering::Relaxed), bounded_shadow_copies: counters.bounded_shadow_copies.load(Ordering::Relaxed), replay_logs_kept: counters.replay_logs_kept.load(Ordering::Relaxed), replay_log_bytes: counters.replay_log_bytes.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index 7c91ed532..2133f55d5 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -225,6 +225,8 @@ mod argument_linear_samples; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod astc_textures; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +mod attachment_read_costs; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod attachment_reads; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod attachmentless; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/attachment_read_costs.rs b/crates/metal2vulkan-validation/src/runtime_lane/attachment_read_costs.rs new file mode 100644 index 000000000..822e5b3e0 --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/attachment_read_costs.rs @@ -0,0 +1,210 @@ +//! What a compositor's reads of its own pass's attachment cost the GPU, on the device the cfg +//! selects, without the validation layer: report only, in release builds, to weigh the copies a +//! draw that samples its pass's attachment takes (`texture/attached_reads.rs`, `shadow.rs`) before +//! and after a change to them. +//! +//! The workload is a window server's composite as the consumer's guest replays it, over a +//! [`WIDTH`]x[`HEIGHT`] `RGBA8Unorm` target of its own image: [`PASSES`] command buffers a frame, +//! each one render pass that loads and stores the target, of [`STEPS`] steps, each a fill of a +//! window's rectangle through its scissor, a memory barrier over the render targets and a draw +//! that reads the target at its own pixels over that rectangle (`tob_read`); then, in every other +//! pass, a barrier and a draw over a window that samples the target at other pixels +//! (`a4_fragment_select_sample`). The windows cover more than a fifth of the target, so no own-pixel +//! read takes a snapshot (`render/snapshot.rs`). The frame waits for its last command buffer. +//! +//! [`WARM`] frames run untimed, then [`TIMED`] frames are printed as one `ATTACHMENT-READ-COST` +//! line: the GPU time per frame (each command buffer's GPU end less its start, summed), the wall +//! time per frame from the first pass's opening through the last command buffer's completion, and +//! the device's work counts per frame: reads through copies, own-pixel reads, splits, snapshots, +//! shadow copies, the copies in of what changed within a rectangle, and the texels each encoder's +//! first copy in of an image's shadow moves. +//! + +use super::attachment_reads::{floats, function}; +use super::{open_device, WAIT}; +use crate::gpu::TEST_DEVICE; +use metal2vulkan::bind::SamplerDescriptor; +use metal2vulkan::metal::{BarrierScope, PixelFormat, PrimitiveType, RenderStages, TextureUsage}; +use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor}; +use metal2vulkan_runtime::{ +}; +use std::time::Instant; + +/// The target's size, a 1080p framebuffer's. +const WIDTH: u64 = 1920; +const HEIGHT: u64 = 1080; +/// The command buffers of a frame, each one pass. +const PASSES: u64 = 4; +/// The fill, barrier and own-pixel read steps of a pass. +const STEPS: u64 = 3; +/// The untimed and the timed frames. +const WARM: usize = 10; +const TIMED: usize = 60; + +/// Step `step` of pass `pass`'s window: 960x720 pixels, at an offset of its own. +fn window(pass: u64, step: u64) -> [u64; 4] { + let (x, y) = ( + (pass * 211 + step * 97) % 960, + (pass * 53 + step * 131) % 360, + ); + [x, y, x + 960, y + 720] +} + +/// The corners, in normalized device coordinates, of the target's pixels `[x0, x1) x [y0, y1)`. +fn corners([x0, y0, x1, y1]: [u64; 4]) -> Vec { + let x = |p: u64| p as f32 / WIDTH as f32 * 2.0 - 1.0; + let y = |p: u64| 1.0 - p as f32 / HEIGHT as f32 * 2.0; + floats([x(x0), y(y1), x(x1), y(y0)]) +} + + let mut d = RenderPipelineDescriptor::new(function(device, "tob_rect", "tob_renders.ll")); + d.fragment = Some(function(device, name, fixture)); + device + .new_render_pipeline_state(&d, &PipelineOptions::default()) + .unwrap() +} + +/// Draw over `rect`, through a scissor of it. +fn draw_over(encoder: &mut RenderCommandEncoder, [x0, y0, x1, y1]: [u64; 4]) { + let rect = ScissorRect { + x: x0, + y: y0, + width: x1 - x0, + height: y1 - y0, + }; + encoder.set_scissor_rect(rect).unwrap(); + encoder + .set_vertex_bytes(&corners([x0, y0, x1, y1]), 0) + .unwrap(); + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0) + .unwrap(); +} + +fn barrier(encoder: &mut RenderCommandEncoder) { + encoder.memory_barrier_with_scope( + BarrierScope::RENDER_TARGETS, + RenderStages::FRAGMENT, + RenderStages::FRAGMENT, + ); +} + +/// The workload's pipelines and sampler. +struct Draws { + fill: RenderPipelineState, + read: RenderPipelineState, + sample: RenderPipelineState, + sampler: SamplerState, +} + +/// One frame over `target` on `queue` (the module docs): its command buffers, committed, the last +/// waited for. +fn frame(queue: &CommandQueue, target: &Texture, draws: &Draws) -> Vec { + let mut d = RenderPassDescriptor::new(); + let color = &mut d.color_attachments[0]; + color.texture = Some(target.clone()); + color.load_action = LoadAction::Load; + color.store_action = StoreAction::Store; + let mut committed = Vec::new(); + for pass in 0..PASSES { + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.render_command_encoder(&d).unwrap(); + for step in 0..STEPS { + let rect = window(pass, step); + encoder.set_render_pipeline_state(&draws.fill).unwrap(); + let red = (pass * STEPS + step) as f32 / (PASSES * STEPS) as f32; + encoder + .set_fragment_bytes(&floats([red, 0.5, 0.0, 1.0]), 0) + .unwrap(); + draw_over(&mut encoder, rect); + barrier(&mut encoder); + encoder.set_render_pipeline_state(&draws.read).unwrap(); + encoder.set_fragment_texture(Some(target), 0).unwrap(); + draw_over(&mut encoder, rect); + } + if pass % 2 == 1 { + barrier(&mut encoder); + encoder.set_render_pipeline_state(&draws.sample).unwrap(); + encoder.set_fragment_texture(Some(target), 0).unwrap(); + encoder.set_fragment_texture(Some(target), 1).unwrap(); + encoder + .set_fragment_sampler_state(Some(&draws.sampler), 0) + .unwrap(); + draw_over(&mut encoder, window(pass, STEPS)); + } + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + committed.push(command_buffer); + } + let last = committed.last().unwrap(); + last.wait_until_completed_for(WAIT).unwrap(); + for command_buffer in &committed { + assert_eq!(command_buffer.error(), None); + } + committed +} + +/// The work counts the module docs name, per frame over `frames` frames. +fn per_frame(before: &WorkCounts, after: &WorkCounts, frames: usize) -> String { + let per = |a: u64, b: u64| (a - b) as f64 / frames as f64; + format!( + "reads through copies {:.1}, own-pixel reads {:.1}, splits {:.1}, snapshotted {:.1}, \ + shadow copies {:.1}, bounded {:.1}, image first-copy texels {:.0}", + per( + after.attachment_reads_through_copies, + before.attachment_reads_through_copies + ), + per(after.own_pixel_reads, before.own_pixel_reads), + per(after.attachment_read_splits, before.attachment_read_splits), + per( + after.reading_draws_snapshotted, + before.reading_draws_snapshotted + ), + per(after.shadow_copies, before.shadow_copies), + per(after.bounded_shadow_copies, before.bounded_shadow_copies), + per( + after.shadow_texels_first_copied_in_images, + before.shadow_texels_first_copied_in_images + ), + ) +} + +#[test] +#[ignore = "a release-mode measurement: run by name"] +fn attachment_read_costs() { + let device = open_device(TEST_DEVICE, DeviceOptions::default()).unwrap(); + let draws = Draws { + sample: state( + &device, + "a4_fragment_select_sample", + "a4_fragment_select_sample.ll", + ), + sampler: device.new_sampler_state(&SamplerDescriptor::new()).unwrap(), + }; + let mut d = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, WIDTH, HEIGHT, false); + d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + d.resource_options = ResourceOptions::private(); + let target = device.new_texture(&d).unwrap(); + let queue = device.new_command_queue().unwrap(); + for _ in 0..WARM { + frame(&queue, &target, &draws); + } + let before = device.work_counts(); + let (mut gpu, started) = (0.0, Instant::now()); + for _ in 0..TIMED { + for command_buffer in frame(&queue, &target, &draws) { + gpu += + command_buffer.gpu_end_time().unwrap() - command_buffer.gpu_start_time().unwrap(); + } + } + let wall = started.elapsed().as_secs_f64(); + let after = device.work_counts(); + println!( + "ATTACHMENT-READ-COST on {}: {WIDTH}x{HEIGHT} target of its own image, {PASSES} passes of \ + {STEPS} steps: GPU {:.3} ms/frame, wall {:.3} ms/frame; {}", + device.name(), + gpu * 1e3 / TIMED as f64, + wall * 1e3 / TIMED as f64, + per_frame(&before, &after, TIMED) + ); +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/attachment_reads.rs b/crates/metal2vulkan-validation/src/runtime_lane/attachment_reads.rs index b095df793..3128d1007 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/attachment_reads.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/attachment_reads.rs @@ -26,21 +26,21 @@ //! - [`a_chain_of_barriers_copies_in_only_what_each_instance_drew`]: [`CHAIN`] steps after A, each //! a fill of one pixel through a one-pixel scissor, a memory barrier, and draw C through a //! one-pixel scissor at the pixel that samples it: every C draws its fill's red, every other -//! pixel keeps its red, the answers of a copy of every texel before each instance. Over a -//! buffer, each copy after the first takes only the rectangle bounding the pixels the instance -//! before it drew (`bounded_shadow_copies`, `shadow_texels_copied_in`); the texture of its own -//! image copies every texel. +//! pixel keeps its red, the answers of a copy of every texel before each instance. Each copy +//! after the first takes only the rectangle bounding the pixels the instance before it drew +//! (`bounded_shadow_copies`; `shadow_texels_copied_in` over a buffer, +//! `shadow_texels_copied_in_images` for the texture of its own image). //! - [`own_pixel_reads_copy_in_only_around_their_scissors`]: [`OWN_STEPS`] steps after A, each a //! fill of one pixel through a one-pixel scissor (corners and edges among them), a memory //! barrier, and draw C (`tob_read`, `t.read(uint2(in.position.xy))`) through a one-pixel //! scissor at that pixel, then one more at the first step's pixel: every C draws its fill's red. -//! Over a buffer, each C reads at its own pixel alone (`own_pixel_reads`), and each copy in -//! moves at most the 3x3 texels around its pixel. A C the device reads through a snapshot +//! Each C reads at its own pixel alone (`own_pixel_reads`), and each copy in moves at most the +//! 3x3 texels around its pixel. A C the device reads through a snapshot //! inside its instance (`snapshot_reads.rs`, `reading_draws_snapshotted`) takes neither a split //! nor a copy, and answers the same. //! - [`an_own_pixel_read_without_a_barrier_reads_the_texels_from_before_the_pass`]: with no //! barrier, `tob_read` over A's block draws the red from before the pass (probe `selfsample`), -//! its copy over a buffer the texels around the block alone. +//! its copy the texels around the block alone. //! - [`a_pass_that_samples_no_attachment_copies_nothing`]: A, then `tob_read` of another texture: //! no read through a copy, split, own-pixel read or shadow copy. @@ -213,7 +213,9 @@ pub(super) fn red(bytes: &[u8], x: u64, y: u64) -> u8 { /// What the pass moved of the counts: its draws' splits for attachment reads, their reads /// through snapshots inside their instances, their reads through copies, the encoders' shadow /// copies, of those the copies in of what changed within a rectangle alone, the texels the copies -/// in moved, and whether the pass rendered the target through a copied stand-in. +/// in of buffers' textures moved and those of images' shadows, the texels the encoder's first +/// copy in moved of a truth that is an image and of one in a mapped buffer, and whether the pass +/// rendered the target through a copied stand-in. struct Moved { splits: u64, snapshotted: u64, @@ -221,6 +223,8 @@ struct Moved { copies: u64, bounded: u64, texels_in: u64, + texels_in_images: u64, + first: [u64; 2], apart: bool, } @@ -232,6 +236,14 @@ fn moved(before: &WorkCounts, after: &WorkCounts) -> Moved { copies: after.shadow_copies - before.shadow_copies, bounded: after.bounded_shadow_copies - before.bounded_shadow_copies, texels_in: after.shadow_texels_copied_in - before.shadow_texels_copied_in, + texels_in_images: after.shadow_texels_copied_in_images + - before.shadow_texels_copied_in_images, + first: [ + after.shadow_texels_first_copied_in_images + - before.shadow_texels_first_copied_in_images, + after.shadow_texels_first_copied_in_mapped_buffers + - before.shadow_texels_first_copied_in_mapped_buffers, + ], apart: after.linear_passes_through_copies > before.linear_passes_through_copies, } } @@ -244,13 +256,16 @@ fn moved(before: &WorkCounts, after: &WorkCounts) -> Moved { fn check(name: &str, moved: &Moved, barriers: u64) { eprintln!( "attachment reads, {name}, barriers {barriers}: splits {}, snapshotted {}, reads through \ - copies {}, shadow copies {} (bounded {}, texels in {}), through a stand-in {}", + copies {}, shadow copies {} (bounded {}, texels in {} and {} of images, first in \ + {:?}), through a stand-in {}", moved.splits, moved.snapshotted, moved.reads, moved.copies, moved.bounded, moved.texels_in, + moved.texels_in_images, + moved.first, moved.apart ); if moved.apart { @@ -268,6 +283,15 @@ fn check(name: &str, moved: &Moved, barriers: u64) { if moved.snapshotted < barriers.max(1) { assert!(moved.reads >= 1, "{name}: the draw read no copy"); assert!(moved.copies >= 1, "{name}: no copy was taken"); + // The encoder's first copy in, counted by what holds the target's texels: its own image, + // or the shared buffer's bytes. + let [images, mapped] = moved.first; + let own = name.starts_with("its own image"); + assert_eq!( + (images > 0, mapped > 0), + (own, !own), + "{name}: the first copy's texels counted by the truth's backing" + ); } } @@ -382,20 +406,17 @@ fn own_pixel_reads_copy_in_only_around_their_scissors() { count, "{name}: each C read the copy or a snapshot" ); - // Over a buffer: each copy in of at most the 3x3 texels around a C's pixel, and a - // shadowed attachment's own copy in at most every texel more. The image's shadow - // takes every texel (`ShadowCopies::cuts`). - if name == "over a buffer" { - assert_eq!(own, moved.reads, "{name}: own-pixel reads"); - let most = SIDE * SIDE + 9 * count; - assert!( - moved.texels_in <= most, - "{name}: {} texels copied in, past {most}", - moved.texels_in - ); - } else { - assert_eq!(own, 0, "{name}: own-pixel reads"); - } + // Each copy in of at most the 3x3 texels around a C's pixel (`ShadowCopies::cuts`), + // and over a buffer a shadowed attachment's own copy in at most every texel more. + assert_eq!(own, moved.reads, "{name}: own-pixel reads"); + let (texels, most) = match name == "over a buffer" { + true => (moved.texels_in, SIDE * SIDE + 9 * count), + false => (moved.texels_in_images, 9 * count), + }; + assert!( + texels <= most, + "{name}: {texels} texels copied in, past {most}" + ); } }); } @@ -428,12 +449,13 @@ fn an_own_pixel_read_without_a_barrier_reads_the_texels_from_before_the_pass() { check(name, &moved, 0); let own = after.own_pixel_reads - counted.own_pixel_reads; eprintln!("own-pixel reads, {name}: {own}"); - if !moved.apart && name == "over a buffer" { + if !moved.apart { assert_eq!(own, 1, "{name}: own-pixel reads"); - // The full scissor, the whole target: its copy every texel at most, and a - // shadowed attachment's own every texel more. + // The full scissor, the whole target: its copy every texel at most, and over a + // buffer a shadowed attachment's own every texel more. let most = 2 * SIDE * SIDE; - assert!(moved.texels_in <= most, "{name}: {}", moved.texels_in); + let texels = moved.texels_in + moved.texels_in_images; + assert!(texels <= most, "{name}: {texels}"); } } }); @@ -767,20 +789,18 @@ fn a_chain_of_barriers_copies_in_only_what_each_instance_drew() { continue; } assert_eq!(moved.reads, CHAIN, "{name}: each C read the copy"); - // Over a buffer: the first copy of every texel, then only what each instance drew. - // The image's shadow takes every texel (`ShadowCopies::cuts`). - if name == "over a buffer" { - assert_eq!(moved.bounded, CHAIN - 1, "{name}: bounded copies"); - // A shadowed attachment's own copy in takes at most every texel more. - let most = 2 * SIDE * SIDE + chain_texels(); - assert!( - moved.texels_in <= most, - "{name}: {} texels copied in, past {most}", - moved.texels_in - ); - } else { - assert_eq!(moved.bounded, 0, "{name}: bounded copies"); - } + // The first copy of every texel, then only what each instance drew + // (`ShadowCopies::cuts`); over a buffer, a shadowed attachment's own copy in takes at + // most every texel more. + assert_eq!(moved.bounded, CHAIN - 1, "{name}: bounded copies"); + let (texels, most) = match name == "over a buffer" { + true => (moved.texels_in, 2 * SIDE * SIDE + chain_texels()), + false => (moved.texels_in_images, SIDE * SIDE + chain_texels()), + }; + assert!( + texels <= most, + "{name}: {texels} texels copied in, past {most}" + ); } }); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/detach_textures.rs b/crates/metal2vulkan-validation/src/runtime_lane/detach_textures.rs index 01ec04886..e73d5fecd 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/detach_textures.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/detach_textures.rs @@ -521,10 +521,6 @@ fn a_rebind_gives_every_texture_its_pages_again() { fn a_texture_made_while_detached_writes_its_pages_once_they_are_given_again() { on_device(|device| { let query = QueryRead::new(device); - let dispatches = device - .properties() - .driver_facts - .contains(&DriverFact::ShadowCopyBackDispatchFaster); let before = device.work_counts().shadow_copies_back_dispatched; for over in [Over::Buffer, Over::Heap] { let Some((bytes, texture)) = detached_texture(device, &query, (over, Made::While)) diff --git a/crates/metal2vulkan-validation/src/runtime_lane/guest_frame_costs.rs b/crates/metal2vulkan-validation/src/runtime_lane/guest_frame_costs.rs new file mode 100644 index 000000000..1fa0c19c0 --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/guest_frame_costs.rs @@ -0,0 +1,3 @@ + dispatched {:.2}, copies in dispatched {:.2}, merge copies dispatched {:.2}, merge \ + per(|c| c.shadow_copies_in_dispatched), + per(|c| c.owned_descriptor_pools), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/no_copy_textures.rs b/crates/metal2vulkan-validation/src/runtime_lane/no_copy_textures.rs index 0f072af59..13e54e923 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/no_copy_textures.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/no_copy_textures.rs @@ -52,7 +52,9 @@ use super::host_memory::{counting, no_copy, not_importable, Mapping, GUEST_PAGE} use super::{validated_device, validated_device_with, Messages, ScratchCache, WAIT}; use crate::air_library::AirLibrary; use crate::gpu::TEST_DEVICE; -use metal2vulkan::metal::{BlendFactor, PixelFormat, PrimitiveType, TextureType, TextureUsage}; +use metal2vulkan::metal::{ + BlendFactor, ColorWriteMask, PixelFormat, PrimitiveType, TextureType, TextureUsage, +}; use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; use metal2vulkan::vk::DriverId; use metal2vulkan_devtools::llvm_assemble; @@ -696,6 +698,35 @@ pub(super) fn rects_beside( blends: bool, beside: Option, ) -> RenderPipelineState { + let mut d = rects_descriptor(device, pf, blends); + match beside { + Some(PixelFormat::Depth32Float) => d.depth_format = beside, + Some(_) => d.stencil_format = beside, + None => {} + } + device + .new_render_pipeline_state(&d, &PipelineOptions::default()) + .unwrap() +} + +/// [`blending`]'s pipeline for a pass whose color 1 is a scratch of `scratch`'s format, which it +/// leaves alone under an empty write mask. +pub(super) fn blending_beside_scratch( + device: &Device, + pf: PixelFormat, + scratch: PixelFormat, +) -> RenderPipelineState { + let mut d = rects_descriptor(device, pf, true); + let mut color = ColorAttachmentDescriptor::new(scratch); + color.write_mask = ColorWriteMask::NONE; + d.color_attachments[1] = Some(color); + device + .new_render_pipeline_state(&d, &PipelineOptions::default()) + .unwrap() +} + +/// [`rects`]'s pipeline descriptor. +fn rects_descriptor(device: &Device, pf: PixelFormat, blends: bool) -> RenderPipelineDescriptor { let ll = Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/public/engine/tob_renders.ll"); let library = device .new_library_with_air(&llvm_assemble(&ll).unwrap()) @@ -717,14 +748,7 @@ pub(super) fn rects_beside( color.source_alpha_blend_factor = BlendFactor::One; color.destination_alpha_blend_factor = BlendFactor::Zero; d.color_attachments[0] = Some(color); - match beside { - Some(PixelFormat::Depth32Float) => d.depth_format = beside, - Some(_) => d.stencil_format = beside, - None => {} - } - device - .new_render_pipeline_state(&d, &PipelineOptions::default()) - .unwrap() + d } /// The bytes of four `f32`s, as a shader reads them. diff --git a/crates/metal2vulkan-validation/src/runtime_lane/pitched_surfaces.rs b/crates/metal2vulkan-validation/src/runtime_lane/pitched_surfaces.rs index d39e5ee31..641002a28 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/pitched_surfaces.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/pitched_surfaces.rs @@ -63,24 +63,33 @@ //! finds the texels and each write past the image's bytes in the pages after it; the writes //! between rows the keep undid are printed (`FIRST-MOVE-WINDOW`). //! -//! [`textures_of_one_image_over_the_same_bytes_share_it`] makes a texture over the same packed -//! 1080p pages at each of a few presents, each over a new no-copy buffer: each takes the first -//! texture's `VkImage` (`WorkCounts::shared_alias_images`), whose move kept the bytes once, and a -//! texture of another usage makes its own (`SHARED-ALIAS`). +//! [`a_loaded_color_beside_a_cleared_depth_copies_inside_its_scissor`] draws under a scissor +//! beside a depth attachment the pass clears and stores, of the color's size and larger, whose +//! clear then reaches past the render area: the color's copies stay inside the scissor, and its +//! bytes are a private texture's. +//! +//! [`a_shadowed_color_beside_a_memoryless_scratch_blends_over_part_of_it`] blends over a shadowed +//! texture beside a memoryless scratch loaded and stored `DontCare`, over a render area smaller +//! than both: the bytes are a private texture's inside the render area and unchanged past it. +//! +//! [`a_pass_s_copies_in_share_their_barriers`] reads several shadowed textures in one pass that +//! loads another: their copies in share one barrier before and one after, and the pass records +//! as many pipeline barriers whatever the number of textures it reads. //! -//! Printed per layout (`PITCHED-SURFACE`): the form, the images the making counted -//! (`WorkCounts::pitched_host_images`, `shadowed_textures`), and a shadow's reason. Printed once //! (`SHADOW-COPY-BACK`, [`a_pass_copies_in_and_back_only_the_texels_its_scissors_reach`]): whether //! a shadow's copy back ran as a dispatch (`WorkCounts::shadow_copies_back_dispatched`). +use super::draw_work::pushes; use super::host_memory::{counting, no_copy, not_importable, Mapping, GUEST_PAGE}; -use super::no_copy_textures::{blending, floats, staged}; +use super::memoryless::memoryless_options; +use super::no_copy_textures::{blending, blending_beside_scratch, floats, rects_beside, staged}; use super::{validated_device, validated_device_with, Messages, ScratchCache, WAIT}; use crate::air_library::AirLibrary; use crate::gpu::TEST_DEVICE; use metal2vulkan::bind::SamplerDescriptor; -use metal2vulkan::device::{DriverFact, PaddedReadsPolicy}; -use metal2vulkan::metal::{PixelFormat, PrimitiveType, SamplerMinMagFilter, TextureUsage}; +use metal2vulkan::metal::{ + BarrierScope, PixelFormat, PrimitiveType, RenderStages, SamplerMinMagFilter, TextureUsage, +}; use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; use metal2vulkan::vk::DriverId; use metal2vulkan_devtools::{engine_dir, llvm_assemble}; @@ -1507,9 +1516,12 @@ fn a_pass_that_draws_nothing_copies_no_shadow() { /// holds the blend inside the scissor, as a private texture of the same texels blended alike /// does, and every other byte as it was; a later draw reading every texel of the texture reads /// the buffer's, none the image kept from before. Without a scissor, both copies move every -/// texel. Each copy back is one dispatch on a device that takes it -/// (`DriverFact::ShadowCopyBackDispatchFaster`), and none elsewhere -/// (`WorkCounts::shadow_copies_back_dispatched`, printed as `SHADOW-COPY-BACK`). +/// texel. The CPU may write the `Shared` buffer's bytes, so its texture's copy back is a merge, +/// which moves no texel back as a copy and dispatches no copy back; its keep moves the texels +/// inside the scissor alone (`WorkCounts::shadow_texels_kept`). On a device that takes the copy +/// Neither merge zeroes its scratch (`WorkCounts::shadow_merge_scratches_zeroed`). Where the +/// device pushes set 0, the keep's and the merge's dispatches push their descriptors and make no +/// descriptor pool; elsewhere each makes one (`WorkCounts::owned_descriptor_pools`). #[test] fn a_pass_copies_in_and_back_only_the_texels_its_scissors_reach() { let layout = LAYOUTS[0]; @@ -1555,39 +1567,61 @@ fn a_pass_copies_in_and_back_only_the_texels_its_scissors_reach() { encoder.end_encoding().unwrap(); run(&command_buffer); }; - // Each pass's one copy back is a dispatch where the device runs one faster than the copy - // (`DriverFact::ShadowCopyBackDispatchFaster`, `WorkCounts::shadow_copies_back_dispatched`), - // and a copy everywhere else. - let dispatches = device - .properties() - .driver_facts - .contains(&DriverFact::ShadowCopyBackDispatchFaster); + // `WorkCounts::shadow_merges_fetched`); both copy everywhere else. let moved = || { let counts = device.work_counts(); ( counts.shadow_texels_copied_in, counts.shadow_texels_copied_back, counts.shadow_copies_back_dispatched, + counts.shadow_merge_copies_dispatched, + counts.shadow_texels_kept, + counts.shadow_merges_fetched, + counts.owned_descriptor_pools, + counts.shadow_copies_in_dispatched, ) }; - let since = |(i, b, d): (u64, u64, u64)| { - let (now_in, now_back, now_dispatched) = moved(); - (now_in - i, now_back - b, now_dispatched - d) + let now = moved(); + ( + now.0 - before.0, + now.1 - before.1, + now.2 - before.2, + now.3 - before.3, + now.4 - before.4, + now.5 - before.5, + now.6 - before.6, + now.7 - before.7, + ) }; - let dispatched = u64::from(dispatches); + // The merge's kernel, and the keep where it is a dispatch, each make a descriptor pool + // where the device does not push set 0. + let pools = if pushes(&device) { 0 } else { 1 + merged }; + // The keep's dispatch takes the copy in of the same texels with it, where the device takes + let zeroed = device.work_counts().shadow_merge_scratches_zeroed; let before = moved(); draw(&texture, Some(scissor)); let scissored = since(before); println!( - "SHADOW-COPY-BACK on {}: a scissored pass dispatched {} of its 1 copy back (the \ - device {} the dispatch)", + "SHADOW-COPY-BACK on {}: a scissored pass dispatched {} copies back and {} of its \ device.name(), scissored.2, + scissored.3, + scissored.4, + scissored.5, + scissored.7, if dispatches { "takes" } else { "does not take" }, ); assert_eq!( scissored, - (300 * 200, 300 * 200, dispatched), + ( + 300 * 200, + back(300 * 200), + dispatched, + merged, + 300 * 200, + fetched, + pools, + ), "a scissored pass" ); draw(&private, Some(scissor)); @@ -1623,9 +1657,24 @@ fn a_pass_copies_in_and_back_only_the_texels_its_scissors_reach() { let every = layout.w * layout.h; assert_eq!( since(before), - (every, every, dispatched), + ( + every, + back(every), + dispatched, + merged, + every, + fetched, + pools, + ), "an unscissored pass" ); + // Both merges go in place over whole words of each row, so their copies write every byte + // their kernels read, and neither zeroes its scratch. + assert_eq!( + device.work_counts().shadow_merge_scratches_zeroed, + zeroed, + "merge scratches zeroed" + ); drop((texture, buffer, private)); } let messages = messages.take(); @@ -1635,36 +1684,80 @@ fn a_pass_copies_in_and_back_only_the_texels_its_scissors_reach() { ); } -/// A texture of `layout` over a no-copy buffer, with shader read and write usage, written at every -/// texel by a fragment function's `write` (`tob_write`): the pages' texels are what a private -/// texture of the same texels holds after the same writes, and no other byte of the pages changes. -fn writes_as_metal(layout: Layout) { +/// A pass that loads a shadowed texture (the browser's padded tile over an ordinary buffer) over +/// a render area smaller than it, of whole 32-pixel tiles on neither axis, beside a memoryless +/// `RGBA16Float` scratch of its size loaded and stored `DontCare` (the consumer's guest's shadowed +/// passes' shape): the buffer holds the blend inside the render area, as a private texture of the +/// same texels drawn alike does, and every other byte as it was. +#[test] +fn a_shadowed_color_beside_a_memoryless_scratch_blends_over_part_of_it() { + let layout = LAYOUTS[0]; let cache = ScratchCache::new().unwrap(); let messages = Messages::default(); { let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); let queue = device.new_command_queue().unwrap(); - let usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; - let Some(surface) = surface(&device, &layout, usage, false) else { - return; - }; - let mut expected = surface.pages.clone(); - let texels = rows(&layout, &expected); + let len = layout.bpr * layout.h; + let buffer = device.new_buffer(len, ResourceOptions::default()).unwrap(); + let bytes = texels_of(&layout, len as usize, 9); + let contents = buffer.contents().unwrap(); + // SAFETY: a new `Shared` buffer of `len` bytes, which no command uses yet. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), contents.as_ptr(), bytes.len()) }; let mut d = TextureDescriptor::texture_2d(layout.pf, layout.w, layout.h, false); - d.usage = usage; - d.resource_options = ResourceOptions::private(); - let reference = device.new_texture(&d).unwrap(); - blit_in(&queue, &layout, &reference, &texels); - let writes = reading(&device, layout.pf, "tob_write"); - drawn(&queue, &layout, &writes, &reference, None); - drawn(&queue, &layout, &writes, &surface.texture, None); - lay( - &layout, - &mut expected, - &blit_out(&queue, &layout, &reference), + d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + d.resource_options = buffer.resource_options(); + let texture = buffer.new_texture(&d, 0, layout.bpr).unwrap(); + // SAFETY: the handle is only compared, while the texture lives. + assert!(unsafe { texture.vk_image() }.is_none(), "a shadow"); + let private = private_with(&queue, &layout, &rows(&layout, &bytes)); + let mut d = + TextureDescriptor::texture_2d(PixelFormat::RGBA16Float, layout.w, layout.h, false); + d.usage = TextureUsage::RENDER_TARGET; + d.resource_options = memoryless_options(); + let scratch = device.new_texture(&d).unwrap(); + let blend = blending_beside_scratch(&device, layout.pf, PixelFormat::RGBA16Float); + let corners = staged(&device, &floats([-1.0, -1.0, 1.0, 1.0])); + let color = staged(&device, &floats([0.25, 0.5, 0.75, 0.5])); + let area = [layout.w - 37, layout.h - 21]; + assert!(area.iter().all(|side| side % 32 != 0), "tiles cut"); + let draw = |target: &Texture| { + let mut pass = RenderPassDescriptor::new(); + let attachment = &mut pass.color_attachments[0]; + attachment.texture = Some(target.clone()); + attachment.load_action = LoadAction::Load; + attachment.store_action = StoreAction::Store; + let attachment = &mut pass.color_attachments[1]; + attachment.texture = Some(scratch.clone()); + attachment.load_action = LoadAction::DontCare; + attachment.store_action = StoreAction::DontCare; + [pass.render_target_width, pass.render_target_height] = area; + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(&blend).unwrap(); + encoder.set_vertex_buffer(Some(&corners), 0, 0).unwrap(); + encoder.set_fragment_buffer(Some(&color), 0, 0).unwrap(); + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0) + .unwrap(); + encoder.end_encoding().unwrap(); + run(&command_buffer); + }; + draw(&texture); + draw(&private); + let mut expected = bytes.clone(); + lay(&layout, &mut expected, &blit_out(&queue, &layout, &private)); + let now = bytes_of(&buffer); + let (count, first) = differing( + &rows(&layout, &now), + &rows(&layout, &expected), + layout.texel, ); - surface.check(&layout, "a fragment function's writes", &expected); - surface.report(&device, &messages); + assert!( + count == 0, + "{count} texels differ from the private texture's, the first at texel {first:?}" + ); + assert!(now == expected, "the bytes between the rows changed"); + drop((texture, buffer, private, scratch)); } let messages = messages.take(); assert!( @@ -1673,26 +1766,498 @@ fn writes_as_metal(layout: Layout) { ); } -/// One test a layout, each its own process: `$name` runs [`LAYOUTS`]`[$index]`. -macro_rules! per_layout { - ($($name:ident => $index:expr;)*) => { - $( - #[test] - fn $name() { - reads_writes_and_renders_as_metal(LAYOUTS[$index]); +/// A pass's copies in share their barriers (`encoder.rs`'s `ShadowRun`): a pass that loads a +/// shadowed texture over a `Shared` buffer and draws `n` rectangles, each under its own scissor +/// reading its own shadowed texture over the same buffer, copies the `n` textures in, and the +/// loaded texture in and kept (it merges back), before it. The copies in of different textures +/// share one barrier before them and one after; the keep, which reads the shadow its texture's +/// copy in wrote, takes a barrier of its own. So the pass records as many pipeline barriers +/// (`WorkCounts::commands_replayed`) whatever `n`, where a barrier before and one after each copy +/// grew them by two a texture (counted after a first pass of the shape). The buffer holds each +/// texture's texels inside its rectangle, as the draws read them, and every other byte as it +/// was. Printed: `SHADOW-RUN`. +#[test] +fn a_pass_s_copies_in_share_their_barriers() { + let layout = LAYOUTS[4]; + assert!(layout.padded(), "{}", layout.name); + let most = 4; + let stride = (layout.len() as u64).next_multiple_of(4096); + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + { + let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); + let queue = device.new_command_queue().unwrap(); + let len = stride * (most + 1); + let buffer = device.new_buffer(len, ResourceOptions::default()).unwrap(); + let bytes = texels_of(&layout, len as usize, 3); + let contents = buffer.contents().unwrap(); + // SAFETY: a new `Shared` buffer of `len` bytes, which no command uses yet. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), contents.as_ptr(), bytes.len()) }; + // The textures each rectangle reads at the buffer's start, the loaded one after them. + let texture_at = |at: u64| { + let mut d = TextureDescriptor::texture_2d(layout.pf, layout.w, layout.h, false); + d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + d.resource_options = buffer.resource_options(); + let texture = buffer.new_texture(&d, at, layout.bpr).unwrap(); + // SAFETY: the handle is only compared, while the texture lives. + assert!(unsafe { texture.vk_image() }.is_none(), "a shadow"); + texture + }; + let read: Vec = (0..most).map(|k| texture_at(k * stride)).collect(); + let loaded = texture_at(most * stride); + let reads = reading(&device, layout.pf, "tob_read"); + let corners = staged(&device, &floats([-1.0, -1.0, 1.0, 1.0])); + // Rectangle `k` of `n`: a band of the texture's rows. + let band = |k: u64, n: u64| { + let rows = layout.h / n; + ScissorRect::new(0, k * rows, layout.w, rows) + }; + let pass = |n: u64| { + let mut pass = RenderPassDescriptor::new(); + let attachment = &mut pass.color_attachments[0]; + attachment.texture = Some(loaded.clone()); + attachment.load_action = LoadAction::Load; + attachment.store_action = StoreAction::Store; + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(&reads).unwrap(); + encoder.set_vertex_buffer(Some(&corners), 0, 0).unwrap(); + for (k, texture) in read.iter().take(n as usize).enumerate() { + encoder.set_scissor_rect(band(k as u64, n)).unwrap(); + encoder.set_fragment_texture(Some(texture), 0).unwrap(); + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0) + .unwrap(); } - )* - }; + encoder.end_encoding().unwrap(); + let before = device.work_counts().commands_replayed.cmd_pipeline_barrier; + run(&command_buffer); + device.work_counts().commands_replayed.cmd_pipeline_barrier - before + }; + // A first pass makes what every pass of the shape needs (the textures' first moves, the + // pipelines' sets), then the counted passes. + let mut expected = bytes.clone(); + let mut barriers = Vec::new(); + for n in [most, 1, most] { + barriers.push(pass(n)); + // Each band of the loaded texture's rows holds its texture's texels there. + for k in 0..n { + let rect = band(k, n); + for y in rect.y..rect.y + rect.height { + let row = (y * layout.bpr) as usize; + let at = (most * stride) as usize + row; + let from = (k * stride) as usize + row; + let width = layout.row() as usize; + let texels = bytes[from..from + width].to_vec(); + expected[at..at + width].copy_from_slice(&texels); + } + } + let now = bytes_of(&buffer); + let (count, first) = differing(&now, &expected, 1); + assert!( + count == 0, + "after a pass of {n} rectangles {count} bytes differ, the first at {first:?}" + ); + } + println!( + "SHADOW-RUN on {}: a pass reading 1 shadowed texture recorded {} pipeline barriers, \ + one reading {most} recorded {}", + device.name(), + barriers[1], + barriers[2], + ); + assert_eq!( + barriers[1], barriers[2], + "barriers of a pass of 1 and of {most} copies in" + ); + drop((read, loaded, buffer)); + } + let messages = messages.take(); + assert!( + messages.is_empty(), + "the validation layer reported: {messages:#?}" + ); } -per_layout! { - a_browser_tile_at_5248_byte_rows_reads_writes_and_renders_as_metal => 0; - a_tile_at_16_byte_padded_rows_reads_writes_and_renders_as_metal => 1; - a_tile_at_256_byte_padded_rows_reads_writes_and_renders_as_metal => 2; - a_tile_at_512_byte_padded_rows_reads_writes_and_renders_as_metal => 3; - a_small_tile_reads_writes_and_renders_as_metal => 4; - a_full_width_strip_reads_writes_and_renders_as_metal => 5; - a_narrow_tile_reads_writes_and_renders_as_metal => 6; +/// A pass that loads a shadowed texture and draws under a scissor beside a depth attachment it +/// clears and stores, which reaches every tile (`clear_reach::PassReach::Every`), `past` pixels +/// wider and taller than the color: where that is some, the depth's clear reaches past the render +/// area to whole tiles and is made before the pass (`clear_reach::ReachClears`, +/// `WorkCounts::attachment_clears_recorded`). Neither clear writes the color, so the draws alone +/// write it, inside the scissor, and its copy in and keep move the texels inside the scissor alone +/// (`WorkCounts::shadow_texels_copied_in`, `shadow_texels_kept`, +/// `shadow_attachment_loads_within`). The buffer holds the blend inside the scissor, as a private +/// texture of the same texels drawn alike does, and every other byte as it was. +fn a_loaded_color_beside_a_cleared_depth_copies_inside_its_scissor(past: u64) { + let layout = LAYOUTS[0]; + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + { + let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); + let queue = device.new_command_queue().unwrap(); + let len = layout.bpr * layout.h; + let buffer = device.new_buffer(len, ResourceOptions::default()).unwrap(); + let bytes = texels_of(&layout, len as usize, 7); + let contents = buffer.contents().unwrap(); + // SAFETY: a new `Shared` buffer of `len` bytes, which no command uses yet. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), contents.as_ptr(), bytes.len()) }; + let mut d = TextureDescriptor::texture_2d(layout.pf, layout.w, layout.h, false); + d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + d.resource_options = buffer.resource_options(); + let texture = buffer.new_texture(&d, 0, layout.bpr).unwrap(); + // SAFETY: the handle is only compared, while the texture lives. + assert!(unsafe { texture.vk_image() }.is_none(), "a shadow"); + let private = private_with(&queue, &layout, &rows(&layout, &bytes)); + // The render area is the color's, 1307 pixels wide, which the depth's clear reaches past + // to 1312, a whole number of 32-pixel tiles, where the depth is wider. + let mut z = TextureDescriptor::texture_2d( + PixelFormat::Depth32Float, + layout.w + past, + layout.h + past, + false, + ); + z.usage = TextureUsage::RENDER_TARGET; + z.resource_options = ResourceOptions::private(); + let depth = device.new_texture(&z).unwrap(); + let blend = rects_beside(&device, layout.pf, true, Some(PixelFormat::Depth32Float)); + let corners = staged(&device, &floats([-1.0, -1.0, 1.0, 1.0])); + let color = staged(&device, &floats([0.25, 0.5, 0.75, 0.5])); + let scissor = ScissorRect::new(100, 40, 300, 200); + let draw = |target: &Texture| { + let mut pass = RenderPassDescriptor::new(); + let attachment = &mut pass.color_attachments[0]; + attachment.texture = Some(target.clone()); + attachment.load_action = LoadAction::Load; + attachment.store_action = StoreAction::Store; + pass.depth_attachment.texture = Some(depth.clone()); + pass.depth_attachment.load_action = LoadAction::Clear; + pass.depth_attachment.store_action = StoreAction::Store; + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(&blend).unwrap(); + encoder.set_scissor_rect(scissor).unwrap(); + encoder.set_vertex_buffer(Some(&corners), 0, 0).unwrap(); + encoder.set_fragment_buffer(Some(&color), 0, 0).unwrap(); + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0) + .unwrap(); + encoder.end_encoding().unwrap(); + run(&command_buffer); + }; + let moved = || { + let counts = device.work_counts(); + [ + counts.attachment_clears_recorded, + counts.shadow_texels_copied_in, + counts.shadow_texels_kept, + counts.shadow_attachment_loads_within, + counts.shadow_attachment_loads_whole, + ] + }; + let before = moved(); + draw(&texture); + let after = moved(); + let [clears, copied_in, kept, within, whole] = + [0, 1, 2, 3, 4].map(|i| after[i] - before[i]); + println!( + "CLEARED-DEPTH-BOUND on {}: a scissored pass beside a cleared depth {past} pixels \ + past the color recorded {clears} attachment clears, copied in {copied_in} texels \ + and kept {kept} ({within} colors loaded within the scissor, {whole} whole)", + device.name(), + ); + assert_eq!( + clears > 0, + past > 0, + "the depth's clear past the render area" + ); + assert_eq!( + (copied_in, kept, within, whole), + (300 * 200, 300 * 200, 1, 0), + "the color's copies inside the scissor" + ); + draw(&private); + let mut expected = bytes.clone(); + lay(&layout, &mut expected, &blit_out(&queue, &layout, &private)); + let now = bytes_of(&buffer); + let (count, first) = differing( + &rows(&layout, &now), + &rows(&layout, &expected), + layout.texel, + ); + assert!( + count == 0, + "{count} texels differ from the private texture's, the first at texel {first:?}" + ); + assert!(now == expected, "the bytes between the rows changed"); + drop((texture, buffer, private, depth)); + } + let messages = messages.take(); + assert!( + messages.is_empty(), + "the validation layer reported: {messages:#?}" + ); +} + +/// [`a_loaded_color_beside_a_cleared_depth_copies_inside_its_scissor`] beside a depth of the +/// color's size. +#[test] +fn a_loaded_color_beside_a_cleared_depth_of_its_size_copies_inside_its_scissor() { + a_loaded_color_beside_a_cleared_depth_copies_inside_its_scissor(0); +} + +/// [`a_loaded_color_beside_a_cleared_depth_copies_inside_its_scissor`] beside a larger depth, +/// whose clear reaches past the render area. +#[test] +fn a_clear_past_the_render_area_leaves_a_loaded_color_s_copies_inside_its_scissor() { + a_loaded_color_beside_a_cleared_depth_copies_inside_its_scissor(64); +} + +/// One draw of [`merged_writes_match_metal`]'s: its scissor (none: the whole target), its +/// viewport (none: the whole target), its color, and a barrier over textures before it, which +/// splits the pass there. +#[derive(Clone, Copy)] +struct Stroke { + scissor: Option, + viewport: Option<[f64; 4]>, + color: usize, + split: bool, +} + +/// [`Stroke`] under `scissor` alone. +fn stroke(scissor: (u64, u64, u64, u64), color: usize) -> Stroke { + let (x, y, w, h) = scissor; + Stroke { + scissor: Some(ScissorRect::new(x, y, w, h)), + viewport: None, + color, + split: false, + } +} + +/// Passes that load a shadowed texture over a buffer's bytes and draw under scissors that change +/// from draw to draw, in instances a barrier splits, across encoders and command buffers, with a +/// viewport and no scissor, under scissors at the right and bottom edges, and through a second +/// texture over the same bytes between them, leave the bytes as a private texture of the same +/// texels drawn alike holds them: each merge's keep and merge are cut to the rectangle the +/// encoder's commands write in (`shadow_merge.rs`), and no write outside it is lost. Over a +/// `Shared` buffer and over a no-copy buffer's host pages, of `layout`. +fn merged_writes_match_metal(layout: Layout) { + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + { + let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); + let queue = device.new_command_queue().unwrap(); + let blend = blending(&device, layout.pf); + let corners = staged(&device, &floats([-1.0, -1.0, 1.0, 1.0])); + let colors = [ + staged(&device, &floats([0.25, 0.5, 0.75, 0.5])), + staged(&device, &floats([0.9, 0.1, 0.3, 0.75])), + ]; + let (w, h) = (layout.w, layout.h); + // Each command buffer's passes, each pass's strokes, the second texture's pass marked. + // Every scissor lies inside the target, as Metal's validation requires, at fractions of + // its size, so each stroke draws over every layout. + let passes: Vec)>> = vec![ + vec![ + ( + false, + vec![ + stroke((w / 13, h / 12, w / 4, h / 3), 0), + stroke((w / 2, h / 2, w / 4, h / 4), 1), + ], + ), + ( + false, + vec![ + stroke((w / 26, h / 6, w / 5, h / 5), 1), + Stroke { + split: true, + ..stroke((w * 5 / 8, h * 5 / 8, w / 4, h / 5), 0) + }, + Stroke { + split: true, + ..stroke((5, h * 5 / 8, w / 9, h / 3), 1) + }, + ], + ), + ], + vec![ + (true, vec![stroke((w / 3, h / 10, w / 4, h / 2), 0)]), + ( + false, + vec![Stroke { + scissor: None, + viewport: Some([ + w as f64 / 4.0, + h as f64 / 5.0, + w as f64 / 3.0, + h as f64 / 4.0, + ]), + color: 1, + split: false, + }], + ), + ( + false, + vec![ + stroke((w - 13, h - 7, 13, 7), 0), + stroke((w - 1, 0, 1, h), 1), + ], + ), + (false, vec![stroke((0, 0, w, h), 0)]), + ], + ]; + let encode = |command_buffer: &metal2vulkan_runtime::CommandBuffer, + target: &Texture, + strokes: &[Stroke]| { + let mut pass = RenderPassDescriptor::new(); + let attachment = &mut pass.color_attachments[0]; + attachment.texture = Some(target.clone()); + attachment.load_action = LoadAction::Load; + attachment.store_action = StoreAction::Store; + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(&blend).unwrap(); + encoder.set_vertex_buffer(Some(&corners), 0, 0).unwrap(); + for s in strokes { + if s.split { + encoder.memory_barrier_with_scope( + BarrierScope::TEXTURES, + RenderStages::FRAGMENT, + RenderStages::FRAGMENT, + ); + } + let scissor = s.scissor.unwrap_or(ScissorRect::new(0, 0, w, h)); + assert!( + scissor.width > 0 + && scissor.height > 0 + && scissor.x + scissor.width <= w + && scissor.y + scissor.height <= h, + "{}: the scissor {scissor:?} lies outside the {w}x{h} target", + layout.name + ); + encoder.set_scissor_rect(scissor).unwrap(); + let [x, y, vw, vh] = s.viewport.unwrap_or([0.0, 0.0, w as f64, h as f64]); + encoder + .set_viewport(Viewport::new(x, y, vw, vh, 0.0, 1.0)) + .unwrap(); + encoder + .set_fragment_buffer(Some(&colors[s.color]), 0, 0) + .unwrap(); + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0) + .unwrap(); + } + encoder.end_encoding().unwrap(); + }; + // The passes through `first` (and `second`, a texture over the same bytes, where marked), + // command buffer by command buffer, waited for at the end. + let draw_all = |first: &Texture, second: &Texture| { + let mut committed = Vec::new(); + for buffer_passes in &passes { + let command_buffer = queue.command_buffer().unwrap(); + for (twin, strokes) in buffer_passes { + encode(&command_buffer, if *twin { second } else { first }, strokes); + } + command_buffer.commit().unwrap(); + committed.push(command_buffer); + } + for command_buffer in &committed { + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + } + }; + let usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + let texture_over = |buffer: &Buffer| { + let mut d = TextureDescriptor::texture_2d(layout.pf, w, h, false); + d.usage = usage; + d.resource_options = buffer.resource_options(); + buffer.new_texture(&d, 0, layout.bpr).unwrap() + }; + // Over a `Shared` buffer. + let len = layout.bpr * h; + let buffer = device.new_buffer(len, ResourceOptions::default()).unwrap(); + let bytes = texels_of(&layout, len as usize, 3); + let contents = buffer.contents().unwrap(); + // SAFETY: a new `Shared` buffer of `len` bytes, which no command uses yet. + unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), contents.as_ptr(), bytes.len()) }; + let (first, second) = (texture_over(&buffer), texture_over(&buffer)); + // SAFETY: the handle is only compared, while the texture lives. + assert!(unsafe { first.vk_image() }.is_none(), "a shadow"); + let private = private_with(&queue, &layout, &rows(&layout, &bytes)); + draw_all(&first, &second); + draw_all(&private, &private); + let mut expected = bytes.clone(); + lay(&layout, &mut expected, &blit_out(&queue, &layout, &private)); + let now = bytes_of(&buffer); + let (count, at) = differing( + &rows(&layout, &now), + &rows(&layout, &expected), + layout.texel, + ); + assert!( + count == 0, + "{}, a Shared buffer: {count} texels differ from the private texture's, the first at \ + texel {at:?}", + layout.name + ); + assert!( + now == expected, + "{}, a Shared buffer: the bytes between the rows changed", + layout.name + ); + drop((first, second, buffer, private)); + // Over a no-copy buffer's host pages. + if let Some(surface) = surface(&device, &layout, usage) { + let second = surface + .buffer + .new_texture( + &{ + let mut d = TextureDescriptor::texture_2d(layout.pf, w, h, false); + d.usage = usage; + d.resource_options = surface.buffer.resource_options(); + d + }, + 0, + layout.bpr, + ) + .unwrap(); + let private = private_with(&queue, &layout, &rows(&layout, &surface.pages)); + draw_all(&surface.texture, &second); + draw_all(&private, &private); + let mut expected = surface.pages.clone(); + lay(&layout, &mut expected, &blit_out(&queue, &layout, &private)); + surface.check(&layout, "passes cut to their scissors", &expected); + drop((second, private)); + surface.report(&device, &messages); + } + } + let messages = messages.take(); + assert!( + messages.is_empty(), + "the validation layer reported: {messages:#?}" + ); +} + +#[test] +fn merged_writes_match_metal_over_the_browser_tile() { + merged_writes_match_metal(LAYOUTS[0]); +} + +#[test] +fn merged_writes_match_metal_over_a_half_float_tile() { + merged_writes_match_metal(LAYOUTS[7]); +} + +#[test] +fn merged_writes_match_metal_over_a_narrow_tile() { + merged_writes_match_metal(LAYOUTS[6]); +} + +/// A texture of `layout` over a no-copy buffer, with shader read and write usage, written at every +/// texel by a fragment function's `write` (`tob_write`): the pages' texels are what a private +/// texture of the same texels holds after the same writes, and no other byte of the pages changes. +fn writes_as_metal(layout: Layout) { + let cache = ScratchCache::new().unwrap(); a_half_float_tile_reads_writes_and_renders_as_metal => 7; a_tile_of_510_packed_rows_reads_writes_and_renders_as_metal => 8; a_small_tile_of_packed_rows_reads_writes_and_renders_as_metal => 9; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/surface_texture_costs.rs b/crates/metal2vulkan-validation/src/runtime_lane/surface_texture_costs.rs index 3948470cf..75989aa34 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/surface_texture_costs.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/surface_texture_costs.rs @@ -22,6 +22,7 @@ //! and 90th percentile of the host's time making the buffer, making the texture and releasing //! both, per texture; per frame, the encoding and the commit-to-completion wall time and the //! process's CPU time; and the device's work counts per frame that the path moves (dma-buf images +//! submissions, shadows' copies and the texels their copies in and back move, the merges' //! scratches reused and zeroed, the merges that fetched their texels, the command buffers begun by //! what for, the render pass begins and secondary executions replayed, and the passes whose first //! instance recorded inline). @@ -29,7 +30,8 @@ //! [`surface_texture_cost_parts`] takes the frame apart over anonymous pages: the textures' making //! around an empty command buffer, the passes that store, the passes that store `DontCare`, the //! passes that draw and store, the blits, and both, so a shadow's copies in and back show apart -//! from the rest (`SURFTEX-PART`). +//! from the rest (`SURFTEX-PART`), then over `Private` buffers: a shadow over the pages, which the +//! CPU may write, is merged back, and one over a tracked `Private` buffer's bytes copied back. //! //! [`shadow_copy_costs`] times a shadow's copies alone, and the same bytes moved between other //! memories, to tell the image's tiling from the pages' memory (`SURFTEX-COPY`). @@ -163,6 +165,15 @@ fn plane_texture(buffer: &Buffer, width: u64, height: u64, bpr: u64) -> Texture .unwrap() } +/// A texture `width`x`height` with rows `bpr` bytes apart over the `Private` `buffer`'s first +/// byte, as [`plane_texture`]'s is used. +fn private_texture(buffer: &Buffer, width: u64, height: u64, bpr: u64) -> Texture { + let mut d = TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, width, height, false); + d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ; + d.resource_options = ResourceOptions::private(); + buffer.new_texture(&d, 0, bpr).unwrap() +} + /// Whether `texture`'s texels are its own image over the buffer's memory: aliased, not shadowed. fn aliased(texture: &Texture) -> bool { // SAFETY: the handle is only compared, while the texture lives. @@ -283,6 +294,7 @@ fn counts_per_frame(before: &WorkCounts, after: &WorkCounts, frames: usize) -> S recalled {:.2}), dma-buf images {:.2}, dma-buf image fallbacks {:.2}, dma-buf imports \ {:.2}, images started on the host {:.2}, internal submissions {:.2}, staging submissions \ {:.2}, shadow copies {:.2} (texels copied in {:.0}, back {:.0}; copies back dispatched \ + {:.2}; keeps and merges dispatched {:.2}, texels kept {:.0}; merge scratches reused \ {:.2}, zeroed {:.2}; merges fetched {:.2}); command buffers begun {:.2} (encoders' own \ {:.2}, segments {:.2}, draws' secondaries {:.2}, batches' {:.2}, barriers kept {:.2}, \ internal {:.2}), render pass begins replayed {:.2}, secondaries executed {:.2}, passes \ @@ -323,28 +335,20 @@ fn counts_per_frame(before: &WorkCounts, after: &WorkCounts, frames: usize) -> S after.shadow_copies_back_dispatched, before.shadow_copies_back_dispatched ), - ) -} - -/// What the driver answers for a `B8G8R8A8_UNORM` image of `DRM_FORMAT_MOD_LINEAR` tiling made for -/// host allocations, at each usage the runtime may ask of a surface's texture: whether it makes -/// one, and whether it imports host memory for it (`SURFTEX-QUERY`). -fn print_host_modifier_queries(device: &Device) { - // SAFETY: read while the device lives; nothing is made. - let raw = unsafe { device.raw() }; - let sampled = vk::ImageUsageFlags::SAMPLED - | vk::ImageUsageFlags::TRANSFER_SRC - | vk::ImageUsageFlags::TRANSFER_DST; - for (name, usage) in [ - ("sampled", sampled), - ( - "sampled+color", - sampled | vk::ImageUsageFlags::COLOR_ATTACHMENT, + per( + after.shadow_merge_copies_dispatched, + before.shadow_merge_copies_dispatched ), - ( - "sampled+color+storage", - sampled | vk::ImageUsageFlags::COLOR_ATTACHMENT | vk::ImageUsageFlags::STORAGE, + per(after.shadow_texels_kept, before.shadow_texels_kept), + per( + after.shadow_merge_scratches_reused, + before.shadow_merge_scratches_reused ), + per( + after.shadow_merge_scratches_zeroed, + before.shadow_merge_scratches_zeroed + ), + per(after.shadow_merges_fetched, before.shadow_merges_fetched), per(after.command_buffers_begun, before.command_buffers_begun), per( after.command_buffers_begun_encoders, @@ -534,12 +538,13 @@ fn surface_texture_costs() { /// [`LAYOUTS`] each frame, taken apart ([`Part`]): the textures made and released around an empty /// command buffer, the passes that store, the passes that store `DontCare`, the passes that draw a /// rectangle and store (also under a scissor of the left half), the blits, and both; -/// then the same over the packed layouts alone, which no shadow is made beside. Where a texture is -/// a shadow, the passes that store less the empty frame are its copies in and back and the pass, -/// the passes that do not store less the empty frame its copies in and the pass; the blits read -/// the bytes either way. Printed per set and part (`SURFTEX-PART`): the textures' forms, the -/// medians and 90th percentiles of each one's making (its buffer and texture), of the frame's -/// release, encoding, commit to completion and process CPU time, and the work counts per frame. +/// then the same over the packed layouts alone, which no shadow is made beside; then over every +/// layout again, each texture over a `Private` buffer of the layout's bytes made once, a new +/// texture over it each frame. Where a texture is a shadow, the passes that store less the empty +/// frame are its copies in and back and the pass, the passes that do not store less the empty +/// frame its copies in and the pass; the blits read the bytes either way. A shadow over the pages +/// is kept and merged back in place of a copy back, and one over a tracked `Private` buffer's +/// bytes copied back. Printed per set and part (`SURFTEX-PART`): the #[test] #[ignore = "a release-mode measurement: run by name"] fn surface_texture_cost_parts() { @@ -568,6 +573,14 @@ fn surface_texture_cost_parts() { .iter() .map(|&len| Surface::Anonymous(Mapping::anonymous(len))) .collect(); + let private_buffers: Vec = lens + .iter() + .map(|&len| { + device + .new_buffer(len as u64, ResourceOptions::private()) + .unwrap() + }) + .collect(); // Every layout, then the packed ones alone (rows one after another, no texture a shadow). let every: Vec = (0..LAYOUTS.len()).collect(); let packed: Vec = every @@ -586,7 +599,12 @@ fn surface_texture_cost_parts() { ]; let drawing = Drawing::new(&device); let drawing = Some(&drawing); - for (set, chosen) in [("every layout", &every), ("packed layouts", &packed)] { + let sets = [ + ("every layout", &every, false), + ("packed layouts", &packed, false), + ("every layout over Private buffers", &every, true), + ]; + for (set, chosen, over_private) in sets { let privates: Vec = chosen.iter().map(|&i| privates[i].clone()).collect(); for part in parts { let mut forms = Vec::new(); @@ -603,8 +621,18 @@ fn surface_texture_cost_parts() { for (at, &index) in chosen.iter().enumerate() { let (_, w, h, bpr) = LAYOUTS[index]; let began = Instant::now(); - let buffer = surfaces[index].buffer(&device, lens[index], None); - let texture = plane_texture(&buffer, w, h, bpr); + let (buffer, texture) = match over_private { + false => { + let buffer = surfaces[index].buffer(&device, lens[index], None); + let texture = plane_texture(&buffer, w, h, bpr); + (buffer, texture) + } + true => { + let buffer = private_buffers[index].clone(); + let texture = private_texture(&buffer, w, h, bpr); + (buffer, texture) + } + }; if k >= WARM { makes[at].push(since(began)); } @@ -654,7 +682,7 @@ fn surface_texture_cost_parts() { ); } } - drop(surfaces); + drop((surfaces, private_buffers)); let notices = super::degrade_notices::counts(&messages.take_notices()); println!("SURFTEX-NOTICES on {}: {notices:?}", device.name()); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/tile_edges.rs b/crates/metal2vulkan-validation/src/runtime_lane/tile_edges.rs index d10bedd76..b87515a4d 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/tile_edges.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/tile_edges.rs @@ -10,17 +10,22 @@ //! - when the pass begins, a loaded attachment's cells past it hold its texel nearest each, //! clamped to its edge, and a cleared one's the clear color; //! - a tile function's writes to them are what the pass's next dispatch reads. +//! +//! [`a_shadowed_attachment_s_tiles_past_its_render_area_hold_its_texels`] runs a draw and a +//! dispatch over a render area smaller than a shadowed attachment, whose tiles reach past the area +//! inside it. +use super::no_copy_textures::{floats, rects, staged}; use super::tile_states::on_device; use super::{buffer_with, read_buffer, WAIT}; use crate::air_library::AirLibrary; -use metal2vulkan::metal::{PixelFormat, TextureUsage}; +use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; use metal2vulkan::pipeline::{StageSource, TileRenderPipelineDescriptor}; use metal2vulkan_devtools::{engine_dir, llvm_assemble}; use metal2vulkan_runtime::{ Buffer, ClearColor, CommandBufferStatus, Device, LoadAction, PipelineOptions, Region, - RenderPassDescriptor, RenderPipelineState, ResourceOptions, Size, StoreAction, Texture, - TextureDescriptor, + RenderPassDescriptor, RenderPipelineState, ResourceOptions, ScissorRect, Size, StoreAction, + Texture, TextureDescriptor, }; /// The tile's side. @@ -210,3 +215,102 @@ fn writes_past_the_attachment_last_for_the_pass() { } }); } + +/// The attachment of [`a_shadowed_attachment_s_tiles_past_its_render_area_hold_its_texels`]: its +/// width and height, and its rows' pitch, padded past their 160 bytes of texels. +const SHADOWED: [u64; 2] = [40, 40]; +const SHADOWED_ROW: u64 = 176; + +/// That pass's render area, one tile across and two down, whose tiles reach past it inside the +/// attachment, and the scissor rectangle of its draw inside it. +const AREA: [u64; 2] = [12, 20]; +const SCISSOR: [u64; 4] = [3, 5, 6, 9]; + +/// The codes of that draw's color `(1, 0.2, 0.6, 1)`. +const DRAWN: [u8; 4] = [255, 51, 153, 255]; + +/// A pass that loads a shadowed attachment (a texture over a buffer's padded rows, the runtime's +/// `shadow.rs`) over a render area smaller than it, of a draw inside the area and then a dispatch +/// of `cfb_tn_read4`: the dispatch reads, in each cell of the tiles over the area, the drawn color +/// inside the draw's scissor rectangle and the attachment's texel elsewhere, past the area too, +/// where the dispatch's stores reach (`render/tile_dispatch.rs`): the shadow's image holds what +/// the dispatch reads, though the pass's draw reaches a part of it alone. The buffer holds the +/// drawn color inside the rectangle, and every other byte as it was. +#[test] +fn a_shadowed_attachment_s_tiles_past_its_render_area_hold_its_texels() { + on_device(|device| { + let [w, h] = SHADOWED; + let len = SHADOWED_ROW * h; + let mut bytes: Vec = (0..len).map(|i| (i * 7 + 3) as u8).collect(); + for y in 0..h { + for x in 0..w { + let at = (y * SHADOWED_ROW + x * 4) as usize; + bytes[at..at + 4].copy_from_slice(&texel(x, y)); + } + } + let buffer = staged(device, &bytes); + let mut d = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, w, h, false); + d.usage = TextureUsage::RENDER_TARGET; + d.resource_options = buffer.resource_options(); + let target = buffer.new_texture(&d, 0, SHADOWED_ROW).unwrap(); + // SAFETY: the handle is only compared, while the texture lives. + assert!(unsafe { target.vk_image() }.is_none(), "a shadow"); + let draw = rects(device, PixelFormat::RGBA8Unorm, false); + let read = state(device, "cfb_tn_read4"); + let corners = staged(device, &floats([-1.0, -1.0, 1.0, 1.0])); + let color = staged(device, &floats([1.0, 0.2, 0.6, 1.0])); + let out = buffer_with(device, &vec![0xAB; (CELLS * 16) as usize]).unwrap(); + let mut pass = RenderPassDescriptor::new(); + pass.color_attachments[0].texture = Some(target.clone()); + pass.color_attachments[0].load_action = LoadAction::Load; + pass.color_attachments[0].store_action = StoreAction::Store; + [pass.render_target_width, pass.render_target_height] = AREA; + pass.tile_width = TILE; + pass.tile_height = TILE; + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(&draw).unwrap(); + encoder.set_vertex_buffer(Some(&corners), 0, 0).unwrap(); + encoder.set_fragment_buffer(Some(&color), 0, 0).unwrap(); + let [x, y, width, height] = SCISSOR; + encoder + .set_scissor_rect(ScissorRect::new(x, y, width, height)) + .unwrap(); + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0) + .unwrap(); + encoder.set_render_pipeline_state(&read).unwrap(); + encoder.set_tile_buffer(Some(&out), 0, 0).unwrap(); + encoder + .dispatch_threads_per_tile(Size::new(TILE, TILE, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + let drawn = |x: u64, y: u64| { + (SCISSOR[0]..SCISSOR[0] + SCISSOR[2]).contains(&x) + && (SCISSOR[1]..SCISSOR[1] + SCISSOR[3]).contains(&y) + }; + let want = |x: u64, y: u64| if drawn(x, y) { DRAWN } else { texel(x, y) }; + for (i, have) in codes(&out).into_iter().enumerate() { + let (x, y) = (i as u64 % TILE, i as u64 / TILE); + assert_eq!(have, want(x, y), "cell ({x}, {y})"); + } + let mut expected = bytes.clone(); + for y in 0..h { + for x in 0..w { + let at = (y * SHADOWED_ROW + x * 4) as usize; + expected[at..at + 4].copy_from_slice(&want(x, y)); + } + } + let contents = buffer.contents().unwrap(); + let mut now = vec![0u8; len as usize]; + // SAFETY: the buffer's `len` bytes, which no command uses once the command buffer + // completed. + unsafe { std::ptr::copy_nonoverlapping(contents.as_ptr(), now.as_mut_ptr(), now.len()) }; + let differ = (0..now.len()).find(|&i| now[i] != expected[i]); + assert_eq!(differ, None, "the first byte of the buffer that differs"); + }); +} diff --git a/crates/metal2vulkan/src/bind/mod.rs b/crates/metal2vulkan/src/bind/mod.rs index f519a981a..7e1840858 100644 --- a/crates/metal2vulkan/src/bind/mod.rs +++ b/crates/metal2vulkan/src/bind/mod.rs @@ -69,8 +69,12 @@ //! [`flat_dispatch_module`], which reads its arguments on the device ([`FlatIndirect`]). Where one //! command writes a buffer's bytes through a texture copied in and out of them and also another //! way, [`shadow_merge_module`] merges the bytes the texture changed into the buffer's in place of -//! the copy back, and where a device copies a shadow back faster by a dispatch, -//! [`shadow_copy_back_module`] stores its texels' words at their rows. A render pass that loads a +//! the copy back ([`shadow_merge_image_module`] reading the shadow's texels through its +//! dispatch, [`shadow_copy_back_module`] stores its texels' words at their rows, and +//! [`shadow_copy_in_module`] copies a merged texture's texels in and keeps them with one dispatch. +//! A copy of many +//! equal rows between two buffers is one dispatch of [`rows_copy_module`] where a copy's region +//! per row costs more. A render pass that loads a //! 32-bit float depth holding a value Vulkan's depth test compares otherwise than Metal's (a //! negative value or a NaN, whose magnitude Metal compares) renders over its stand-in, written //! before the pass and merged back after it by [`depth_magnitude_module`]. A blit between a buffer @@ -156,7 +160,9 @@ pub(crate) mod rotate_texels; pub(crate) mod sample_interleave; pub(crate) mod sample_planes; pub(crate) mod shadow_copy_back; +pub(crate) mod shadow_copy_in; pub(crate) mod shadow_merge; +pub(crate) mod shadow_merge_image; pub(crate) mod state; pub(crate) mod status; pub(crate) mod table; @@ -279,7 +285,8 @@ pub use sample_interleave::{ pub use sample_planes::{ planes_merge_modules, planes_split_module, PlanesCopy, PlanesMergeModules, PlanesSplitModule, }; -pub use shadow_copy_back::{shadow_copy_back_module, ShadowCopyBackModule}; +pub use shadow_copy_back::{shadow_copy_back_module, ShadowCopyBackModule, ShadowTexelView}; +pub use shadow_copy_in::{shadow_copy_in_module, ShadowCopyInModule}; pub use shadow_merge::{shadow_merge_module, ShadowMergeModule}; pub use status::{ ExecutionStatus, MeshRecordsFault, ReplayFaults, StatusBits, StatusReport, StatusWord, diff --git a/crates/metal2vulkan/src/bind/shadow_copy_back.rs b/crates/metal2vulkan/src/bind/shadow_copy_back.rs index 8e8c9672d..463541b45 100644 --- a/crates/metal2vulkan/src/bind/shadow_copy_back.rs +++ b/crates/metal2vulkan/src/bind/shadow_copy_back.rs @@ -10,16 +10,20 @@ //! compatible formats will have the same mapping between texel coordinates and memory locations //! irrespective of the format, with only the interpretation of the bit pattern changing" //! (`VkImageViewCreateInfo`), and an unsigned-integer view returns its components' bits -//! unconverted, so the words a fetch returns are the texel's bytes as the copy writes them. +//! unconverted, so the words a fetch returns are the texel's bytes as the copy writes them. The +//! view is the consumer's choice of [`ShadowTexelView`]: a 4-byte texel's `R32_UINT` view returns +//! its word, and its `R8G8B8A8_UINT` view its bytes in memory order (byte `i` in component `i`), +//! which the kernel packs into the word (byte `i` at bits `8i` onward, [`fetched_words`]); a +//! wider texel's is the 32-bit unsigned format of its width, whose components are its words. //! -//! **The module** (one per texel width: 1, 2 or 4 words). One `GLCompute` entry `main` with local +//! **The module** (one per view, [`ShadowTexelView`]). One `GLCompute` entry `main` with local //! size ([`ShadowCopyBackModule::LOCAL_SIZE`], 1, 1), [`ShadowCopyBackModule::PUSH_BYTES`] of //! `COMPUTE` push constants at offset 0 (the region's shape, [`ShadowCopyBackModule::shape`]), //! and in set 0: //! //! | Binding | Resource | //! |---|---| -//! | [`ShadowCopyBackModule::IMAGE_BINDING`] | the shadow's sampled view of `R32_UINT`, `R32G32_UINT` or `R32G32B32A32_UINT`, the format of the texel's width, in the `GENERAL` layout | +//! | [`ShadowCopyBackModule::IMAGE_BINDING`] | the shadow's sampled view of the module's format ([`ShadowTexelView`]), in the `GENERAL` layout | //! | [`ShadowCopyBackModule::BYTES_BINDING`] | a storage buffer over the buffer's bytes, a whole number of 4-byte words | //! //! The shape's words, in order: `origin`, the region's first texel `x0` in its low 16 bits and @@ -52,7 +56,52 @@ use crate::spirv::ir::{ LayoutRule, MemAccess, StorageClass, Type, TypedModule, }; -/// The crate-owned copy-back module of one texel width on one device, validated like any output. +/// The unsigned-integer view of a shadow that its kernels read its texels through, and a copy in +/// stores them through ([`shadow_copy_back_module`], `shadow_merge_image_module`, +/// word's or its bytes'. Every one shares the texel's compatibility class, so a view of any +/// reads and stores the texel's bits unconverted. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum ShadowTexelView { + /// `R32_UINT`: a 4-byte texel's word, in component 0. + R32Uint, + /// `R8G8B8A8_UINT`: a 4-byte texel's bytes, byte `i` in component `i`. + R8G8B8A8Uint, + /// `R32G32_UINT`: an 8-byte texel's words. + R32G32Uint, + /// `R32G32B32A32_UINT`: a 16-byte texel's words. + R32G32B32A32Uint, +} + +impl ShadowTexelView { + /// Every view. + pub const ALL: [ShadowTexelView; 4] = [ + ShadowTexelView::R32Uint, + ShadowTexelView::R8G8B8A8Uint, + ShadowTexelView::R32G32Uint, + ShadowTexelView::R32G32B32A32Uint, + ]; + + /// The texel's 4-byte words: 1, 2 or 4. + pub fn words(self) -> u32 { + match self { + ShadowTexelView::R32Uint | ShadowTexelView::R8G8B8A8Uint => 1, + ShadowTexelView::R32G32Uint => 2, + ShadowTexelView::R32G32B32A32Uint => 4, + } + } + + /// The view's storage image format, as a copy in declares it. + pub(crate) fn storage_format(self) -> crate::spv::ImageFormat { + match self { + ShadowTexelView::R32Uint => crate::spv::ImageFormat::R32ui, + ShadowTexelView::R8G8B8A8Uint => crate::spv::ImageFormat::Rgba8ui, + ShadowTexelView::R32G32Uint => crate::spv::ImageFormat::Rg32ui, + ShadowTexelView::R32G32B32A32Uint => crate::spv::ImageFormat::Rgba32ui, + } + } +} + +/// The crate-owned copy-back module of one view on one device, validated like any output. #[non_exhaustive] #[derive(Clone, Debug, PartialEq, Eq)] pub struct ShadowCopyBackModule { @@ -128,11 +177,64 @@ fn u32_value(f: &mut FunctionBuilder<'_>, v: u32) -> BResult { f.module().const_value(c) } -/// The copy-back module of texels `words` words wide (1, 2 or 4) as a typed module, before -/// serialization: the module [`shadow_copy_back_module`] serializes, which the CPU interpreter -/// runs. Its bindings are the symbols `IMAGE` and `BYTES`, and its push field the shape, a -/// `uvec4` (the module docs). -fn typed_module(words: u32) -> BResult { +/// The words of a texel that a fetch through the shadow's `view` returned (`texel`, a `uvec4`): +/// an `R8G8B8A8_UINT` view's components, its bytes, packed into one word (byte `i` at bits `8i` +/// onward); another view's components, its words (the module docs). +pub(super) fn fetched_words( + f: &mut FunctionBuilder<'_>, + texel: Value, + view: ShadowTexelView, +) -> BResult> { + if view != ShadowTexelView::R8G8B8A8Uint { + return (0..view.words()) + .map(|lane| f.composite_extract(texel, &[lane])) + .collect(); + } + let mut word = f.composite_extract(texel, &[0])?; + for lane in 1..4u32 { + let byte = f.composite_extract(texel, &[lane])?; + let shift = u32_value(f, 8 * lane)?; + let byte = f.binary(BinOp::ShiftLeftLogical, byte, shift)?; + word = f.binary(BinOp::BitwiseOr, word, byte)?; + } + Ok(vec![word]) +} + +/// The `uvec4` a store of a texel of `words` (its words, in memory order) through the shadow's +/// `view` takes, as [`fetched_words`] reads it back: an `R8G8B8A8_UINT` view's bytes, one a +/// component; another view's words, zero in the components it lacks. +pub(super) fn stored_texel( + f: &mut FunctionBuilder<'_>, + uvec4: TypeId, + view: ShadowTexelView, + words: &[Value], +) -> BResult { + let zero = u32_value(f, 0)?; + let components = match (view, words) { + (ShadowTexelView::R8G8B8A8Uint, [word]) => { + let byte = u32_value(f, 0xff)?; + let mut bytes = Vec::with_capacity(4); + for lane in 0..4u32 { + let shift = u32_value(f, 8 * lane)?; + let shifted = f.binary(BinOp::ShiftRightLogical, *word, shift)?; + bytes.push(f.binary(BinOp::BitwiseAnd, shifted, byte)?); + } + bytes + } + _ => { + let mut lanes = words.to_vec(); + lanes.resize(4, zero); + lanes + } + }; + f.composite_construct(uvec4, &components) +} + +/// The copy-back module of `view` as a typed module, before serialization: the module +/// [`shadow_copy_back_module`] serializes, which the CPU interpreter runs. Its bindings are the +/// symbols `IMAGE` and `BYTES`, and its push field the shape, a `uvec4` (the module docs). +fn typed_module(view: ShadowTexelView) -> BResult { + let words = view.words(); let mut b = ModuleBuilder::new(); let u32_ = b.ty(Type::Int { width: 32, @@ -143,7 +245,7 @@ fn typed_module(words: u32) -> BResult { let uvec4 = b.ty(Type::Vector { elem: u32_, len: 4 })?; let m_shape = b.push_member(SHAPE, uvec4, 0)?; let push = b.push_global()?; - let view = b.ty(Type::Image(ImageType { + let image_type = b.ty(Type::Image(ImageType { sampled_type: u32_, dim: Dim::D2, depth: false, @@ -152,7 +254,7 @@ fn typed_module(words: u32) -> BResult { usage: ImageUsage::Sampled, format: crate::spv::ImageFormat::Unknown, }))?; - let image = b.resource(IMAGE, StorageClass::UniformConstant, view)?; + let image = b.resource(IMAGE, StorageClass::UniformConstant, image_type)?; let bytes = words_buffer(&mut b, BYTES, u32_)?; let invocation = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?; let void = b.ty(Type::Void)?; @@ -192,12 +294,12 @@ fn typed_module(words: u32) -> BResult { ..ImageOperands::default() }; let texel = f.fetch(image, coord, &ops)?; + let texel = fetched_words(f, texel, view)?; let row = f.binary(BinOp::IMul, y, row_words)?; let column = f.binary(BinOp::IMul, x, n)?; let at = f.binary(BinOp::IAdd, first_word, row)?; let at = f.binary(BinOp::IAdd, at, column)?; - for (lane, &index) in lanes.iter().enumerate() { - let word = f.composite_extract(texel, &[lane as u32])?; + for (&word, &index) in texel.iter().zip(&lanes) { let place = f.binary(BinOp::IAdd, at, index)?; let to = f.access_chain(bytes, &[zero, place])?; f.store(to, word, MemAccess::default())?; @@ -229,22 +331,15 @@ fn binding_of(sym: &Symbol) -> Option { } } -/// The copy-back module of `device` for texels `texel_words` 4-byte words wide (1, 2 or 4; an -/// internal error for another width): built with the typed builder, checked by the owned -/// verifier against the device's profile (requirements included), serialized, and numbered with -/// the fixed bindings of [`ShadowCopyBackModule`]. +/// The copy-back module of `device` reading texels through `view`: built with the typed builder, +/// checked by the owned verifier against the device's profile (requirements included), +/// serialized, and numbered with the fixed bindings of [`ShadowCopyBackModule`]. pub fn shadow_copy_back_module( device: &Device, - texel_words: u32, + view: ShadowTexelView, ) -> Result { - if !matches!(texel_words, 1 | 2 | 4) { - return Err(Error::Internal(InternalError::new( - InternalKind::Invariant, - format!("a shadow copy back of texels {texel_words} words wide"), - ))); - } let profile = device.profile(); - let m = typed_module(texel_words)?; + let m = typed_module(view)?; let mut meter = Meter::new(&Budget::default()); crate::spirv::verify::verify(&m, profile, &mut meter)?; let r = crate::spirv::serialize::serialize(m)?; @@ -263,29 +358,38 @@ pub fn shadow_copy_back_module( #[cfg(test)] mod tests { - use super::{typed_module, ShadowCopyBackModule, BYTES, IMAGE}; + use super::{typed_module, ShadowCopyBackModule, ShadowTexelView, BYTES, IMAGE}; use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Order, Resources}; use crate::spirv::testing::{assert_valid, committed_profiles}; #[test] fn the_copy_back_kernels_are_valid_on_every_committed_profile() { for (_, p) in committed_profiles().expect("profiles") { - for words in [1, 2, 4] { - assert_valid(typed_module(words).expect("module"), &p); + for view in ShadowTexelView::ALL { + assert_valid(typed_module(view).expect("module"), &p); } } } - /// A `[width, height]` image of texels `words` words wide, texel `(x, y)`'s word `i` - /// `0x0100_0000 · (i + 1) + 0x1000 · y + x`, as a view of the width's format returns it - /// (the components a view lacks 0, and alpha 1). - fn image([width, height]: [u32; 2], words: u32) -> Image { + /// A `[width, height]` image of texels whose word `i` at `(x, y)` is + /// `0x0100_0000 · (i + 1) + 0x1000 · y + x`, as `view` returns it: an `R8G8B8A8_UINT` view's + /// components its word's bytes, another view's its words (the components a view lacks 0, and + /// alpha 1). + fn image([width, height]: [u32; 2], view: ShadowTexelView) -> Image { let mut image = Image::new(IMAGE, [width, height, 1], 1, 1, 1); for y in 0..height { for x in 0..width { + let word = |i: u32| 0x0100_0000 * (i + 1) + 0x1000 * y + x; let mut texel = [0, 0, 0, 1]; - for (i, c) in texel.iter_mut().enumerate().take(words as usize) { - *c = 0x0100_0000 * (i as u32 + 1) + 0x1000 * y + x; + match view { + ShadowTexelView::R8G8B8A8Uint => { + texel = word(0).to_le_bytes().map(u32::from); + } + _ => { + for (i, c) in texel.iter_mut().enumerate().take(view.words() as usize) { + *c = word(i as u32); + } + } } image.texels[(y * width + x) as usize] = texel; } @@ -294,16 +398,16 @@ mod tests { } /// The buffer's bytes after one dispatch over `region` (`[x0, y0, width, height]`) of the - /// `extent` image of texels `words` words wide into `bytes` words, rows `row_words` apart - /// from `first_word`, in both invocation orders. + /// `extent` image read through `view` into `bytes` words, rows `row_words` apart from + /// `first_word`, in both invocation orders. fn copied_back( extent: [u32; 2], - words: u32, + view: ShadowTexelView, region: [u32; 4], (row_words, first_word): (u32, u32), bytes: &[u32], ) -> Vec { - let m = typed_module(words).expect("module"); + let m = typed_module(view).expect("module"); let [x0, y0, width, height] = region; let shape = ShadowCopyBackModule::shape([x0, y0], width, row_words, first_word); let mut out = Vec::new(); @@ -323,9 +427,9 @@ mod tests { workgroups: [gx, gy, 1], ..Config::default() }; - let images = vec![image(extent, words)]; + let images = vec![image(extent, view)]; let (outcome, images) = run_with_images(&m, &cfg, res, images).expect("run"); - assert_eq!(images[0], image(extent, words), "the view is only read"); + assert_eq!(images[0], image(extent, view), "the view is only read"); let words: Vec = outcome.buffers[0] .as_chunks::<4>() .0 @@ -340,10 +444,11 @@ mod tests { /// Every texel of a region lands at its row's place as its words, and every word between the /// rows, before the first texel and past the last keeps the buffer's own (a padded row's - /// bytes, and a scissor's outside): one, two and four words a texel, across workgroups. + /// bytes, and a scissor's outside): through every view, across workgroups. #[test] fn a_region_lands_at_its_rows_and_no_other_word_changes() { - for words in [1u32, 2, 4] { + for view in ShadowTexelView::ALL { + let words = view.words(); let extent = [90, 7]; // The region's rows 5 + 70 · words words apart, from word 3. let region = [10, 2, 70, 4]; @@ -351,7 +456,7 @@ mod tests { let first_word = 3; let len = (first_word + 4 * row_words + 2) as usize; let bytes: Vec = (0..len as u32).map(|i| 0xa5a5_0000 | i).collect(); - let got = copied_back(extent, words, region, (row_words, first_word), &bytes); + let got = copied_back(extent, view, region, (row_words, first_word), &bytes); let mut want = bytes.clone(); for y in 0..4 { for x in 0..70 { @@ -362,7 +467,7 @@ mod tests { } } } - assert_eq!(got, want, "{words} words a texel"); + assert_eq!(got, want, "{view:?}"); } } @@ -372,18 +477,20 @@ mod tests { let extent = [300, 260]; let region = [290, 257, 3, 2]; let bytes = vec![0u32; 8]; - let got = copied_back(extent, 1, region, (4, 1), &bytes); - let texel = |x: u32, y: u32| 0x0100_0000 + 0x1000 * y + x; - let want = vec![ - 0, - texel(290, 257), - texel(291, 257), - texel(292, 257), - 0, - texel(290, 258), - texel(291, 258), - texel(292, 258), - ]; - assert_eq!(got, want); + for view in [ShadowTexelView::R32Uint, ShadowTexelView::R8G8B8A8Uint] { + let got = copied_back(extent, view, region, (4, 1), &bytes); + let texel = |x: u32, y: u32| 0x0100_0000 + 0x1000 * y + x; + let want = vec![ + 0, + texel(290, 257), + texel(291, 257), + texel(292, 257), + 0, + texel(290, 258), + texel(291, 258), + texel(292, 258), + ]; + assert_eq!(got, want, "{view:?}"); + } } } diff --git a/crates/metal2vulkan/src/bind/shadow_copy_in.rs b/crates/metal2vulkan/src/bind/shadow_copy_in.rs new file mode 100644 index 000000000..646bf9194 --- /dev/null +++ b/crates/metal2vulkan/src/bind/shadow_copy_in.rs @@ -0,0 +1,438 @@ +//! A shadowed texture's texels copied in from its buffer's rows, and kept, by one compute +//! dispatch. +//! +//! A texture over a buffer whose rows the device cannot lay as Metal does lives in a shadow, an +//! optimally tiled image copied in from the buffer's bytes before a command and back after it +//! (`shadow_copy_back`). Where another writer may write the buffer's bytes while the command runs, +//! the shadow's texels are also *kept* after the copy in, in a scratch buffer laid out row after +//! row, so the copy back can merge only the words the command changed (`shadow_merge`). The copy +//! in is `vkCmdCopyBufferToImage` on every device and the keep a copy or a dispatch of +//! [`shadow_copy_back_module`](super::shadow_copy_back_module) after it. Where a device copies a +//! shadow back faster by a dispatch (a cost the runtime measures per device), a consumer may take +//! both with one dispatch of [`shadow_copy_in_module`] instead: it reads each texel's words from +//! the buffer once, stores them through an unsigned-integer storage view of the shadow, and +//! stores them in the kept part. The shadow holds the bytes the copy writes: Vulkan states that +//! "Views of compatible formats will have the same mapping between texel coordinates and memory +//! locations irrespective of the format, with only the interpretation of the bit pattern +//! changing" (`VkImageViewCreateInfo`), and an unsigned-integer view stores its components' bits +//! unconverted (an `R8G8B8A8_UINT` view's components a 4-byte texel's bytes in memory order, as +//! [`shadow_copy_back_module`](super::shadow_copy_back_module) reads them); the kept part holds +//! the same words, as the keep after the copy would store them. +//! +//! **The module** (one per view, [`ShadowTexelView`]). One `GLCompute` entry `main` with local +//! size ([`ShadowCopyInModule::LOCAL_SIZE`], 1, 1), [`ShadowCopyInModule::PUSH_BYTES`] of +//! `COMPUTE` push constants at offset 0 (the region's shape, [`ShadowCopyInModule::shape`]), and +//! in set 0: +//! +//! | Binding | Resource | +//! |---|---| +//! | [`ShadowCopyInModule::IMAGE_BINDING`] | the shadow's storage view of the module's format ([`ShadowTexelView`]), in the `GENERAL` layout | +//! | [`ShadowCopyInModule::BYTES_BINDING`] | a storage buffer over the buffer's bytes, a whole number of 4-byte words, only read | +//! | [`ShadowCopyInModule::KEPT_BINDING`] | a storage buffer over the kept part, from its first word | +//! +//! The shape's words, in order: `origin`, the region's first texel `x0` in its low 16 bits and +//! `y0` in its high 16; `width`, its texels a row; `row_words`, the buffer's rows apart in words; +//! and `first_word`, the word of the region's first texel in the bytes binding. Invocation +//! `(x, y)` with `x` below `width` reads the `n` words (`n` the module's texel width) at words +//! `first_word + y · row_words + x · n` onward, stores them as texel `(x0 + x, y0 + y)` of level 0 +//! (through an `R8G8B8A8_UINT` view, byte `i` its component `i`) and at words `(y · width + x) · n` +//! onward of the kept part; one at `x` past `width` does +//! nothing. A dispatch takes `ceil(width / LOCAL_SIZE)` by the region's height workgroups +//! ([`ShadowCopyInModule::groups`]). No texel outside the region and no kept word past its texels +//! is written, and nothing is written to the bytes. +//! +//! **Synchronization** (consumer): the bytes' last writes → `SHADER_STORAGE_READ` in +//! `COMPUTE_SHADER`, and the shadow's and the kept part's earlier accesses → +//! `SHADER_STORAGE_WRITE` there, before the dispatch; its writes → the shadow's and the kept part's +//! next uses. + +use std::sync::Arc; + +use super::shadow_copy_back::{stored_texel, ShadowTexelView}; +use super::shadow_merge::{u32_value, words_buffer}; +use crate::budget::{Budget, Meter}; +use crate::device::requirements::Requirements; +use crate::device::Device; +use crate::error::{Error, Feature, InternalError, InternalKind, Unsupported}; +use crate::pipeline::sym::{PushField, ResourceKind, ResourceSlot, Stage, Symbol}; +use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; +use crate::spirv::builder::ModuleBuilder; +use crate::spirv::error::BResult; +use crate::spirv::ir::{ + BinOp, Dim, ExecMode, ExecModel, ImageOperands, ImageType, ImageUsage, IoDir, MemAccess, + StorageClass, TexelMemory, Type, TypedModule, +}; + +/// The crate-owned copy-in module of one texel width on one device, validated like any output. +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ShadowCopyInModule { + /// SPIR-V 1.5 words, entry point `main`, bindings numbered as below in set 0. + pub spirv: Arc<[u32]>, + /// What the module needs from the device (within every Vulkan 1.2 device). + pub requirements: Requirements, +} + +impl ShadowCopyInModule { + /// Descriptor set of every binding. + pub const SET: u32 = 0; + /// The shadow's unsigned-integer view, a storage image the dispatch writes the texels into. + pub const IMAGE_BINDING: u32 = 0; + /// The buffer's bytes, a storage buffer the dispatch reads the texels' words from. + pub const BYTES_BINDING: u32 = 1; + /// The kept part, a storage buffer the dispatch writes the texels' words into, row after row. + pub const KEPT_BINDING: u32 = 2; + /// Invocations of one workgroup, along x: one texel each, of one row. + pub const LOCAL_SIZE: u32 = 64; + /// Bytes of the `COMPUTE` push-constant range at offset 0: the region's shape. + pub const PUSH_BYTES: u32 = 16; + + /// The push bytes of a region whose first texel is `[x0, y0]` (each below 65536), `width` + /// texels a row, whose rows lie `row_words` apart in the bytes binding from its word + /// `first_word` (the module docs). + pub fn shape([x0, y0]: [u32; 2], width: u32, row_words: u32, first_word: u32) -> [u8; 16] { + let words = [(x0 & 0xffff) | (y0 << 16), width, row_words, first_word]; + let mut bytes = [0; 16]; + for (chunk, word) in bytes.as_chunks_mut::<4>().0.iter_mut().zip(words) { + chunk.copy_from_slice(&word.to_le_bytes()); + } + bytes + } + + /// The workgroups of a dispatch over a region `[width, height]` texels. + pub fn groups([width, height]: [u32; 2]) -> [u32; 2] { + [width.div_ceil(Self::LOCAL_SIZE), height] + } +} + +/// The binding symbol of the shadow's view in the typed module. +const IMAGE: ResourceSlot = ResourceSlot { + stage: Stage::Kernel, + kind: ResourceKind::Texture, + index: 0, +}; +/// The binding symbol of the buffer's bytes in the typed module. +const BYTES: ResourceSlot = ResourceSlot { + stage: Stage::Kernel, + kind: ResourceKind::Buffer, + index: 0, +}; +/// The binding symbol of the kept part in the typed module. +const KEPT: ResourceSlot = ResourceSlot { + stage: Stage::Kernel, + kind: ResourceKind::Buffer, + index: 1, +}; + +/// The push field the shape is declared under: a crate-owned module's own words, which no +/// selection places. +const SHAPE: PushField = PushField::DispatchRegion; + +/// The copy-in module of `view` as a typed module, before +/// serialization: the module [`shadow_copy_in_module`] serializes, which the CPU interpreter runs. +/// Its bindings are the symbols `IMAGE`, `BYTES` and `KEPT`, and its push field the shape, a +/// `uvec4` (the module docs). +fn typed_module(view: ShadowTexelView) -> BResult { + let words = view.words(); + let mut b = ModuleBuilder::new(); + let u32_ = b.ty(Type::Int { + width: 32, + signed: false, + })?; + let uvec2 = b.ty(Type::Vector { elem: u32_, len: 2 })?; + let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?; + let uvec4 = b.ty(Type::Vector { elem: u32_, len: 4 })?; + let m_shape = b.push_member(SHAPE, uvec4, 0)?; + let push = b.push_global()?; + let image_type = b.ty(Type::Image(ImageType { + sampled_type: u32_, + dim: Dim::D2, + depth: false, + arrayed: false, + multisampled: false, + usage: ImageUsage::Storage, + format: view.storage_format(), + }))?; + let image = b.resource(IMAGE, StorageClass::UniformConstant, image_type)?; + let bytes = words_buffer(&mut b, BYTES, u32_)?; + let kept = words_buffer(&mut b, KEPT, u32_)?; + let invocation = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?; + let void = b.ty(Type::Void)?; + let mut f = b.function(void)?; + let zero = u32_value(&mut f, 0)?; + let low = u32_value(&mut f, 0xffff)?; + let sixteen = u32_value(&mut f, 16)?; + let n = u32_value(&mut f, words)?; + let mut lanes = Vec::with_capacity(words as usize); + for lane in 0..words { + lanes.push(u32_value(&mut f, lane)?); + } + let invocation = f.module().global_value(invocation)?; + let invocation = f.load(invocation, MemAccess::default())?; + let x = f.composite_extract(invocation, &[0])?; + let y = f.composite_extract(invocation, &[1])?; + let image = f.module().global_value(image)?; + let bytes = f.module().global_value(bytes)?; + let kept = f.module().global_value(kept)?; + let push = f.module().global_value(push)?; + let member = u32_value(&mut f, m_shape.index)?; + let shape = f.access_chain(push, &[member])?; + let shape = f.load(shape, MemAccess::default())?; + let origin = f.composite_extract(shape, &[0])?; + let width = f.composite_extract(shape, &[1])?; + let row_words = f.composite_extract(shape, &[2])?; + let first_word = f.composite_extract(shape, &[3])?; + let inside = f.binary(BinOp::ULessThan, x, width)?; + let copy: ArmFn<'_, ()> = Box::new(move |f, _| { + let row = f.binary(BinOp::IMul, y, row_words)?; + let column = f.binary(BinOp::IMul, x, n)?; + let at = f.binary(BinOp::IAdd, first_word, row)?; + let at = f.binary(BinOp::IAdd, at, column)?; + let kept_row = f.binary(BinOp::IMul, y, width)?; + let kept_texel = f.binary(BinOp::IAdd, kept_row, x)?; + let kept_at = f.binary(BinOp::IMul, kept_texel, n)?; + let mut texel = Vec::with_capacity(lanes.len()); + for &index in &lanes { + let place = f.binary(BinOp::IAdd, at, index)?; + let from = f.access_chain(bytes, &[zero, place])?; + let word = f.load(from, MemAccess::default())?; + let place = f.binary(BinOp::IAdd, kept_at, index)?; + let to = f.access_chain(kept, &[zero, place])?; + f.store(to, word, MemAccess::default())?; + texel.push(word); + } + let x0 = f.binary(BinOp::BitwiseAnd, origin, low)?; + let y0 = f.binary(BinOp::ShiftRightLogical, origin, sixteen)?; + let tx = f.binary(BinOp::IAdd, x0, x)?; + let ty = f.binary(BinOp::IAdd, y0, y)?; + let coord = f.composite_construct(uvec2, &[tx, ty])?; + let texel = stored_texel(f, uvec4, view, &texel)?; + let image = f.load(image, MemAccess::default())?; + f.write( + image, + coord, + texel, + &ImageOperands::default(), + TexelMemory::default(), + )?; + Ok(ArmEnd::FallThrough(Vec::new())) + }); + f.if_(&mut (), inside, copy, None)?; + f.ret(None)?; + let id = f.finish()?; + b.entry( + ExecModel::GLCompute, + id, + vec![ExecMode::LocalSize { + x: ShadowCopyInModule::LOCAL_SIZE, + y: 1, + z: 1, + }], + )?; + b.finalize() +} + +/// The fixed binding numbers of the module's symbols. +fn binding_of(sym: &Symbol) -> Option { + match sym { + Symbol::DescriptorSet(_) => Some(ShadowCopyInModule::SET), + Symbol::Binding(s) if *s == IMAGE => Some(ShadowCopyInModule::IMAGE_BINDING), + Symbol::Binding(s) if *s == BYTES => Some(ShadowCopyInModule::BYTES_BINDING), + Symbol::Binding(s) if *s == KEPT => Some(ShadowCopyInModule::KEPT_BINDING), + _ => None, + } +} + +/// The copy-in module of `device` storing texels through `view`: built with the typed builder, +/// checked by the owned verifier against the device's profile (requirements included), +/// serialized, and numbered with the fixed bindings of [`ShadowCopyInModule`]. Refused, +/// `Unsupported` (feature `Format`) naming what the device lacks, for the `R32G32_UINT` view +/// without `shaderStorageImageExtendedFormats` (its `Rg32ui`). +pub fn shadow_copy_in_module( + device: &Device, + view: ShadowTexelView, +) -> Result { + let profile = device.profile(); + let m = typed_module(view)?; + profile + .check(m.requirements()) + .map_err(|c| Error::Unsupported(Unsupported::needs(Feature::Format, c)))?; + let mut meter = Meter::new(&Budget::default()); + crate::spirv::verify::verify(&m, profile, &mut meter)?; + let r = crate::spirv::serialize::serialize(m)?; + profile.check(&r.requirements).map_err(|c| { + Error::Internal(InternalError::new( + InternalKind::RequirementsExceedProfile, + format!("the shadow copy in needs {c:?}"), + )) + })?; + let words = crate::spirv::serialize::relocate(&r, &binding_of)?; + Ok(ShadowCopyInModule { + spirv: words.into(), + requirements: r.requirements, + }) +} + +#[cfg(test)] +mod tests { + use super::{typed_module, ShadowCopyInModule, ShadowTexelView, BYTES, IMAGE, KEPT}; + use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Order, Resources}; + use crate::spirv::testing::{assert_valid, committed_profiles}; + + /// Valid on every committed profile that has what it needs: the `R32G32_UINT` kernel's + /// `Rg32ui` view needs extended storage image formats, which the Vulkan 1.2 floor lacks. + #[test] + fn the_copy_in_kernels_are_valid_on_every_committed_profile() { + for (_, p) in committed_profiles().expect("profiles") { + for view in ShadowTexelView::ALL { + let m = typed_module(view).expect("module"); + if view == ShadowTexelView::R32G32Uint && p.check(m.requirements()).is_err() { + continue; + } + assert_valid(m, &p); + } + } + } + + /// A `[width, height]` image, every component of every texel `fill`. + fn image([width, height]: [u32; 2], fill: u32) -> Image { + let mut image = Image::new(IMAGE, [width, height, 1], 1, 1, 1); + for texel in image.texels.iter_mut() { + *texel = [fill; 4]; + } + image + } + + /// The image and the kept part after one dispatch over `region` (`[x0, y0, width, height]`) + /// of the `extent` image stored through `view` from `bytes` words, rows `row_words` apart + /// from `first_word`, in both invocation orders; the bytes are checked unchanged. + fn copied_in( + extent: [u32; 2], + view: ShadowTexelView, + region: [u32; 4], + (row_words, first_word): (u32, u32), + bytes: &[u32], + kept_words: usize, + ) -> (Image, Vec) { + let m = typed_module(view).expect("module"); + let [x0, y0, width, height] = region; + let shape = ShadowCopyInModule::shape([x0, y0], width, row_words, first_word); + let to_bytes = + |words: &[u32]| -> Vec { words.iter().flat_map(|w| w.to_le_bytes()).collect() }; + let mut out = Vec::new(); + for order in [Order::Forward, Order::Reverse] { + let res = Resources { + buffers: vec![ + Buffer { + slot: Some(BYTES), + address: None, + bytes: to_bytes(bytes), + }, + Buffer { + slot: Some(KEPT), + address: None, + bytes: to_bytes(&vec![0xdead_beef; kept_words]), + }, + ], + push: shape.to_vec(), + spec: Default::default(), + }; + let [gx, gy] = ShadowCopyInModule::groups([width, height]); + let cfg = Config { + order, + workgroups: [gx, gy, 1], + ..Config::default() + }; + let (outcome, mut images) = + run_with_images(&m, &cfg, res, vec![image(extent, 7)]).expect("run"); + assert_eq!( + outcome.buffers[0], + to_bytes(bytes), + "the bytes are only read" + ); + let kept: Vec = outcome.buffers[1] + .as_chunks::<4>() + .0 + .iter() + .map(|b| u32::from_le_bytes(*b)) + .collect(); + out.push((images.swap_remove(0), kept)); + } + assert_eq!(out[0], out[1], "order independent"); + out.swap_remove(0) + } + + /// Every texel of a region is its row's words (through an `R8G8B8A8_UINT` view its bytes, one + /// a component), in the image and row after row in the kept part, and no texel outside it and + /// no kept word past its texels changes: through every view, across workgroups. + #[test] + fn a_region_lands_in_the_image_and_the_kept_part_alone() { + for view in ShadowTexelView::ALL { + let words = view.words(); + let extent = [90, 7]; + // The region's rows 5 + 70 · words words apart, from word 3. + let region = [10, 2, 70, 4]; + let row_words = 5 + 70 * words; + let first_word = 3; + let len = (first_word + 4 * row_words + 2) as usize; + let bytes: Vec = (0..len as u32).map(|i| 0xa5a5_0000 | i).collect(); + let kept_words = (70 * 4 * words + 3) as usize; + let (got, kept) = copied_in( + extent, + view, + region, + (row_words, first_word), + &bytes, + kept_words, + ); + let mut want = image(extent, 7); + let mut want_kept = vec![0xdead_beef; kept_words]; + for y in 0..4 { + for x in 0..70 { + let (tx, ty) = (10 + x, 2 + y); + let mut texel = [0, 0, 0, 0]; + for i in 0..words { + let word = bytes[(first_word + y * row_words + x * words + i) as usize]; + texel[i as usize] = word; + want_kept[((y * 70 + x) * words + i) as usize] = word; + } + if view == ShadowTexelView::R8G8B8A8Uint { + texel = texel[0].to_le_bytes().map(u32::from); + } + want.texels[(ty * extent[0] + tx) as usize] = texel; + } + } + assert_eq!(got, want, "{view:?}: the image"); + assert_eq!(kept, want_kept, "{view:?}: the kept part"); + } + } + + /// The origin's two halves: a texel past 255 in both coordinates is written at its place. + #[test] + fn the_origin_reaches_far_texels() { + let extent = [300, 260]; + let region = [290, 257, 3, 2]; + let bytes: Vec = (0..8).map(|i| 0x100 + i).collect(); + for view in [ShadowTexelView::R32Uint, ShadowTexelView::R8G8B8A8Uint] { + let (got, kept) = copied_in(extent, view, region, (4, 1), &bytes, 6); + let at = |x: u32, y: u32| { + let texel = got.texels[(y * extent[0] + x) as usize]; + match view { + ShadowTexelView::R8G8B8A8Uint => u32::from_le_bytes(texel.map(|b| b as u8)), + _ => texel[0], + } + }; + assert_eq!( + [at(290, 257), at(291, 257), at(292, 257)], + [0x101, 0x102, 0x103], + "{view:?}" + ); + assert_eq!( + [at(290, 258), at(291, 258), at(292, 258)], + [0x105, 0x106, 0x107], + "{view:?}" + ); + assert_eq!(kept, vec![0x101, 0x102, 0x103, 0x105, 0x106, 0x107]); + } + } +} diff --git a/crates/metal2vulkan/src/bind/shadow_merge.rs b/crates/metal2vulkan/src/bind/shadow_merge.rs index 69e86b8a2..0b6936d6b 100644 --- a/crates/metal2vulkan/src/bind/shadow_merge.rs +++ b/crates/metal2vulkan/src/bind/shadow_merge.rs @@ -118,7 +118,11 @@ const CURRENT: ResourceSlot = ResourceSlot { }; /// A `Block { u32 words[]; }` storage buffer bound at `sym`. -fn words_buffer(b: &mut ModuleBuilder, sym: ResourceSlot, u32_: TypeId) -> BResult { +pub(super) fn words_buffer( + b: &mut ModuleBuilder, + sym: ResourceSlot, + u32_: TypeId, +) -> BResult { let rta = b.ty(Type::RuntimeArray { elem: u32_, stride: Some(4), @@ -131,7 +135,7 @@ fn words_buffer(b: &mut ModuleBuilder, sym: ResourceSlot, u32_: TypeId) -> BResu b.resource(sym, StorageClass::StorageBuffer, block) } -fn u32_value(f: &mut FunctionBuilder<'_>, v: u32) -> BResult { +pub(super) fn u32_value(f: &mut FunctionBuilder<'_>, v: u32) -> BResult { let c = f.u32_const(v)?; f.module().const_value(c) } @@ -161,11 +165,6 @@ fn typed_module() -> BResult { let void = b.ty(Type::Void)?; let mut f = b.function(void)?; let zero = u32_value(&mut f, 0)?; - let all = u32_value(&mut f, u32::MAX)?; - let mut lanes = Vec::with_capacity(4); - for byte in 0..4 { - lanes.push(u32_value(&mut f, 0xff << (8 * byte))?); - } let invocation = f.module().global_value(invocation)?; let invocation = f.load(invocation, MemAccess::default())?; let i = f.composite_extract(invocation, &[0])?; @@ -196,20 +195,7 @@ fn typed_module() -> BResult { let word = f.binary(BinOp::IAdd, first_word, row)?; let word = f.binary(BinOp::IAdd, word, x)?; let at = f.access_chain(current, &[zero, word])?; - let now = f.load(at, MemAccess::default())?; - // The bytes that differ, each 0xff in the mask. - let mut mask = zero; - for &lane in &lanes { - let bits = f.binary(BinOp::BitwiseAnd, differ, lane)?; - let moved = f.binary(BinOp::INotEqual, bits, zero)?; - let taken = f.select(moved, lane, zero)?; - mask = f.binary(BinOp::BitwiseOr, mask, taken)?; - } - let others = f.binary(BinOp::BitwiseXor, mask, all)?; - let left = f.binary(BinOp::BitwiseAnd, now, others)?; - let taken = f.binary(BinOp::BitwiseAnd, after, mask)?; - let merged = f.binary(BinOp::BitwiseOr, left, taken)?; - f.store(at, merged, MemAccess::default())?; + merge_word(f, at, after, differ)?; Ok(ArmEnd::FallThrough(Vec::new())) }); f.if_(&mut (), moved, write, None)?; @@ -230,6 +216,35 @@ fn typed_module() -> BResult { b.finalize() } +/// Merge into the current word at `at` the changed word `after`, `differ` its xor with the kept +/// word (not zero): each byte where they differ becomes `after`'s, and the others keep the +/// current word's (the module docs). +pub(super) fn merge_word( + f: &mut FunctionBuilder<'_>, + at: Value, + after: Value, + differ: Value, +) -> BResult<()> { + let zero = u32_value(f, 0)?; + let all = u32_value(f, u32::MAX)?; + let now = f.load(at, MemAccess::default())?; + // The bytes that differ, each 0xff in the mask. + let mut mask = zero; + for byte in 0..4 { + let lane = u32_value(f, 0xff << (8 * byte))?; + let bits = f.binary(BinOp::BitwiseAnd, differ, lane)?; + let moved = f.binary(BinOp::INotEqual, bits, zero)?; + let taken = f.select(moved, lane, zero)?; + mask = f.binary(BinOp::BitwiseOr, mask, taken)?; + } + let others = f.binary(BinOp::BitwiseXor, mask, all)?; + let left = f.binary(BinOp::BitwiseAnd, now, others)?; + let taken = f.binary(BinOp::BitwiseAnd, after, mask)?; + let merged = f.binary(BinOp::BitwiseOr, left, taken)?; + f.store(at, merged, MemAccess::default())?; + Ok(()) +} + /// The fixed binding numbers of the module's symbols. fn binding_of(sym: &Symbol) -> Option { match sym { diff --git a/crates/metal2vulkan/src/bind/shadow_merge_image.rs b/crates/metal2vulkan/src/bind/shadow_merge_image.rs new file mode 100644 index 000000000..37d79881a --- /dev/null +++ b/crates/metal2vulkan/src/bind/shadow_merge_image.rs @@ -0,0 +1,384 @@ +//! The merge of a shadowed texture's writes into its buffer's bytes, reading the shadow itself. +//! +//! [`shadow_merge_module`](super::shadow_merge_module) compares a texture's texels kept before a +//! command with the same texels copied out of its shadow after it. Where the shadow has an +//! unsigned-integer view of its texel's width, [`shadow_merge_image_module`] reads the texels +//! after the command through that view instead, so no copy of them is made: Vulkan states that +//! "Views of compatible formats will have the same mapping between texel coordinates and memory +//! locations irrespective of the format, with only the interpretation of the bit pattern +//! changing" (`VkImageViewCreateInfo`), and an unsigned-integer view returns its components' bits +//! unconverted, so the words a fetch returns are the words a copy of the texel writes (a 4-byte +//! texel's `R8G8B8A8_UINT` bytes packed into its word, as +//! [`shadow_copy_back_module`](super::shadow_copy_back_module) packs them). +//! +//! **The module** (one per view, [`ShadowTexelView`]). One `GLCompute` entry `main` with local +//! size ([`ShadowMergeImageModule::LOCAL_SIZE`], 1, 1), [`ShadowMergeImageModule::PUSH_BYTES`] of +//! `COMPUTE` push constants at offset 0 (the region's shape, [`ShadowMergeImageModule::shape`]), +//! and in set 0: +//! +//! | Binding | Resource | +//! |---|---| +//! | [`ShadowMergeImageModule::IMAGE_BINDING`] | the shadow's sampled view of the module's format ([`ShadowTexelView`]), in the `GENERAL` layout | +//! | [`ShadowMergeImageModule::KEPT_BINDING`] | the region's texels before the command, row after row, a storage buffer | +//! | [`ShadowMergeImageModule::CURRENT_BINDING`] | the bytes the region lies in, a storage buffer merged in place | +//! +//! The shape's words, in order: `origin`, the region's first texel `x0` in its low 16 bits and +//! `y0` in its high 16; `width`, its texels a row; `row_words`, the current buffer's rows apart in +//! words; and `first_word`, the word of the region's first texel in the current binding. +//! Invocation `(x, y)` with `x` below `width` fetches texel `(x0 + x, y0 + y)` of level 0 and, for +//! each of its `n` words `k` (`n` the module's texel width), compares it with word +//! `(y · width + x) · n + k` of the kept buffer; where they differ, word +//! `first_word + y · row_words + x · n + k` of the current buffer takes, in each byte where they +//! differ, the fetched word's byte, and keeps its own in the others. Where they are equal it reads +//! and writes nothing of the current buffer; one at `x` past `width` does nothing. A dispatch takes +//! `ceil(width / LOCAL_SIZE)` by the region's height workgroups +//! ([`ShadowMergeImageModule::groups`]). No word between the region's rows or past its texels is +//! read or written. +//! +//! **Synchronization** (consumer): the shadow's last writes → `SHADER_SAMPLED_READ` in + +use std::sync::Arc; + +use super::shadow_copy_back::{fetched_words, ShadowTexelView}; +use super::shadow_merge::{merge_word, u32_value, words_buffer}; +use crate::budget::{Budget, Meter}; +use crate::device::requirements::Requirements; +use crate::device::Device; +use crate::error::{Error, InternalError, InternalKind}; +use crate::pipeline::sym::{PushField, ResourceKind, ResourceSlot, Stage, Symbol}; +use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; +use crate::spirv::builder::ModuleBuilder; +use crate::spirv::error::BResult; +use crate::spirv::ir::{ + BinOp, Dim, ExecMode, ExecModel, ImageOperands, ImageType, ImageUsage, IoDir, MemAccess, + StorageClass, Type, TypedModule, +}; + +/// The crate-owned image-reading merge module of one texel width on one device, validated like +/// any output. +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ShadowMergeImageModule { + /// SPIR-V 1.5 words, entry point `main`, bindings numbered as below in set 0. + pub spirv: Arc<[u32]>, + /// What the module needs from the device (within every Vulkan 1.2 device). + pub requirements: Requirements, +} + +impl ShadowMergeImageModule { + /// Descriptor set of every binding. + pub const SET: u32 = 0; + /// The shadow's unsigned-integer view, a sampled image. + pub const IMAGE_BINDING: u32 = 0; + pub const KEPT_BINDING: u32 = 1; + /// The buffer's bytes after the command, a storage buffer the dispatch merges into. + pub const CURRENT_BINDING: u32 = 2; + /// Invocations of one workgroup, along x: one texel each, of one row. + pub const LOCAL_SIZE: u32 = 64; + /// Bytes of the `COMPUTE` push-constant range at offset 0: the region's shape. + pub const PUSH_BYTES: u32 = 16; + + /// The push bytes of a region whose first texel is `[x0, y0]` (each below 65536), `width` + /// texels a row, whose rows lie `row_words` apart in the current binding from its word + /// `first_word` (the module docs). + pub fn shape([x0, y0]: [u32; 2], width: u32, row_words: u32, first_word: u32) -> [u8; 16] { + let words = [(x0 & 0xffff) | (y0 << 16), width, row_words, first_word]; + let mut bytes = [0; 16]; + for (chunk, word) in bytes.as_chunks_mut::<4>().0.iter_mut().zip(words) { + chunk.copy_from_slice(&word.to_le_bytes()); + } + bytes + } + + /// The workgroups of a dispatch over a region `[width, height]` texels. + pub fn groups([width, height]: [u32; 2]) -> [u32; 2] { + [width.div_ceil(Self::LOCAL_SIZE), height] + } +} + +/// The binding symbol of the shadow's view in the typed module. +const IMAGE: ResourceSlot = ResourceSlot { + stage: Stage::Kernel, + kind: ResourceKind::Texture, + index: 0, +}; +/// The binding symbol of the kept buffer in the typed module. +const KEPT: ResourceSlot = ResourceSlot { + stage: Stage::Kernel, + kind: ResourceKind::Buffer, + index: 0, +}; +/// The binding symbol of the current buffer in the typed module. +const CURRENT: ResourceSlot = ResourceSlot { + stage: Stage::Kernel, + kind: ResourceKind::Buffer, + index: 1, +}; + +/// The push field the shape is declared under: a crate-owned module's own words, which no +/// selection places. +const SHAPE: PushField = PushField::DispatchRegion; + + let words = view.words(); + let mut b = ModuleBuilder::new(); + let u32_ = b.ty(Type::Int { + width: 32, + signed: false, + })?; + let uvec2 = b.ty(Type::Vector { elem: u32_, len: 2 })?; + let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?; + let uvec4 = b.ty(Type::Vector { elem: u32_, len: 4 })?; + let m_shape = b.push_member(SHAPE, uvec4, 0)?; + let push = b.push_global()?; + let image_type = b.ty(Type::Image(ImageType { + sampled_type: u32_, + dim: Dim::D2, + depth: false, + arrayed: false, + multisampled: false, + usage: ImageUsage::Sampled, + format: crate::spv::ImageFormat::Unknown, + }))?; + let image = b.resource(IMAGE, StorageClass::UniformConstant, image_type)?; + let current = words_buffer(&mut b, CURRENT, u32_)?; + let invocation = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?; + let void = b.ty(Type::Void)?; + let mut f = b.function(void)?; + let zero = u32_value(&mut f, 0)?; + let low = u32_value(&mut f, 0xffff)?; + let sixteen = u32_value(&mut f, 16)?; + let n = u32_value(&mut f, words)?; + let mut lanes = Vec::with_capacity(words as usize); + for lane in 0..words { + lanes.push(u32_value(&mut f, lane)?); + } + let invocation = f.module().global_value(invocation)?; + let invocation = f.load(invocation, MemAccess::default())?; + let x = f.composite_extract(invocation, &[0])?; + let y = f.composite_extract(invocation, &[1])?; + let image = f.module().global_value(image)?; + let current = f.module().global_value(current)?; + let push = f.module().global_value(push)?; + let member = u32_value(&mut f, m_shape.index)?; + let shape = f.access_chain(push, &[member])?; + let shape = f.load(shape, MemAccess::default())?; + let origin = f.composite_extract(shape, &[0])?; + let width = f.composite_extract(shape, &[1])?; + let row_words = f.composite_extract(shape, &[2])?; + let first_word = f.composite_extract(shape, &[3])?; + let inside = f.binary(BinOp::ULessThan, x, width)?; + let merge: ArmFn<'_, ()> = Box::new(move |f, _| { + let x0 = f.binary(BinOp::BitwiseAnd, origin, low)?; + let y0 = f.binary(BinOp::ShiftRightLogical, origin, sixteen)?; + let tx = f.binary(BinOp::IAdd, x0, x)?; + let ty = f.binary(BinOp::IAdd, y0, y)?; + let coord = f.composite_construct(uvec2, &[tx, ty])?; + let image = f.load(image, MemAccess::default())?; + let ops = ImageOperands { + lod: Some(zero), + ..ImageOperands::default() + }; + let texel = f.fetch(image, coord, &ops)?; + let texel = fetched_words(f, texel, view)?; + let row = f.binary(BinOp::IMul, y, row_words)?; + let column = f.binary(BinOp::IMul, x, n)?; + let at = f.binary(BinOp::IAdd, first_word, row)?; + let at = f.binary(BinOp::IAdd, at, column)?; + let differ = f.binary(BinOp::BitwiseXor, before, after)?; + let moved = f.binary(BinOp::INotEqual, differ, zero)?; + // A word the command left as it was is neither read nor written. + let write: ArmFn<'_, ()> = Box::new(move |f, _| { + let place = f.binary(BinOp::IAdd, at, index)?; + let to = f.access_chain(current, &[zero, place])?; + merge_word(f, to, after, differ)?; + Ok(ArmEnd::FallThrough(Vec::new())) + }); + f.if_(&mut (), moved, write, None)?; + } + Ok(ArmEnd::FallThrough(Vec::new())) + }); + f.if_(&mut (), inside, merge, None)?; + f.ret(None)?; + let id = f.finish()?; + b.entry( + ExecModel::GLCompute, + id, + vec![ExecMode::LocalSize { + x: ShadowMergeImageModule::LOCAL_SIZE, + y: 1, + z: 1, + }], + )?; + b.finalize() +} + +/// The fixed binding numbers of the module's symbols. +fn binding_of(sym: &Symbol) -> Option { + match sym { + Symbol::DescriptorSet(_) => Some(ShadowMergeImageModule::SET), + Symbol::Binding(s) if *s == IMAGE => Some(ShadowMergeImageModule::IMAGE_BINDING), + Symbol::Binding(s) if *s == CURRENT => Some(ShadowMergeImageModule::CURRENT_BINDING), + _ => None, + } +} + +/// The image-reading merge module of `device` reading texels through `view`: built with the typed +/// builder, checked by the owned verifier against the device's profile (requirements included), +/// serialized, and numbered with the fixed bindings of [`ShadowMergeImageModule`]. +pub fn shadow_merge_image_module( + device: &Device, + view: ShadowTexelView, +) -> Result { + let profile = device.profile(); + let mut meter = Meter::new(&Budget::default()); + crate::spirv::verify::verify(&m, profile, &mut meter)?; + let r = crate::spirv::serialize::serialize(m)?; + profile.check(&r.requirements).map_err(|c| { + Error::Internal(InternalError::new( + InternalKind::RequirementsExceedProfile, + format!("the image-reading shadow merge needs {c:?}"), + )) + })?; + let words = crate::spirv::serialize::relocate(&r, &binding_of)?; + Ok(ShadowMergeImageModule { + spirv: words.into(), + requirements: r.requirements, + }) +} + +#[cfg(test)] +mod tests { + use crate::spirv::interp::{run_with_images, Buffer, Config, Image, Order, Resources}; + use crate::spirv::testing::{assert_valid, committed_profiles}; + + #[test] + fn the_image_merge_kernels_are_valid_on_every_committed_profile() { + for (_, p) in committed_profiles().expect("profiles") { + for view in ShadowTexelView::ALL { + } + } + } + + /// Texel `(x, y)`'s word `i` of the image the tests read: `0x0100_0000 · (i + 1) + + /// 0x1000 · y + x`. + fn texel_word(x: u32, y: u32, i: u32) -> u32 { + 0x0100_0000 * (i + 1) + 0x1000 * y + x + } + + for y in 0..height { + for x in 0..width { + let mut texel = [0, 0, 0, 1]; + match view { + ShadowTexelView::R8G8B8A8Uint => { + } + _ => { + for (i, c) in texel.iter_mut().enumerate().take(view.words() as usize) { + } + } + } + image.texels[(y * width + x) as usize] = texel; + } + } + image + } + + fn bytes_of(words: &[u32]) -> Vec { + words.iter().flat_map(|w| w.to_le_bytes()).collect() + } + + fn words_of(bytes: &[u8]) -> Vec { + bytes + .as_chunks::<4>() + .0 + .iter() + .map(|b| u32::from_le_bytes(*b)) + .collect() + } + + /// The current buffer's words after one dispatch over `region` (`[x0, y0, width, height]`) of + fn merged( + extent: [u32; 2], + region: [u32; 4], + kept: &[u32], + (row_words, first_word): (u32, u32), + current: &[u32], + ) -> Vec { + let [x0, y0, width, height] = region; + let shape = ShadowMergeImageModule::shape([x0, y0], width, row_words, first_word); + let mut out = Vec::new(); + for order in [Order::Forward, Order::Reverse] { + let buffer = |slot, words: &[u32]| Buffer { + slot: Some(slot), + address: None, + bytes: bytes_of(words), + }; + let res = Resources { + push: shape.to_vec(), + spec: Default::default(), + }; + let [gx, gy] = ShadowMergeImageModule::groups([width, height]); + let cfg = Config { + order, + workgroups: [gx, gy, 1], + ..Config::default() + }; + let (outcome, images) = run_with_images(&m, &cfg, res, images).expect("run"); + assert_eq!(images[0], image(extent, view), "the view is only read"); + } + assert_eq!(out[0], out[1], "order independent"); + out.swap_remove(0) + } + + /// Each byte the texture changed since the keep lands at its row's place; a word whose kept + /// and fetched words are equal keeps the current buffer's (another writer's write there + /// stays); a word with one byte changed takes that byte alone; and no word between the rows, + #[test] + fn the_bytes_the_texture_changed_merge_at_their_rows_alone() { + let words = view.words(); + let extent = [90, 7]; + let region = [10, 2, 70, 4]; + let [x0, y0, width, height] = region; + let row_words = 5 + width * words; + let first_word = 3; + let len = (first_word + height * row_words + 2) as usize; + let current: Vec = (0..len as u32).map(|i| 0xa5a5_0000 | i).collect(); + // Kept: the fetched words, but word 0 of texel (x, y) where (x + y) % 3 == 0, whose + // low byte alone differs, and every word of texel (x, y) where (x + y) % 3 == 1, + // which differs in every byte. + let mut kept = Vec::new(); + for y in 0..height { + for x in 0..width { + for i in 0..words { + let word = texel_word(x0 + x, y0 + y, i); + kept.push(match (x + y) % 3 { + 0 if i == 0 => word ^ 0xff, + 1 => !word, + _ => word, + }); + } + } + } + let got = merged( + extent, + region, + &kept, + (row_words, first_word), + ¤t, + ); + let mut want = current.clone(); + for y in 0..height { + for x in 0..width { + for i in 0..words { + let at = (first_word + y * row_words + x * words + i) as usize; + let word = texel_word(x0 + x, y0 + y, i); + want[at] = match (x + y) % 3 { + 0 if i == 0 => (current[at] & !0xff) | (word & 0xff), + 1 => word, + _ => current[at], + }; + } + } + } + } + } +} diff --git a/crates/metal2vulkan/src/device/driver_facts.rs b/crates/metal2vulkan/src/device/driver_facts.rs index 6dfd2e275..926b055a3 100644 --- a/crates/metal2vulkan/src/device/driver_facts.rs +++ b/crates/metal2vulkan/src/device/driver_facts.rs @@ -1322,13 +1322,44 @@ pub enum DriverFact { /// 1307x512 `BGRA8Unorm` tile over guest pages with rows of 5248 bytes, 60 frames, three rounds /// within 3 us of each other): a pass that loads, draws and stores took 1319 us of GPU time with /// the copy back and 972 us with the dispatch, one half-scissored 742 and 575 us, and one that - /// stores nothing (the mutable shadow's cost alone) 500 and 513 us. On a driver with it a shadowed - /// texture's copy back is such a dispatch (`shadow_copy_back.rs` in the runtime), its shadow made - /// `MUTABLE_FORMAT` with that view: the same bytes either way, as Vulkan states a compatible view - /// reads a texel's bits unchanged. Measured no faster, so not listed: RADV, Mesa 26.2.4 on the - /// Radeon 780M (whose passes over a mutable shadow took 84 to 150 us longer a frame), and NVIDIA's + /// stores nothing (the mutable shadow's cost alone) 500 and 513 us. On the UHD 770 of RPL-S (a + /// pass a frame over a 1920x1080 `BGRA8Unorm` shadow over anonymous pages, six rounds, GPU time + /// the rounds' median), a pass that loads, draws and stores took 1.68 ms with the dispatches + /// against 1.81 ms with the copies, one that clears 1.04 against 1.14 ms, and one drawn in a + /// centred region of half the width and height 446 against 476 us. The driver's copy cost, so + /// the row names no GPU: it holds on each measured identity of ANV at the release. On a driver + /// with it a shadowed texture's copy back is such a dispatch (`shadow_copy_back.rs` in the + /// runtime), and so is a merge's copy of the shadow into its scratch before the commands + /// (`shadow_merge.rs`), its shadow made `MUTABLE_FORMAT` with that view, through which the + /// merge reads the texels the commands left: the same bytes either way, as Vulkan states a + /// compatible view reads a texel's bits unchanged. Measured no faster, so not listed: RADV, + /// Mesa 26.2.4 on the Radeon 780M (whose passes over a mutable shadow took 84 to 150 us longer + /// a frame) and 26.0.8 on the Radeon 780M and the Radeon RX 7900 XTX (where a merge reading a + /// mutable shadow's texels through the view in place of a copy of them saved 6% and 2% of a + /// 1920x1080 pass that loads, and a pass that clears took 75% and 0% more), and NVIDIA's /// 615.71.09 on the RTX 5080 Laptop GPU. ShadowCopyBackDispatchFaster, + /// A cost fact (the module docs), on a driver with [`DriverFact::ShadowCopyBackDispatchFaster`]: + /// the GPU runs a merged shadowed texture's copy in (`vkCmdCopyBufferToImage`) and its keep (the + /// copy back's dispatch into the merge's scratch) slower than one dispatch that reads the + /// texels' words from the buffer once and stores them in the shadow, through a storage view of + /// it, and in the scratch, with the shadow's 4-byte texels viewed as `R8G8B8A8_UINT` (whose + /// storage usage keeps the image compressed on ANV, where `R32_UINT` beside storage usage makes + /// gfx12.0 drop its aux surface). Measured on ANV, Mesa 26.2.4 (one pass a frame, or twelve in + /// one command buffer, over a 1920x1080 `BGRA8Unorm` shadow over anonymous pages, 1000 frames, + /// GPU time a frame, two rounds each): on the UHD 770 of RPL-S, a pass that loads, draws and + /// stores took 1427 us against 1643 to 1665 us with the copy back's fact alone, twelve such + /// passes 17.2 ms against 20.0 ms, and one that clears 891 against 1042 us. On the Iris Xe of + /// RPL-P it was measured no faster, so not listed: twelve such passes took 9.3 to 15.8 ms + /// against 9.3 to 15.3 ms with the copy back's fact alone, slower in six of seven alternating + /// rounds (median 5% more), one pass 3.05 against 3.48 ms, one that clears 0.40 to 1.29 + /// against 0.61 to 1.20 ms; and the `R8G8B8A8_UINT` view without the dispatch took longer + /// still there (twelve passes 10.0 to 13.3 ms, a clearing pass 0.89 to 1.67 ms). On a device + /// with it a merged texture's copy in and keep of the same rectangle are that dispatch + /// (`shadow_copy_in.rs` in the runtime), and its shadow's view also stores (`shadow_copy_back.rs` + /// in the runtime): the same bytes either way, as Vulkan states a compatible view reads and + /// stores a texel's bits unchanged. + ShadowCopyInDispatchFaster, /// The driver answers a format's linear-tiling attachment features from memory it has not /// yet initialized, so they differ between instances of one process: MoltenVK 1.4.1 builds /// its format table in `MVKPhysicalDevice`'s member initializers, where @@ -2323,6 +2354,18 @@ pub(crate) const MEASURED: &[Measured] = &[ fact: DriverFact::ShadowCopyBackDispatchFaster, driver: DriverId::INTEL_OPEN_SOURCE_MESA, vendor: Some(INTEL_VENDOR_ID), + device: None, + first: mesa(26, 2, 4), + last: mesa(26, 2, 4), + }, + Measured { + fact: DriverFact::ShadowCopyInDispatchFaster, + driver: DriverId::INTEL_OPEN_SOURCE_MESA, + vendor: Some(INTEL_VENDOR_ID), + device: Some(INTEL_UHD_770_RPL_S), + first: mesa(26, 2, 4), + last: mesa(26, 2, 4), + }, Measured { fact: DriverFact::SampledDepthKeepsHiZ, driver: DriverId::INTEL_OPEN_SOURCE_MESA, diff --git a/crates/metal2vulkan/src/device/tests/driver_facts.rs b/crates/metal2vulkan/src/device/tests/driver_facts.rs index 6b7758960..d79692f48 100644 --- a/crates/metal2vulkan/src/device/tests/driver_facts.rs +++ b/crates/metal2vulkan/src/device/tests/driver_facts.rs @@ -527,6 +527,7 @@ const BC7: DriverFact = DriverFact::Bc7BlockDecodeIsMetals; const SCARCE_POOLS: DriverFact = DriverFact::TimestampPoolsAreCounterSampleBuffers; const ONE_OF_METALS: DriverFact = DriverFact::DontCareStoreIsOneOfMetals; const COPY_BACK: DriverFact = DriverFact::ShadowCopyBackDispatchFaster; +const COPY_IN: DriverFact = DriverFact::ShadowCopyInDispatchFaster; const LINEAR_UNINITIALIZED: DriverFact = DriverFact::LinearTilingFeaturesUninitialized; const STALL: DriverFact = DriverFact::SemaphoreOperationsStallSubmits; const SAMPLED_HIZ: DriverFact = DriverFact::SampledDepthKeepsHiZ; @@ -552,6 +553,8 @@ const TILE_STORE: DriverFact = DriverFact::TileStoreIsMetals; /// first sparse resource waits for every queue; BC6H decodes as Metal's on the 780M, the RPL-P, /// lavapipe 26.0.8, both MoltenVK GPUs and the RTX 5080 Laptop GPU, and BC7 on the same but /// lavapipe; `DONT_CARE` keeps one of Metal's two answers on the 780M, the RPL-S and the RPL-P; a +/// shadow's copy back runs faster as a dispatch on the RPL-S and the RPL-P, and a merged shadow's +/// copy in with its keep on the RPL-S alone, and a copy of rows /// linear-tiling attachment features uninitialized; NVIDIA's stalls a submission per thousand /// profile is an unmeasured identity and takes its driver's defects alone: the GTX 1060 /// (580.178.04) and the RTX 5080 desktop GPU (another GPU at 615.71.09) NVIDIA's custom-position @@ -607,7 +610,8 @@ fn the_committed_profiles_drivers_have_their_facts() { ), ( "intel-uhd770-rpls-anv", - vec![ZERO, HIDE, HOST, FETCH, WHOLE, SPARSE_WAIT, ONE_OF_METALS], + COPY_BACK, + COPY_IN, ), ( "moltenvk-m3", diff --git a/crates/metal2vulkan/src/tests/owned_divisions.rs b/crates/metal2vulkan/src/tests/owned_divisions.rs index 9162e181b..efafa99bd 100644 --- a/crates/metal2vulkan/src/tests/owned_divisions.rs +++ b/crates/metal2vulkan/src/tests/owned_divisions.rs @@ -144,7 +144,19 @@ fn modules() -> Vec { ); } } - for words in [1, 2, 4] { + for view in bind::ShadowTexelView::ALL { + push( + format!("shadow_copy_back_module({view:?})"), + Box::new(move |d| Ok(bind::shadow_copy_back_module(d, view)?.spirv)), + ); + push( + format!("shadow_copy_in_module({view:?})"), + Box::new(move |d| Ok(bind::shadow_copy_in_module(d, view)?.spirv)), + ); + push( + format!("shadow_merge_image_module({view:?})"), + Box::new(move |d| Ok(bind::shadow_merge_image_module(d, view)?.spirv)), + ); push( format!("shadow_copy_back_module({words})"), Box::new(move |d| Ok(bind::shadow_copy_back_module(d, words)?.spirv)), diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index 4bcbad38c..324c48c12 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -611,8 +611,13 @@ surface! { struct VisibilityResolveModule N; fn shadow_copy_back_module; struct ShadowCopyBackModule N; + enum ShadowTexelView E; + fn shadow_copy_in_module; + struct ShadowCopyInModule N; fn shadow_merge_module; struct ShadowMergeModule N; + fn shadow_merge_image_module; + struct ShadowMergeImageModule N; fn depth_magnitude_module; struct DepthMagnitudeModule N; fn unused_bits_module; diff --git a/docs/API.md b/docs/API.md index da53b4276..755be8ba8 100644 --- a/docs/API.md +++ b/docs/API.md @@ -973,20 +973,33 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. it). Cost: its texels are copied into an image before each use and back after each write; a render pass that loads it as an attachment, takes it in no other way and draws under scissors copies in - and back only the texels inside them (`WorkCounts::shadow_texels_copied_in`, - `shadow_texels_copied_back`). Where the device is measured to run it faster so - (`DriverFact::ShadowCopyBackDispatchFaster`), a copy back of a one-slice texture of 4-, 8- or - 16-byte texels is a compute dispatch that stores the same bytes - (`WorkCounts::shadow_copies_back_dispatched`). + only the texels inside them (`WorkCounts::shadow_texels_copied_in`). Over a buffer's bytes that + another writer may write while a command buffer runs, the image is kept in a scratch buffer + before the first command that writes through it, and each copy back is a dispatch that merges + only the words the commands changed, so that writer's writes to the texels they left stay, as on + Metal: the CPU's, over a `Shared` or `Managed` buffer's bytes, host pages or the caller's + `VkBuffer`, and another queue's commands', over an untracked buffer's. A tracked `Private` + buffer's bytes have no such writer (the runtime orders another queue's commands that touch them + before or after the command buffer, as Metal does), and are copied back + (`shadow_texels_copied_back`), as a command that replaces every texel is. The scratch keeps the + rectangle the commands write in, where they bound it and the copies are cut so + (`WorkCounts::shadow_texels_kept`). + Where the device is measured to run it faster so (`DriverFact::ShadowCopyBackDispatchFaster`), a + copy back of a one-slice texture of 4-, 8- or 16-byte texels is a compute dispatch that stores + the same bytes (`WorkCounts::shadow_copies_back_dispatched`), and so is a merge's copy of such a + texture's image into its scratch buffer before the commands + (`WorkCounts::shadow_merge_copies_dispatched`), which on a device measured faster so + (`DriverFact::ShadowCopyInDispatchFaster`) also takes the copy in of the same texels before it, + storing them in the image through that view (`WorkCounts::shadow_copies_in_dispatched`); after + them, a cut merge reads the texels the commands left from the image itself, through an - `metal2vulkan-degrade-staged-texture-buffer` (performance). `StagedTextureBuffer`: A texture buffer is viewed through a staging buffer: its texels start where the device views none (`minTexelBufferOffsetAlignment`). Cost: its texels are copied into a staging buffer before each use and back after each write. - `metal2vulkan-degrade-shadow-merge` (performance). `ShadowMerge`: One command writes a buffer's bytes through a shadowed texture or a staged texture buffer and also another way. Cost: the - shadow's texels are kept in a scratch buffer of three times the texture's bytes before the - command, and after it a dispatch merges the bytes it changed through the texture into the - buffer's: three copies and a dispatch in place of one copy back. + buffer's, in place where the texture's bytes start and end in whole words of the buffer: one to + three copies and a dispatch in place of one copy back. - `metal2vulkan-degrade-copied-draw-bytes` (performance). `CopiedDrawBytes`: A draw's index buffer or indirect arguments start where Vulkan reads neither. Cost: they are copied into a buffer of the command buffer before the pass, and the draw reads the copy. diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 9fdeb4727..52853b31f 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -169,10 +169,30 @@ recorded here. texture keeps, the buffer's texels copied in first (`dont-care-stand-in`), so the buffer keeps its bytes as Metal's does: about 10 µs a pass on the Iris Xe (ANV). A pass that clears and stores `DontCare` costs no more, and one that stores renders in place. -- **The interlocked pass on the M4 under macOS 27.** MoltenVK gives the M3 Max and the M4 one device - identity on macOS 27, so both split a pass the pixel interlock would split - (`DriverFact::InterlockedPassSplitNoSlower`), about a quarter faster on the M3 Max; the M4 runs - that pass about 8% faster kept whole. +- **A shadow over bytes another writer may write is merged back, not copied back.** Metal writes + only the texels a command writes, and another writer writing bytes no command touches while a + command buffer runs is valid under its contract. On an M3 Max under macOS 27.0.1, a CPU write to + a texel no command touched, made 6 to 23 ms into a kernel's 58 to 68 ms run that wrote another + texel of a texture over a `Shared` or `Managed` buffer, stayed every time; so did another + queue's fill of such a texel of an untracked `Private` buffer, run inside a kernel's or a render + pass's 61 ms run (5 times of 6; the sixth ran after it). Another queue's fill of a tracked + buffer ran after the kernel or the pass ended, every time, as the runtime's tracker orders it. + So a shadow over the bytes of a `Shared` or `Managed` buffer, host pages, the caller's + `VkBuffer` or an untracked buffer is kept after its copy in, and the bytes the commands changed + texture's image into a buffer and a merge, in place of one copy back, each cut to the rectangle + the commands write in where they bound it. A tracked `Private` buffer's, which no other writer + writes while the command buffer runs, is copied back. Where the copy back is a dispatch + (`DriverFact::ShadowCopyBackDispatchFaster`: ANV, whose `vkCmdCopyImageToBuffer` is slow), so is + the first copy, and the merge reads the texels the commands left from the image through an + unsigned-integer view in place of the second. Where the copy in and the first copy are also one + dispatch (`DriverFact::ShadowCopyInDispatchFaster`, measured faster on the UHD 770 of RPL-S + alone), that dispatch reads the texels from the buffer once and stores them in the image and in + the scratch: on the UHD 770 a 1920x1080 pass that loads took 1.43 ms of GPU time against + 1.64-1.67 ms, twelve 17.2 ms against 20.0 ms, a clearing pass 0.89 against 1.04 ms; on the Iris + (`surface_texture_costs::surface_texture_cost_parts`, four shadowed textures a frame, 1,582,016 + texels), over anonymous pages, merged back, passes that draw took 5.0-5.4 ms a frame from commit + to completion, and under scissors (790,448 texels) 3.6-3.9 ms; over tracked `Private` buffers, + copied back, 3.1 ms and 2.2-2.4 ms. - **Emulated tessellation's scan.** On a device without `tessellationShader` a patch draw first runs a one-workgroup scan that places each patch's triangles in Metal's order, patch after patch: about 6-60 ms of GPU time per 10,000-patch draw at factors 4 to 64 on the Radeon 780M and @@ -303,22 +323,19 @@ driver's. Each is open work. each timed command buffer writes: on an M4 a bare barrier took 14.7 µs alone and 167.8 µs with them. `DeviceOptions::gpu_times_from_host` (off by default, announced) answers GPU times from the host clock and spares them. -- **A shadow's copy back after a pass that draws covers every texel inside the draws' scissors**, - where Metal's store writes back only the 32x32 tiles a draw's primitives touch. A CPU write during - the pass to an undrawn texel in an untouched tile inside the scissors can be undone where Metal - keeps it: the host does not know which tiles the primitives touch. No copy reaches the bytes - between rows. -- **A CPU write to a texture's bytes while the host keeps them across the image's first move is - undone.** An image over a no-copy buffer's host pages starts `UNDEFINED` - (`VUID-VkImageCreateInfo-pNext-01443`), and its first move may read and write all the memory - bound to it, so the host keeps those bytes (`texture/first_move.rs`, `device/submit.rs`): once - the submissions before have completed, it reads them through the host pointer, submits the moves - alone, waits, and writes back those that differ. A CPU write to them in between, within one - submission's round trip of the commit that makes the move, is undone, once per image - (`texture/shared_alias.rs`); Metal keeps it, and never writes the bytes between a texture's rows. - No byte outside them is read or written (`runtime_lane::pitched_surfaces`: - `a_texture_s_first_move_keeps_the_bytes_it_lies_over`, - `a_cpu_write_during_a_texture_s_first_move_stays_outside_its_bytes`). +- **A shadow's copy back covers every texel it moves, where no merge serves it**: an image's + shadow (a view of a layout the device's views do not reinterpret), a turned texture's and a + two-plane one's. After a pass that draws, that is every texel inside the draws' scissors, where + Metal's store writes back only the 32x32 tiles a draw's primitives touch: another writer's write + during the pass to an undrawn texel in an untouched tile there can be undone where Metal keeps + it. A shadow over a buffer's bytes another writer may write is merged back instead, only the + words the commands changed (`shadow.rs`), and no write reaches the bytes between rows; a tracked + `Private` buffer's, whose bytes no other writer writes during the pass, is copied back. +- **A merge through a copy rewrites the texture's bytes it did not change**: where the texture's + first byte is not a whole word of its buffer, its bytes go through a staging buffer, or its last + word runs past the buffer, the merge copies the bytes from the texture's first to its last into + its scratch, merges there, and copies them back (`shadow_merge.rs`). Another writer's write to + them between the two copies is undone. - **A cold pipeline making on NVIDIA grows with a module's sampling sites.** NVIDIA's compiler takes about 1 s for macOS 26's largest CoreAnimation fragment (210,033 words) on the RTX 5080 Laptop GPU, once per cold cache; states that share the module then take 13 to 16 ms, and a warm cache