diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index cfbb037b5..db13ba428 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -2189,6 +2189,12 @@ while the driver's exit handler waited on a lock, with every runtime thread alre no thicker than the shift there, and the slab at the far end of the shift goes first. Each slab is one `vkCmdCopyImage`, with an execution barrier between two slabs. A shift of one texel takes one slab and one barrier per texel of the region's extent on that axis. +- Regions of two textures in place over one buffer whose bytes meet copy the same way, each shift + that from a destination row to a source row on its bytes, by the row pitch the device reports + for the linear images: in rows along y, in whole texels along x. Regions on the same bytes copy + nothing. Where the rows meet shifted both ways, or not shifted, along each axis (a destination + row across the end of its own source row and the start of the next), no cut along one axis + keeps the order, and the copy is `Gap::TextureCopy`. - `copy_from_buffer` is `copyFromBuffer:sourceOffset:sourceBytesPerRow:sourceBytesPerImage:` `sourceSize:toTexture:destinationSlice:destinationLevel:destinationOrigin:` and `copy_from_texture_to_buffer` is `copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:` diff --git a/crates/metal2vulkan-runtime/src/blit.rs b/crates/metal2vulkan-runtime/src/blit.rs index 05aef1123..b2ab76924 100644 --- a/crates/metal2vulkan-runtime/src/blit.rs +++ b/crates/metal2vulkan-runtime/src/blit.rs @@ -7,8 +7,9 @@ //! once the copy has run, and holds one global memory barrier beside the image barriers, so the //! copy's writes are visible to every later command through any resource over the same bytes (a //! heap's aliases), not through the image alone. Nothing is copied but the region Metal names. -//! Overlapping regions of one level and slice are the one exception to one command: slabs, one -//! `vkCmdCopyImage` each, an execution barrier between two ([`Slabs`]). +//! Regions whose bytes meet, of one level and slice or of two textures in place over one buffer, +//! are the one exception to one command: slabs, one `vkCmdCopyImage` each, an execution barrier +//! between two ([`Slabs`]). //! //! A copy between a buffer and a texture is the same: `vkCmdCopyBufferToImage` or //! `vkCmdCopyImageToBuffer` against the bytes shaders reach (the buffer's range of its block, or a @@ -46,7 +47,7 @@ use crate::over::{self, Reached}; use crate::record::{memory_barrier, Reach}; use crate::surface::Surface; use crate::texture::{ - copy_unit, place, BytesPlace, CopyUnit, Placed, Region, Texture, TextureDescriptor, + copy_unit, place, BytesPlace, CopyUnit, Placed, Region, Rows, Texture, TextureDescriptor, TextureObject, }; use ash::vk; @@ -167,18 +168,22 @@ impl BlitCommandEncoder { /// nothing, as plain Metal does where its validation stops the call. Within one level and /// slice of one image (the texture into itself, or a texture and its view), regions apart /// copy with that subresource in the general layout, and the same region copies nothing and - /// records no command, every texel already its own. Overlapping regions there, which Metal - /// leaves undefined, copy as if the source were read whole before any texel is written, the - /// answer an Apple M3 Max gives: in slabs across one axis, each no thicker than the shift - /// between the regions there, so that its two regions lie apart, one `vkCmdCopyImage` a slab - /// and the far end of the shift first, an execution barrier between two slabs. The axis is the - /// one of fewest slabs; a shift of one texel takes one slab a texel. The command buffer keeps - /// both textures until it retires. + /// records no command, every texel already its own. Overlapping regions there, and regions of + /// two textures in place over one buffer ([`Buffer::new_texture`]) whose bytes meet, which + /// Metal leaves undefined, copy as if the source were read whole before any texel is written, + /// the answer an Apple M3 Max gives: in slabs across one axis, each no thicker than the shift + /// between the regions there (between two textures over one buffer, from each destination + /// row to each source row on its bytes: in rows along y, in whole texels along x), so that its + /// two regions share no byte, one `vkCmdCopyImage` a slab and the far end of the shift first, + /// an execution barrier between two slabs. The axis is the one of fewest slabs; a shift of one + /// texel takes one slab a texel. Two textures over one buffer whose regions are the same bytes + /// copy nothing. The command buffer keeps both textures until it retires. /// /// Err: [`Refusal::OtherDevice`] for another device's texture; [`Refusal::TextureRegion`] for /// a level, slice or region outside either texture or off its format's block grid; - /// [`Refusal::TextureCopyMismatch`]; [`Gap::TextureCopy`]; [`Error::Vulkan`] where the command - /// buffer cannot record. + /// [`Refusal::TextureCopyMismatch`]; [`Gap::TextureCopy`], regions of two textures over one + /// buffer whose bytes meet where no axis cuts them so among it; [`Error::Vulkan`] where the + /// command buffer cannot record. pub fn copy_from_texture( &mut self, source: &Texture, @@ -241,7 +246,7 @@ impl BlitCommandEncoder { (&away_one, &back_one) } }; - // Between two slabs, every hazard is a write after a read: no slab reads a texel an + // Between two slabs, every hazard is a write after a read: no slab reads a byte an // earlier one wrote (`Slabs`), so an execution dependency orders them. let between = [vk::MemoryBarrier2::default() .src_stage_mask(vk::PipelineStageFlags2::COPY) @@ -250,8 +255,8 @@ impl BlitCommandEncoder { let (named_read, named_write) = (source.copy_layout(read), destination.copy_layout(write)); // SAFETY: the command buffer records outside any render pass and keeps both images until // it retires; each subresource is in its home layout between commands, and in its copy - // layout between the barriers: two subresources, or one in the general layout whose two - // regions lie apart in each slab (`texture_copy`); each slab's regions lie in both. + // layout between the barriers: two subresources, or one in the general layout; each + // slab's two regions share no byte (`texture_copy`), and lie in both. unsafe { device.cmd_pipeline_barrier2( command, @@ -1235,13 +1240,15 @@ unsafe fn close(core: &Core, command: vk::CommandBuffer, back: &[vk::ImageMemory core.counters.closed(dependency.memory_barrier_count); } -/// One texture of a copy: its descriptor, its image's format, the unit its copies move, and -/// where it starts in its image (a view's first level and array layer). +/// One texture of a copy: its descriptor, its image's format, the unit its copies move, where it +/// starts in its image (a view's first level and array layer), and, in place over a buffer, where +/// its texels lie in the buffer's bytes. pub(crate) struct Side<'a> { pub(crate) descriptor: &'a TextureDescriptor, pub(crate) format: vk::Format, pub(crate) unit: Option, pub(crate) base: [u32; 2], + pub(crate) rows: Option, } impl<'a> Side<'a> { @@ -1251,6 +1258,7 @@ impl<'a> Side<'a> { format: texture.format(), unit: texture.unit(), base: texture.base(), + rows: texture.in_place(), } } @@ -1323,12 +1331,12 @@ impl ImageCopy { /// The slabs a copy between textures runs as, one copy command each: the region cut across /// `axis` into slabs `thickness` texels thick (the last what is left), from the far end of the -/// axis first where `reversed`. Regions apart copy as one slab. Overlapping regions of one -/// subresource are cut no thicker than the shift between them along an axis they are shifted -/// along, so that each slab's two regions lie apart, on the axis of fewest slabs; and the slab -/// at the end the shift points to goes first, so that no slab reads a texel an earlier one -/// wrote. The copy so gives what reading its source whole before writing gives, as `memmove` -/// does. +/// axis first where `reversed`. Regions that share no byte copy as one slab. Regions that do are +/// cut ([`cut`]) no thicker than the least shift between them along an axis every shift points +/// the same way along, so that each slab's two regions share no byte, on the axis of fewest +/// slabs; and the slab at the end the shifts point to goes first, so that no slab reads a byte +/// an earlier one wrote. The copy so gives what reading its source whole before writing gives, +/// as `memmove` does. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct Slabs { pub(crate) axis: usize, @@ -1658,35 +1666,39 @@ pub(crate) fn texture_copy( return Ok(None); }; // One subresource of one image, the textures one or a texture and its view, copies in the - // general layout (`VUID-vkCmdCopyImage-srcImage-09460`), and no command's source and - // destination share a texel (`-pRegions-00124`). The same region copies nothing, every texel - // already its own. Metal leaves a copy whose regions overlap undefined (Apple's - // `copy(from:...to:...)` page: "unexpected behavior"); an Apple M3 Max reads the source whole - // before it writes, which slabs give (`Slabs`). + // general layout (`VUID-vkCmdCopyImage-srcImage-09460`); two textures in place over one + // buffer may share bytes too. No command's source and destination share a byte + // (`-pRegions-00124`). The same texels copy nothing, every one already its own. Metal leaves + // a copy whose regions overlap undefined (Apple's `copy(from:...to:...)` page: "unexpected + // behavior"); an Apple M3 Max reads the source whole before it writes, which slabs give + // (`Slabs`). let shared = same && from.level == to.level && from.layer == to.layer; - let apart = (0..3).any(|axis| { - let (a, b, extent) = (from.origin[axis], to.origin[axis], from.size[axis]); - a + extent <= b || b + extent <= a - }); - let slabs = match shared && !apart { - false => Slabs { - axis: 0, - thickness: from.size[0], - reversed: false, - }, - true => { - let shifted = (0..3).filter(|&axis| from.origin[axis] != to.origin[axis]); - let thickness = |axis: usize| from.origin[axis].abs_diff(to.origin[axis]); - let fewest = shifted.min_by_key(|&axis| from.size[axis].div_ceil(thickness(axis))); - let Some(axis) = fewest else { - return Ok(None); - }; - Slabs { - axis, - thickness: thickness(axis), - reversed: to.origin[axis] > from.origin[axis], - } + let slabs = match (source.rows, destination.rows) { + _ if shared => { + let apart = (0..3).any(|axis| { + let (a, b, extent) = (from.origin[axis], to.origin[axis], from.size[axis]); + a + extent <= b || b + extent <= a + }); + let shift = std::array::from_fn(|axis| { + i128::from(to.origin[axis]) - i128::from(from.origin[axis]) + }); + cut((!apart).then_some(shift), [1; 3], from.size) } + (Some(a), Some(b)) if a.buffer == b.buffer => { + let texel = u64::from(unit.bytes); + let first = |rows: Rows, placed: &Placed| Rows { + offset: rows.offset + + u64::from(placed.origin[1]) * rows.pitch + + u64::from(placed.origin[0]) * texel, + ..rows + }; + let rows = meeting(first(a, &from), first(b, &to), from.size, texel); + cut(rows, [u128::from(texel), 1, 1], from.size) + } + _ => cut(None, [1; 3], from.size), + }; + let Some(slabs) = slabs.ok_or_else(gap)? else { + return Ok(None); }; Ok(Some(ImageCopy { from, @@ -1697,6 +1709,82 @@ pub(crate) fn texture_copy( })) } +/// The slabs of a copy of `size` texels from `shifts`: for each destination texel, or row, on +/// bytes of a source texel, or row, how far that source lies from it in the region (the source's +/// place less the destination's), along each axis in `units`: texels, or bytes along x between +/// two textures over one buffer. Regions of no shift share no byte, and copy as one slab. Shifts +/// all of 0 make every destination texel its own source: `Some(None)`, nothing to copy. Otherwise +/// an axis that every shift moves along, all one way, is cut no thicker than the least shift +/// along it in whole texels, so that no slab's source and destination share a byte; the slab at +/// the end the shifts point to goes first, so that no slab reads a byte an earlier one wrote (an +/// earlier slab's destination bytes that are a later one's source would be a shift the other +/// way). The cut is along the axis of fewest slabs, the first of them; `None` where no axis cuts. +fn cut( + shifts: impl IntoIterator, + units: [u128; 3], + size: [u32; 3], +) -> Option> { + // Along each axis: the least shift's size, and whether a shift points toward lower and one + // toward higher coordinates. + let mut along = [(u128::MAX, false, false); 3]; + let (mut any, mut own) = (false, true); + for shift in shifts { + any = true; + own &= shift == [0; 3]; + for ((least, lower, higher), shift) in along.iter_mut().zip(shift) { + *least = (*least).min(shift.unsigned_abs()); + *lower |= shift < 0; + *higher |= shift > 0; + } + } + if !any { + return Some(Some(Slabs { + axis: 0, + thickness: size[0], + reversed: false, + })); + } + if own { + return Some(None); + } + (0..3) + .filter_map(|axis| { + let (least, lower, higher) = along[axis]; + let thickness = u32::try_from(least / units[axis]).ok()?; + (thickness > 0 && !(lower && higher)).then_some(Slabs { + axis, + thickness, + reversed: higher, + }) + }) + .min_by_key(|slabs| size[slabs.axis].div_ceil(slabs.thickness)) + .map(Some) +} + +/// The shifts ([`cut`]) of a copy of `size` texels of `texel` bytes between two textures in place +/// over one buffer, from the region whose first texel is at `from` to the one at `to`: for each +/// destination row on bytes of a source row, the destination row's first byte less the source +/// row's along x (in bytes, the source texel on a destination texel's bytes less that texel, in +/// the region), and the source row less the destination row along y. A row of the texture is no +/// longer than its pitch, so a source row meets at most the two destination rows whose starts lie +/// nearest before and after its own. Regions whose spans of bytes do not meet meet in no row. +fn meeting(from: Rows, to: Rows, size: [u32; 3], texel: u64) -> impl Iterator { + let row = i128::from(size[0]) * i128::from(texel); + let rows = i128::from(size[1]); + let (first, pitch) = (i128::from(from.offset), i128::from(from.pitch)); + let (onto, onto_pitch) = (i128::from(to.offset), i128::from(to.pitch)); + let spans = + first < onto + (rows - 1) * onto_pitch + row && onto < first + (rows - 1) * pitch + row; + (0..if spans { rows } else { 0 }).flat_map(move |j| { + let start = first + j * pitch; + let k = (start - onto).div_euclid(onto_pitch); + [k, k + 1].into_iter().filter_map(move |k| { + let shift = onto + k * onto_pitch - start; + ((0..rows).contains(&k) && shift.abs() < row).then_some([shift, j - k, 0]) + }) + }) +} + /// Whether Apple defines mipmaps of `pf`: a colour-renderable, filterable format, which is not a /// depth or stencil, compressed, YCbCr or integer one ("generateMipmapsForTexture:"). pub(crate) fn mipmapped(pf: PixelFormat) -> bool { diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index eee4185c5..f17e473dc 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -1143,12 +1143,15 @@ pub enum Gap { pixel_format: PixelFormat, }, /// [`BlitCommandEncoder::copy_from_texture`](crate::BlitCommandEncoder::copy_from_texture) - /// that no single `vkCmdCopyImage` in the floor makes: a multisample texture; a format of - /// depth and stencil both; one pixel format held in two Vulkan formats, which the two - /// textures' usages chose; or a 1D texture with one of another type. + /// that the floor's `vkCmdCopyImage` does not make: a multisample texture; a format of depth + /// and stencil both; one pixel format held in two Vulkan formats, which the two textures' + /// usages chose; a 1D texture with one of another type; or regions of two textures in place + /// over one buffer whose rows meet shifted both ways, or not shifted, along each axis, so + /// that no cut into slabs along one axis copies them as from the source before the copy (a + /// destination row across the end of its own source row and the start of the next is one). /// - /// Basis: ours (Vulkan 1.3 copies none of these with one command; each is built when a replay - /// stream makes one). + /// Basis: ours (Vulkan 1.3 copies none of these with one command, nor these regions in slabs + /// along one axis; each is built when a replay stream makes one). TextureCopy { /// The source texture's pixel format. source: PixelFormat, diff --git a/crates/metal2vulkan-runtime/src/tests/blit.rs b/crates/metal2vulkan-runtime/src/tests/blit.rs index a5450d466..6b5a578c6 100644 --- a/crates/metal2vulkan-runtime/src/tests/blit.rs +++ b/crates/metal2vulkan-runtime/src/tests/blit.rs @@ -6,7 +6,10 @@ //! among it, is `Gap::TextureCopy`; within one level and slice of one image (one texture, or a //! texture and its view), regions apart copy in the general layout, the same region copies //! nothing, and overlapping regions, which Metal leaves undefined, copy in slabs across the -//! axis of fewest, each no thicker than the shift there, the far end of the shift first; a +//! axis of fewest, each no thicker than the shift there, the far end of the shift first; so do +//! regions of two textures in place over one buffer whose bytes meet, each shift that from a +//! destination row to a source row on its bytes, and where no axis cuts them so they are +//! `Gap::TextureCopy`, while rows that interleave or other bytes copy whole; a //! level, slice or region outside a texture or off its block grid is `Refusal::TextureRegion`; //! a size of 0 on an axis a texture lacks copies one texel there, and on another copies //! nothing; a 3D texture's image copies to and from a 2D slice. @@ -22,7 +25,10 @@ //! in the conformance crate (an Apple M3 Max, macOS 27.0.1, job m3-max-43464, plain and under //! the validation layer). Overlapping regions of one level and slice leave the source's bytes //! from before the copy, toward higher and lower coordinates on each axis, through a view, and -//! in BC1 blocks where the device makes them, at one barrier more a slab after the first. +//! in BC1 blocks where the device makes them, at one barrier more a slab after the first. So do +//! regions of two textures in place over one buffer whose bytes meet, a row on and within the +//! rows, each way, every other byte of the buffer kept; whole rows each across the end of its +//! own source row and the start of the next are refused, and record nothing. //! - Between a buffer and a texture: each image of the region lies at its own offset, its rows a //! count of texels apart; what Metal's validation stops is `Refusal::BufferCopyLayout`, and an //! offset or row stride a copy command cannot address `Gap::BufferCopyAlignment`. Under a device @@ -58,9 +64,9 @@ use crate::blit::{ Lies, Side, Slabs, Span, TexturePlace, }; use crate::error::{Error, Gap, Refusal}; -use crate::texture::{CopyUnit, Placed}; +use crate::texture::{CopyUnit, Placed, Rows}; use crate::{PixelFormat, TextureDescriptor, TextureType}; -use ash::vk; +use ash::vk::{self, Handle}; /// A side of a copy: a texture of `d` held in `format`, of `unit`. fn side(d: &TextureDescriptor, format: vk::Format, unit: Option) -> Side<'_> { @@ -69,6 +75,20 @@ fn side(d: &TextureDescriptor, format: vk::Format, unit: Option) -> Si format, unit, base: [0, 0], + rows: None, + } +} + +/// A side of an RGBA8 texture of `d` in place over a buffer: its first texel at `offset` in the +/// `VkBuffer` numbered `buffer`, its rows `pitch` apart. +fn over(d: &TextureDescriptor, buffer: u64, offset: u64, pitch: u64) -> Side<'_> { + Side { + rows: Some(Rows { + buffer: vk::Buffer::from_raw(buffer), + offset, + pitch, + }), + ..side(d, vk::Format::R8G8B8A8_UNORM, color(4)) } } @@ -341,6 +361,78 @@ fn overlapping_regions_copy_in_slabs_the_far_end_of_the_shift_first() { ); } +#[test] +fn regions_of_two_textures_over_one_buffer_copy_in_slabs_where_their_bytes_meet() { + // Rows of 16 texels of 4 bytes, 64 bytes apart. + let d = descriptor(TextureType::Type2D, PixelFormat::RGBA8Unorm, [16, 4, 1]); + let first = over(&d, 1, 0, 64); + let copy = |from: &Side<'_>, to: &Side<'_>, size| { + texture_copy(from, at(0, 0, [0; 3]), size, to, at(0, 0, [0; 3]), false) + }; + let slabs = |from: &Side<'_>, to: &Side<'_>, size| copied(copy(from, to, size)).slabs; + let cut = |axis, thickness, reversed| Slabs { + axis, + thickness, + reversed, + }; + let whole = [16, 4, 1]; + // A texture a row on: slabs of a row, the end the shift points to first. + let row_on = over(&d, 1, 64, 64); + let forward = copied(copy(&first, &row_on, whole)); + assert!(!forward.shared, "two images"); + assert_eq!( + slab_regions(&forward), + [ + ([0, 3], [0, 3], [16, 1]), + ([0, 2], [0, 2], [16, 1]), + ([0, 1], [0, 1], [16, 1]), + ([0, 0], [0, 0], [16, 1]), + ] + ); + assert_eq!(slabs(&row_on, &first, whole), cut(1, 1, false)); + assert_eq!(slabs(&first, &over(&d, 1, 128, 64), whole), cut(1, 2, true)); + // Two texels on, a region that stays inside the other's rows: slabs of two texels across. + let within = over(&d, 1, 8, 64); + assert_eq!(slabs(&first, &within, [12, 4, 1]), cut(0, 2, true)); + assert_eq!(slabs(&within, &first, [12, 4, 1]), cut(0, 2, false)); + // A row and two texels on, whole rows: each destination row across the end of one source + // row and the start of the next, neither its own, so slabs of a row. + assert_eq!(slabs(&first, &over(&d, 1, 72, 64), whole), cut(1, 1, true)); + // Two texels on, whole rows: each destination row across the end of its own source row and + // the start of the next. No cut along one axis keeps the order. + assert!(matches!( + gap(copy(&first, &within, whole)), + Gap::TextureCopy { .. } + )); + // Rows of two pitches that meet at their starts: no cut either. + let wider = over(&d, 1, 0, 128); + assert!(matches!( + gap(copy(&first, &wider, [8, 4, 1])), + Gap::TextureCopy { .. } + )); + // Regions whose rows interleave, touching, of one pitch or two, and textures over other bytes, + // share no byte: one slab, the whole region. + let (left, interleaved) = (over(&d, 1, 0, 128), over(&d, 1, 64, 128)); + assert_eq!(slabs(&left, &interleaved, whole), cut(0, 16, false)); + assert_eq!( + slabs(&first, &over(&d, 1, 32, 128), [8, 4, 1]), + cut(0, 8, false) + ); + assert_eq!(slabs(&first, &over(&d, 2, 0, 64), whole), cut(0, 16, false)); + // The same bytes: nothing to copy. + assert!(matches!( + texture_copy( + &first, + at(0, 0, [0, 1, 0]), + [16, 3, 1], + &row_on, + at(0, 0, [0; 3]), + false + ), + Ok(None) + )); +} + #[test] fn what_metal_refuses_is_refused_and_what_one_command_does_not_make_is_a_gap() { let d = |format, extent| descriptor(TextureType::Type2D, format, extent); @@ -1676,6 +1768,157 @@ pub(crate) mod on_device { }); } + /// Two textures in place over one Shared buffer, rows the device's own pitch apart, whose + /// regions' bytes meet, which Metal leaves undefined, leave each destination texel holding + /// what the source held before the copy, the answer an Apple M3 Max gives (the conformance + /// crate's `buffer_texture_blits.rs`, its rows a row on), every other byte of the buffer kept: + /// a texture a row on from the other, onto it and from it, in slabs of a row; one a memory + /// alignment on, a region within the other's rows, onto it and from it, in slabs of that many + /// bytes across; regions apart in one command. Each copy is one submission and copies no byte + /// of the runtime's own; each slab after the first costs one barrier more than a copy's three. + /// Whole rows a memory alignment on, each destination row across the end of its own source + /// row and the start of the next, are `Gap::TextureCopy`, and record nothing. + #[test] + fn every_device_copies_between_textures_over_one_buffer_from_the_source_before_the_copy() { + use crate::texture::TextureObject; + const HEIGHT: u32 = 4; + each_device("blit_over_one_buffer", |name, _, device| { + device + .grant_indices(IndexClass::Texture, 4096, 4) + .expect("a grant"); + let format = PixelFormat::RGBA8Unorm; + let mut d = TextureDescriptor::new(TextureType::Type2D, format, 64, HEIGHT); + d.usage = TextureUsage::SHADER_READ; + // A place in the buffer's bytes that a linear image takes: a memory alignment on, a + // texel at least. + let memory = (device.linear_memory_alignment(&d)).expect("a linear image"); + let step = memory.max(4); + let align = (device.minimum_linear_texture_alignment(format)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + // Rows of four steps at least, at the device's own pitch: a texture a step on starts + // inside the other's first row, and a region a step narrower than a row lies inside + // the other's rows. + let pitch = [256, 4 * step, align].into_iter().max().expect("a pitch"); + d.width = u32::try_from(pitch / 4).expect("a width"); + let len = (2 * u64::from(HEIGHT) + 1) * pitch; + let block = (device.take_block(MemoryClass::Shared, len)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let buffer = (device.new_buffer(block.id, 0, len, None)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let mut indices = 4096..; + let mut over = |offset: u64| { + let texture = (buffer.new_texture(&d, indices.next(), offset, pitch)) + .unwrap_or_else(|error| panic!("{name}: at {offset}: {error}")); + assert!( + texture.copied_over().is_none(), + "{name}: at {offset}: in place" + ); + (texture, offset) + }; + let first = over(0); + let row_on = over(pitch); + let within = over(step); + let apart = over(u64::from(HEIGHT) * pitch); + let queue = device.new_command_queue(4).expect("a queue"); + // The textures' moves home go with a command buffer of their own. + let homes = queue.command_buffer().expect("a command buffer"); + homes + .record_for_test(&[], |_, _| {}) + .expect("a command buffer's commands"); + homes.commit().expect("a commit"); + finished(name, &homes); + let counters = device.counters(); + let width = d.width; + let shift = u32::try_from(step / 4).expect("a shift"); + let across = (width - shift).div_ceil(shift); + // Each case: the source and the destination with their offsets in the buffer, the + // region's width (its height is the textures'), and the slabs the copy takes. + let cases = [ + ("a row on", &first, &row_on, width, HEIGHT), + ("a row back", &row_on, &first, width, HEIGHT), + ( + "within the rows, on", + &first, + &within, + width - shift, + across, + ), + ( + "within the rows, back", + &within, + &first, + width - shift, + across, + ), + ("apart", &first, &apart, width, 1), + ]; + let at = TexturePlace::default(); + for (seed, (case, (from, from_at), (to, to_at), columns, slabs)) in (1..).zip(cases) { + let before = pattern(len as usize, seed); + write(&buffer, &before); + settled(&device); + let metrics = counters.metrics(); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = command_buffer.blit_command_encoder().expect("an encoder"); + (encoder.copy_from_texture(from, at, [columns, HEIGHT, 1], to, at)) + .unwrap_or_else(|error| panic!("{name}: {case}: {error}")); + encoder.end_encoding(); + run(name, &command_buffer); + let rows = (0..u64::from(HEIGHT)).map(|row| { + ( + (from_at + row * pitch) as usize, + (to_at + row * pitch) as usize, + ) + }); + let want = moved(before.clone(), &before, rows, 4 * columns as usize); + assert_eq!(read(&buffer), want, "{name}: {case}: the buffer's bytes"); + let after = counters.metrics(); + assert_eq!( + ( + after.submissions - metrics.submissions, + after.barriers - metrics.barriers, + after.bytes_copied - metrics.bytes_copied, + ), + (1, 2 + u64::from(slabs), 0), + "{name}: {case}: submissions, barriers, bytes copied" + ); + } + + // Whole rows a memory alignment on: refused, nothing recorded, every byte kept. + let before = read(&buffer); + settled(&device); + let metrics = counters.metrics(); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = command_buffer.blit_command_encoder().expect("an encoder"); + let refused = + encoder.copy_from_texture(&first.0, at, [width, HEIGHT, 1], &within.0, at); + assert!( + matches!(refused, Err(Error::Unsupported(Gap::TextureCopy { .. }))), + "{name}: whole rows a memory alignment on: {refused:?}" + ); + encoder.end_encoding(); + run(name, &command_buffer); + let after = counters.metrics(); + assert_eq!( + ( + after.submissions - metrics.submissions, + after.barriers - metrics.barriers + ), + (0, 0), + "{name}: the refused copy records nothing" + ); + assert_eq!( + read(&buffer), + before, + "{name}: the refused copy keeps every byte" + ); + println!( + "{name}: copies between textures over one buffer from the source before the copy, \ + rows {pitch} bytes apart, a memory alignment of {memory}" + ); + }); + } + /// Writes `bytes` over the start of a Shared buffer. fn write(buffer: &Buffer, bytes: &[u8]) { let contents = buffer.contents().expect("a Shared buffer"); diff --git a/crates/metal2vulkan-runtime/src/tests/blit_options.rs b/crates/metal2vulkan-runtime/src/tests/blit_options.rs index e9d1f71ad..d79090ae5 100644 --- a/crates/metal2vulkan-runtime/src/tests/blit_options.rs +++ b/crates/metal2vulkan-runtime/src/tests/blit_options.rs @@ -34,6 +34,7 @@ fn copy( format, unit: None, base: [0, 0], + rows: None, }; let lies = Lies { base: 0, diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 79bc15837..671bbc448 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -3049,6 +3049,18 @@ impl Made { } } +/// Where the texels of a texture in place over a buffer lie ([`Buffer::new_texture`]): the +/// `VkBuffer` commands reach the buffer's bytes through, which spans their allocation, so that two +/// textures whose bytes meet name one; the first texel's offset there; and the bytes from one +/// row's start to the next's, the row pitch the device reports for the linear image +/// (`vkGetImageSubresourceLayout`, which the image is made only at). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Rows { + pub(crate) buffer: vk::Buffer, + pub(crate) offset: u64, + pub(crate) pitch: u64, +} + /// A region of one level and slice of a texture, checked against the texture. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct Placed { @@ -4662,6 +4674,19 @@ pub(crate) trait TextureObject { bicubic_texels_word(inner.descriptor.pixel_format, inner.reads()) } + /// Of a texture in place over a buffer, where its texels lie in the bytes shaders reach (a + /// Managed buffer's device copy, where it has one); `None` for any other texture. + fn in_place(&self) -> Option { + let named = (self.object().named.as_ref()).filter(|named| named.form == Form::InPlace)?; + let place = named.places[0]; + let (buffer, at) = named.buffer.device_range(); + Some(Rows { + buffer, + offset: at + place.offset, + pitch: place.bytes_per_row, + }) + } + /// Whether the host reads the GPU's writes to it with no copy: a texture in place over a /// Shared buffer. fn host_reads(&self) -> bool { diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 74c22d8a8..1058753a2 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -376,7 +376,7 @@ Columns: | `LodClamps` | A sampler state bound with LOD clamps its samples read otherwise through (`ComputeCommandEncoder::set_sampler_state_with_lod_clamps` and the... | every device (a public call's own check of its arguments) | `ours`: no replay stream binds such clamps: every bind-time clamp the streams make reads as its state's own | 1: `crates/metal2vulkan-runtime/src/sampler.rs (clamps_at_bind)` | `-` | | `TextureBytes` | `Texture::replace_region`, `Texture::get_bytes` or a blit copy between a buffer and a texture (`BlitCommandEncoder::copy_from_buffer`) of a... | every device (a public call's own check of its arguments) | `ours`: no copy between such an image and bytes is built | 4: `crates/metal2vulkan-runtime/src/blit.rs (buffer_copy)`, `crates/metal2vulkan-runtime/src/blit.rs (with_option)` (+2) | `-` | | `FloatDepthUpload` | `Texture::replace_region` or `BlitCommandEncoder::copy_from_buffer` into a 32-bit float depth (`Depth32Float`) | every device (a public call's own check of its arguments) | `ours`: no upload of a 32-bit float depth is built | 3: `crates/metal2vulkan-runtime/src/blit.rs (buffer_copy)`, `crates/metal2vulkan-runtime/src/texture.rs (replace_region)` (+1) | `-` | -| `TextureCopy` | `BlitCommandEncoder::copy_from_texture` that no single `vkCmdCopyImage` in the floor makes | every device (a public call's own check of its arguments) | `ours`: Vulkan 1.3 copies none of these with one command; each is built when a replay stream makes one | 1: `crates/metal2vulkan-runtime/src/blit.rs (texture_copy)` | `-` | +| `TextureCopy` | `BlitCommandEncoder::copy_from_texture` that the floor's `vkCmdCopyImage` does not make | every device (a public call's own check of its arguments) | `ours`: Vulkan 1.3 copies none of these with one command, nor these regions in slabs along one axis; each is built when a replay stream makes one | 1: `crates/metal2vulkan-runtime/src/blit.rs (texture_copy)` | `-` | | `TextureOverBuffer` | A texture over a buffer (`Buffer::new_texture`) the runtime does not make | every device (a public call's own check of its arguments) | `ours`: the in-place linear image and the copy form take one 2D color image | 3: `crates/metal2vulkan-runtime/src/texture.rs (check_over)`, `crates/metal2vulkan-runtime/src/texture.rs (error)` (+1) | `-` | | `HeapTexture` | A heap texture the runtime does not place (`Device::new_heap_texture`, `Device::new_heap_texture_for_views` and `Device::heap_texture_size_and_align`) | every device (a public call's own check of its arguments) | `ours`: heap textures are built for Private heaps of placeable images | 2: `crates/metal2vulkan-runtime/src/texture.rs (heap_fit)`, `crates/metal2vulkan-runtime/src/texture.rs (heap_source)` | `-` | | `SurfaceUsage` | A surface plane in place (`Device::new_exported_surface`) whose texture's uses ask an image usage its linear tiling lacks (storage, for one) | at the device's limit | `device`: the image format query and the format features of the plane's tiling | 3: `crates/metal2vulkan-runtime/src/d3d11.rs (d3d11_plane)`, `crates/metal2vulkan-runtime/src/surface.rs (plane)` (+1) | `-` |