diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index 700ca9f9b..fd425b44c 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -5,8 +5,8 @@ takes its name when it does; until then it is unpublished. Its public API so far: the instance and the device, memory blocks and the buffers in them, the grants of texture and sampler indices, textures, sampler states, command queues, command buffers -and events, the device's counters, and `floor`, the check of a Vulkan device against the floor -below. +and events, compute and blit encoders, the device's counters, and `floor`, the check of a Vulkan +device against the floor below. ## Instance and device @@ -291,7 +291,8 @@ made, with no lock, and never rewritten for layouts. wrote Shared memory (a Shared buffer bound or declared for writing, or a write through an address outside the dispatch's resources) or signals an event, so the host reads those writes once the command buffer completes or it sees the event; a segment that wrote only Private memory leaves - the host out. No segment starts with a barrier. + the host out. No segment starts with a barrier of its own; a blit copy records its own two + (see "Blit encoders"). `enqueue` takes the command buffer's place in its queue; `commit` hands it to the submit thread and returns. A committed command buffer holds no device handle. - The submit thread passes what is ready to `vkQueueSubmit2` in the device's commit order, each @@ -442,9 +443,9 @@ that touch blocks first. - A barrier within a segment orders dispatches after dispatches: compute shader writes before it, compute shader reads and writes after it, and indirect argument reads only where the dispatch after it is indirect. An indirect dispatch after a write that no barrier since has ordered - before indirect argument reads gets one that does, in either kind of encoder. A segment records - nothing else that touches memory; the barrier at a segment's end takes every command and the - host. + before indirect argument reads gets one that does, in either kind of encoder. The other + commands a segment records that touch memory, blit copies, order themselves against everything + before and after them; the barrier at a segment's end takes every command and the host. - A buffer bound where its address, its `gpuAddress` plus the offset, is not a multiple of its kernel argument's alignment (`air.arg_type_align_size`, at most 16) is pushed rounded down to that alignment, where Metal's API validation refuses the bind; `docs/API.md` section 10 says @@ -462,6 +463,33 @@ that touch blocks first. state an encoder binds or declares, until it retires, so their elements of set 1 stay theirs while work may read them. +## Blit encoders + +- `CommandBuffer::blit_command_encoder` is `blitCommandEncoder`. While it is open it holds the + command buffer's recording, as a compute encoder does. +- `copy_from_texture` is `copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:` + `toTexture:destinationSlice:destinationLevel:destinationOrigin:`, a `TexturePlace` holding each + side's slice, level and origin. It records one `vkCmdCopyImage` between the two images, at once, + with nothing staged and no byte copied beyond the region. The bytes move as they are: formats + whose units have the same bytes copy into each other, as Metal copies them; a compressed + region is whole blocks or reaches the level's edge on both sides; a 3D texture's image copies + into or out of a 2D slice. A size of 0 on an axis a texture lacks copies one texel there; on + another axis the copy copies nothing. +- A copy records two barriers. The first moves each texture's level and slice from its home + layout to the transfer layout after every earlier command, and makes every earlier write visible + to every later command; it pays a barrier an encoder owed, and the hazard sets start again. The + second moves them home once the copy has run, its writes visible to every later command. A copy + so needs no hazard tracking and leaves none: a command buffer of one copy has three barriers, + the segment's end among them. The encoder owes nothing at its end. +- Refused: what Metal leaves undefined, formats whose units differ in bytes and textures of + different sample counts (`Refusal::TextureCopyMismatch`), and a region outside either texture + or off its block grid (`Refusal::TextureRegion`). Not built (`Gap::TextureCopy`): what one + `vkCmdCopyImage` in the floor does not make (a multisample texture, a format of depth and stencil + both, depth or stencil with another format, a compressed format with another block extent, + `A8_UNORM` with another format, a 1D texture with another type), and one level and slice of a + texture into itself. The slice-and-level and whole-texture forms of `copyFromTexture`, and the + other blit commands, are not built yet. + ## Compute pipeline states - `Device::new_compute_pipeline_state(&ComputePipelineDescriptor, sampler_ids)` is diff --git a/crates/metal2vulkan-rt/src/blit.rs b/crates/metal2vulkan-rt/src/blit.rs new file mode 100644 index 000000000..40fe77194 --- /dev/null +++ b/crates/metal2vulkan-rt/src/blit.rs @@ -0,0 +1,284 @@ +//! Blit command encoders: each copy recorded at once into the command buffer's current segment. +//! +//! A copy between textures is one `vkCmdCopyImage` between two barriers. The first moves each +//! texture's level and slice from its home layout to a transfer layout after every earlier +//! command, and makes every earlier command's writes visible to every later command: it pays the +//! barrier an earlier encoder owed, and the hazard sets start again. The second moves them home +//! once the copy has run, its writes visible to every later command. Nothing is copied but the +//! region Metal names. + +use crate::command::{Building, CommandBuffer}; +use crate::counters::Metric; +use crate::error::{Error, Gap, Refusal}; +use crate::record::{memory_barrier, Reach}; +use crate::texture::{place, CopyUnit, Placed, Region, Texture, TextureDescriptor}; +use ash::vk; +use metal2vulkan::metal::TextureType; +use std::sync::Arc; + +/// No Metal counterpart as a type: the slice, mipmap level and origin a blit names in one +/// texture, which Metal's calls take as three arguments (`sourceSlice:sourceLevel:sourceOrigin:`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct TexturePlace { + /// The slice: an array's element, or a cube's face, six a cube; 0 for a texture of one + /// slice, a 3D texture among them. + pub slice: u32, + /// The mipmap level. + pub level: u32, + /// The first texel, `[x, y, z]`. + pub origin: [u32; 3], +} + +/// `MTLBlitCommandEncoder`: records each copy into its command buffer at once. +/// +/// A copy runs after every earlier command of its command buffer, and every later command runs +/// after it, with the writes on either side visible across it: a blit needs no hazard tracking of +/// its own and leaves none for the encoders after it. Each texture's level and slice leaves its +/// home layout for the copy and comes back in the same call; no element of set 1 is rewritten. +/// +/// Owned: one thread encodes at a time. Dropping it ends it, as +/// [`end_encoding`](Self::end_encoding) does. +pub struct BlitCommandEncoder { + command_buffer: CommandBuffer, + /// What the command buffer records, held while the encoder is open. + building: Option, +} + +impl CommandBuffer { + /// `blitCommandEncoder`. + /// + /// Err: [`Refusal::Committed`]; [`Refusal::EncoderOpen`] while another encoder of the command + /// buffer is open. + pub fn blit_command_encoder(&self) -> Result { + let building = self.open_encoder()?; + building.device.core().counters.count(Metric::Passes); + Ok(BlitCommandEncoder { + command_buffer: self.clone(), + building: Some(building), + }) + } +} + +impl BlitCommandEncoder { + fn building(&mut self) -> &mut Building { + self.building + .as_mut() + .expect("an encoder holds its command buffer's recording until it ends") + } + + /// `copyFromTexture:sourceSlice:sourceLevel:sourceOrigin:sourceSize:toTexture:` + /// `destinationSlice:destinationLevel:destinationOrigin:`: `size` texels from `from` in + /// `source` to `to` in `destination`, one `vkCmdCopyImage`. The bytes move as they are, so + /// formats whose units have the same bytes copy into each other (`RGBA8Unorm` into + /// `R32Uint`), as Metal copies them; a compressed format's region is whole blocks or reaches + /// the level's edge on both sides. A 3D texture's region one image deep copies into or out of + /// a 2D slice. A size of 0 on an axis one of the textures lacks (depth on any but a 3D + /// texture, height on a 1D one) copies one texel there, and a size of 0 on another axis copies + /// nothing, as plain Metal does where its validation stops the call. 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. + pub fn copy_from_texture( + &mut self, + source: &Texture, + from: TexturePlace, + size: [u32; 3], + destination: &Texture, + to: TexturePlace, + ) -> Result<(), Error> { + let building = self.building(); + let core = Arc::clone(building.device.core()); + if !source.is_of(&core) || !destination.is_of(&core) { + return Err(Error::Refused(Refusal::OtherDevice)); + } + let same = source.id() == destination.id(); + let sides = (Side::of(source), Side::of(destination)); + let Some(copy) = texture_copy(&sides.0, from, size, &sides.1, to, same)? else { + return Ok(()); + }; + building.keep_texture(source); + building.keep_texture(destination); + let command = building.ordered_command()?; + let (read, write) = ( + vk::ImageLayout::TRANSFER_SRC_OPTIMAL, + vk::ImageLayout::TRANSFER_DST_OPTIMAL, + ); + let earlier = [memory_barrier(Reach::Commands)]; + let away = [ + source.away(©.from, read, vk::AccessFlags2::TRANSFER_READ), + destination.away(©.to, write, vk::AccessFlags2::TRANSFER_WRITE), + ]; + let back = [ + source.back(©.from, read), + destination.back(©.to, write), + ]; + let regions = [vk::ImageCopy { + src_subresource: copy.from.layers(copy.aspect), + src_offset: copy.from.offset, + dst_subresource: copy.to.layers(copy.aspect), + dst_offset: copy.to.offset, + extent: copy.from.extent, + }]; + let device = &core.device; + // 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 the two are + // different subresources where the textures are one (`texture_copy`), in their transfer + // layouts between the barriers; the region lies in both. + unsafe { + device.cmd_pipeline_barrier2( + command, + &vk::DependencyInfo::default() + .memory_barriers(&earlier) + .image_memory_barriers(&away), + ); + device.cmd_copy_image( + command, + source.image(), + read, + destination.image(), + write, + ®ions, + ); + device.cmd_pipeline_barrier2( + command, + &vk::DependencyInfo::default().image_memory_barriers(&back), + ); + } + core.counters.count(Metric::Barriers); + core.counters.count(Metric::Barriers); + Ok(()) + } + + /// `endEncoding`. Each copy ordered itself, so the encoder owes no barrier. + pub fn end_encoding(mut self) { + self.end(); + } + + fn end(&mut self) { + if let Some(building) = self.building.take() { + self.command_buffer.close_encoder(building); + } + } +} + +impl Drop for BlitCommandEncoder { + fn drop(&mut self) { + self.end(); + } +} + +/// One texture of a copy: its descriptor, its image's format and the unit its copies move. +pub(crate) struct Side<'a> { + pub(crate) descriptor: &'a TextureDescriptor, + pub(crate) format: vk::Format, + pub(crate) unit: Option, +} + +impl<'a> Side<'a> { + fn of(texture: &'a Texture) -> Side<'a> { + Side { + descriptor: texture.descriptor(), + format: texture.format(), + unit: texture.unit(), + } + } +} + +/// A copy between two textures, checked: the region in each, and the aspect it copies. +#[derive(Debug, PartialEq, Eq)] +pub(crate) struct ImageCopy { + pub(crate) from: Placed, + pub(crate) to: Placed, + pub(crate) aspect: vk::ImageAspectFlags, +} + +/// Checks a copy of `size` texels from `from` in `source` to `to` in `destination`, `same` where +/// they are one texture. `None` where it copies nothing. +/// +/// Err: [`Refusal::TextureCopyMismatch`]; [`Gap::TextureCopy`]; [`Refusal::TextureRegion`]. +pub(crate) fn texture_copy( + source: &Side<'_>, + from: TexturePlace, + size: [u32; 3], + destination: &Side<'_>, + to: TexturePlace, + same: bool, +) -> Result, Error> { + let (s, d) = (source.descriptor, destination.descriptor); + let formats = (s.pixel_format, d.pixel_format); + let mismatch = || { + Error::Refused(Refusal::TextureCopyMismatch { + source: formats.0, + destination: formats.1, + }) + }; + let gap = || { + Error::Unsupported(Gap::TextureCopy { + source: formats.0, + destination: formats.1, + }) + }; + if s.sample_count != d.sample_count { + return Err(mismatch()); + } + // No unit: a multisample texture, or a format of depth and stencil both. + let (Some(unit), Some(other)) = (source.unit, destination.unit) else { + return Err(gap()); + }; + if unit.bytes != other.bytes { + return Err(mismatch()); + } + // Vulkan copies between color formats of one texel block's bytes and extent, an alpha format + // only with an alpha format, and a depth or stencil aspect only into the same aspect of the + // same format. + let alpha = |format| format == vk::Format::A8_UNORM_KHR; + let color = unit.aspect == vk::ImageAspectFlags::COLOR; + if unit.block != other.block + || unit.aspect != other.aspect + || (!color && source.format != destination.format) + || alpha(source.format) != alpha(destination.format) + { + return Err(gap()); + } + let one_d = |d: &TextureDescriptor| { + matches!( + d.texture_type, + TextureType::Type1D | TextureType::Type1DArray + ) + }; + let three_d = |d: &TextureDescriptor| d.texture_type == TextureType::Type3D; + // Vulkan 1.3 copies a 1D image only into a 1D image (`VUID-vkCmdCopyImage-srcImage-07743`). + if one_d(s) != one_d(d) { + return Err(gap()); + } + let mut size = size; + if size[1] == 0 && (one_d(s) || one_d(d)) { + size[1] = 1; + } + if size[2] == 0 && !(three_d(s) && three_d(d)) { + size[2] = 1; + } + let region = |place: TexturePlace| Region { + origin: place.origin, + size, + }; + let placed = ( + place(s, unit.block, region(from), from.level, from.slice)?, + place(d, other.block, region(to), to.level, to.slice)?, + ); + let (Some(from), Some(to)) = placed else { + return Ok(None); + }; + // One subresource is in one layout at a time. + if same && from.level == to.level && from.layer == to.layer { + return Err(gap()); + } + Ok(Some(ImageCopy { + from, + to, + aspect: unit.aspect, + })) +} diff --git a/crates/metal2vulkan-rt/src/command.rs b/crates/metal2vulkan-rt/src/command.rs index dce623be7..0fe5e744a 100644 --- a/crates/metal2vulkan-rt/src/command.rs +++ b/crates/metal2vulkan-rt/src/command.rs @@ -628,19 +628,36 @@ impl Building { /// The current segment's command buffer, with the barrier owed recorded first, reaching what /// the caller records next (`reach`). Commands after a signal go in a new segment. pub(crate) fn command(&mut self, reach: Reach) -> Result { - if !self.last().signals.is_empty() { - self.split()?; - } - let command = match self.last().command { - Some(command) => command, - None => self.begin()?, - }; + let command = self.current()?; if self.owed { self.barrier(command, reach); } Ok(command) } + /// The current segment's command buffer, for commands that record a barrier of their own + /// first that orders every earlier command before every later one and makes their writes + /// visible to them (a blit's): it pays what is owed, and the hazard sets start again. + pub(crate) fn ordered_command(&mut self) -> Result { + let command = self.current()?; + self.owed = false; + self.args_unordered = false; + self.hazards().clear(); + Ok(command) + } + + /// The current segment's command buffer, begun where it has none. Commands after a signal go + /// in a new segment. + fn current(&mut self) -> Result { + if !self.last().signals.is_empty() { + self.split()?; + } + match self.last().command { + Some(command) => Ok(command), + None => self.begin(), + } + } + /// Records a barrier into `command`, the current segment's, reaching what the caller records /// next (`reach`), and pays what is owed. The caller starts the hazard sets again where it /// has not. diff --git a/crates/metal2vulkan-rt/src/counters.rs b/crates/metal2vulkan-rt/src/counters.rs index 72bba1165..2402ff44f 100644 --- a/crates/metal2vulkan-rt/src/counters.rs +++ b/crates/metal2vulkan-rt/src/counters.rs @@ -232,15 +232,17 @@ impl Counters { pub struct Metrics { /// `vkQueueSubmit2` calls. pub submissions: u64, - /// Encoders recorded: compute, and later blit and render. + /// Encoders recorded: compute and blit, and later render. pub passes: u64, /// Pipeline-barrier commands recorded into command buffers' work: one at the end of each - /// segment with commands and of each upload, one before a dispatch at a hazard, and one owed - /// by an encoder that wrote or a memory barrier call, recorded before the next command. A - /// block's zero fill, made apart from any command buffer, is not counted. + /// segment with commands and of each upload, one before a dispatch at a hazard, one owed by + /// an encoder that wrote or a memory barrier call, recorded before the next command, and two + /// around each blit copy, the first of which pays what is owed. A block's zero fill, made + /// apart from any command buffer, is not counted. pub barriers: u64, /// Bytes the runtime copied for a call: `replace_region` and `get_bytes` staging, and the - /// counted copy at commit where a device offers no linear image. + /// counted copy at commit where a device offers no linear image. A blit's own copy is the + /// program's and is not counted. pub bytes_copied: u64, /// `VkPipeline`s created. pub pipelines_created: u64, diff --git a/crates/metal2vulkan-rt/src/error.rs b/crates/metal2vulkan-rt/src/error.rs index 93b90e923..b7fa10e06 100644 --- a/crates/metal2vulkan-rt/src/error.rs +++ b/crates/metal2vulkan-rt/src/error.rs @@ -117,13 +117,14 @@ pub enum Refusal { /// buffer", "Completed handler provided after commit call" and "Scheduled handler provided /// after commit call"). Committed, - /// An event, a buffer or a pipeline state of another device in an encode call + /// An event, a buffer, a texture or a pipeline state of another device in an encode call /// ([`CommandBuffer::encode_wait_for_event`](crate::CommandBuffer::encode_wait_for_event), /// [`CommandBuffer::encode_signal_event`](crate::CommandBuffer::encode_signal_event), or a - /// [`ComputeCommandEncoder`](crate::ComputeCommandEncoder) call). + /// [`ComputeCommandEncoder`](crate::ComputeCommandEncoder) or + /// [`BlitCommandEncoder`](crate::BlitCommandEncoder) call). /// - /// Basis: ours (an event's semaphore, a buffer's block and a pipeline belong to the - /// `VkDevice` that made them). + /// Basis: ours (an event's semaphore, a buffer's block, a texture's image and a pipeline + /// belong to the `VkDevice` that made them). OtherDevice, /// A queue that may hold no command buffer /// ([`Device::new_command_queue`](crate::Device::new_command_queue) with a count of 0). @@ -314,9 +315,11 @@ pub enum Refusal { /// Basis: metal-documented (Apple's documentation of `MTLStorageModePrivate`: "The resource is /// accessible only to the GPU."). TextureBytesPrivate, - /// [`Texture::replace_region`](crate::Texture::replace_region) or - /// [`Texture::get_bytes`](crate::Texture::get_bytes) of a level or slice past the texture's, - /// or of a region that leaves the level or is off the format's block grid. + /// [`Texture::replace_region`](crate::Texture::replace_region), + /// [`Texture::get_bytes`](crate::Texture::get_bytes) or a blit copy + /// ([`BlitCommandEncoder::copy_from_texture`](crate::BlitCommandEncoder::copy_from_texture)) + /// of a level or slice past the texture's, or of a region that leaves the level or is off the + /// format's block grid. /// /// Basis: ours (no texel of the texture is there to copy). TextureRegion { @@ -339,6 +342,21 @@ pub enum Refusal { /// The bytes given. len: u64, }, + /// [`BlitCommandEncoder::copy_from_texture`](crate::BlitCommandEncoder::copy_from_texture) + /// between formats whose copy units differ in bytes, or between textures of different + /// sample counts. Plain Metal completes such a copy, storing its GPU's own layout of the + /// texels or samples, which neither Metal nor Vulkan defines. + /// + /// Basis: metal-takes (an M4 and an Apple M3 Max, macOS 27.0.1: plain Metal completes the copy + /// with no error; between formats of different units the bytes follow the GPU's own texel + /// layout, and between sample counts its own twiddled or compressed sample layout, so there is + /// no defined answer to put in its place). + TextureCopyMismatch { + /// The source texture's pixel format. + source: PixelFormat, + /// The destination texture's pixel format. + destination: PixelFormat, + }, } /// A Metal feature the runtime does not build yet, with what it was asked. Each is refused until a @@ -440,6 +458,21 @@ pub enum Gap { /// The texture's pixel format. 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; a depth or stencil aspect with a color format or with another + /// format; a compressed format with a format of another block extent; an alpha-only image + /// (`A8Unorm` held as `A8_UNORM`) with another format; a 1D texture with one of another + /// type; or a region of one texture's level and slice into the same level and slice. + /// + /// Basis: ours (Vulkan 1.3 copies none of these with one command; each is built when a replay + /// stream makes one). + TextureCopy { + /// The source texture's pixel format. + source: PixelFormat, + /// The destination texture's pixel format. + destination: PixelFormat, + }, } /// A limit a call ran into, with what it was asked. @@ -695,6 +728,13 @@ impl fmt::Display for Refusal { f, "rows {bytes_per_row} and images {bytes_per_image} bytes apart in {len} bytes do not hold the region" ), + Refusal::TextureCopyMismatch { + source, + destination, + } => write!( + f, + "a copy from {source:?} to {destination:?} moves units of different bytes or samples, which Metal leaves undefined" + ), } } } @@ -737,6 +777,13 @@ impl fmt::Display for Gap { f, "bytes are not uploaded into the 32-bit float depth of this texture of {pixel_format:?}" ), + Gap::TextureCopy { + source, + destination, + } => write!( + f, + "this copy from a texture of {source:?} to one of {destination:?} is not built" + ), } } } diff --git a/crates/metal2vulkan-rt/src/lib.rs b/crates/metal2vulkan-rt/src/lib.rs index 9c64412c5..2971529b2 100644 --- a/crates/metal2vulkan-rt/src/lib.rs +++ b/crates/metal2vulkan-rt/src/lib.rs @@ -9,6 +9,7 @@ #![warn(missing_docs)] mod arrays; +mod blit; mod buffer; mod cache; mod command; @@ -40,6 +41,7 @@ mod texture; mod times; pub use arrays::{IndexClass, IndexGrant, ResourceId}; +pub use blit::{BlitCommandEncoder, TexturePlace}; pub use buffer::{Buffer, MAX_BUFFER_LENGTH}; pub use command::{CommandBuffer, CommandBufferError, CommandBufferStatus}; pub use counters::{Counters, Gauges, Metrics}; diff --git a/crates/metal2vulkan-rt/src/record.rs b/crates/metal2vulkan-rt/src/record.rs index c8d3171d5..7b0cf0a9b 100644 --- a/crates/metal2vulkan-rt/src/record.rs +++ b/crates/metal2vulkan-rt/src/record.rs @@ -51,9 +51,10 @@ impl Recorder { pub(crate) enum Reach { /// Within a segment: the dispatches after it after the dispatches before it, their shader /// reads and writes seeing the earlier shader writes, and where `indirect` (the dispatch that - /// follows it reads its arguments from a buffer), their indirect argument reads too. A - /// segment records nothing else that reads or writes memory, so it orders the segment's - /// commands as [`Reach::Commands`] would. + /// follows it reads its arguments from a buffer), their indirect argument reads too. The + /// other commands a segment records that read or write memory, blit copies, order + /// themselves against every command before and after them with barriers of their own, so it + /// orders the segment's commands as [`Reach::Commands`] would. Dispatches { indirect: bool }, /// Every later command, in this submission and every later one on the queue. Commands, @@ -76,6 +77,15 @@ impl Reach { /// barrier the runtime records for buffers: none names a buffer or a range. The caller counts it /// where it is part of the queues' work. pub(crate) fn barrier(device: &ash::Device, buffer: vk::CommandBuffer, reach: Reach) { + let barrier = [memory_barrier(reach)]; + let dependency = vk::DependencyInfo::default().memory_barriers(&barrier); + // SAFETY: the buffer is recording. + unsafe { device.cmd_pipeline_barrier2(buffer, &dependency) }; +} + +/// The global memory barrier [`barrier`] records for `reach`, for a caller that records it with +/// image barriers of its own in one command. +pub(crate) fn memory_barrier(reach: Reach) -> vk::MemoryBarrier2<'static> { let (source, written, stages, accesses) = match reach { Reach::Dispatches { indirect: false } => ( vk::PipelineStageFlags2::COMPUTE_SHADER, @@ -107,14 +117,11 @@ pub(crate) fn barrier(device: &ash::Device, buffer: vk::CommandBuffer, reach: Re | vk::AccessFlags2::HOST_WRITE, ), }; - let barrier = [vk::MemoryBarrier2::default() + vk::MemoryBarrier2::default() .src_stage_mask(source) .src_access_mask(written) .dst_stage_mask(stages) - .dst_access_mask(accesses)]; - let dependency = vk::DependencyInfo::default().memory_barriers(&barrier); - // SAFETY: the buffer is recording. - unsafe { device.cmd_pipeline_barrier2(buffer, &dependency) }; + .dst_access_mask(accesses) } /// Ends a segment's command buffer after its one barrier: a later command buffer's commands run diff --git a/crates/metal2vulkan-rt/src/tests/blit.rs b/crates/metal2vulkan-rt/src/tests/blit.rs new file mode 100644 index 000000000..9f159703e --- /dev/null +++ b/crates/metal2vulkan-rt/src/tests/blit.rs @@ -0,0 +1,777 @@ +//! Blit copies between textures. +//! +//! - The rules: formats whose units have the same bytes copy into each other; units of other +//! bytes, and other sample counts, are `Refusal::TextureCopyMismatch`; what one copy command in +//! the floor does not make is `Gap::TextureCopy`; 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. +//! - Under a device cfg, on every device of the cfg's kind: the bytes of a level of a 2D texture +//! land in a slice of a 2D array of another format of one unit's bytes, a cube's face in an +//! image of a 3D texture, an image of a 3D texture in a 2D texture, a slice of an array in +//! another slice of it, and a block-compressed region in another texture where the device makes +//! one, everything around each region kept. One copy alone is one submission, two barriers and +//! the segment's end, and copies no byte of the runtime's own; a barrier an encoder owed is paid +//! by the copy's first. Every gauge comes back to zero with the device. + +use crate::blit::{texture_copy, ImageCopy, Side, TexturePlace}; +use crate::error::{Error, Gap, Refusal}; +use crate::texture::{CopyUnit, Placed}; +use crate::{PixelFormat, TextureDescriptor, TextureType}; +use ash::vk; + +/// A side of a copy: a texture of `d` held in `format`, of `unit`. +fn side(d: &TextureDescriptor, format: vk::Format, unit: Option) -> Side<'_> { + Side { + descriptor: d, + format, + unit, + } +} + +fn color(bytes: u32) -> Option { + Some(CopyUnit { + aspect: vk::ImageAspectFlags::COLOR, + bytes, + block: [1, 1], + }) +} + +fn descriptor( + texture_type: TextureType, + format: PixelFormat, + extent: [u32; 3], +) -> TextureDescriptor { + let mut d = TextureDescriptor::new(texture_type, format, extent[0], extent[1]); + d.depth = extent[2]; + d +} + +fn at(slice: u32, level: u32, origin: [u32; 3]) -> TexturePlace { + TexturePlace { + slice, + level, + origin, + } +} + +fn placed(level: u32, layer: u32, offset: [i32; 3], extent: [u32; 3]) -> Placed { + Placed { + level, + layer, + offset: vk::Offset3D { + x: offset[0], + y: offset[1], + z: offset[2], + }, + extent: vk::Extent3D { + width: extent[0], + height: extent[1], + depth: extent[2], + }, + } +} + +fn refused(result: Result) -> Refusal { + match result { + Err(Error::Refused(refusal)) => refusal, + other => panic!("not a refusal: {other:?}"), + } +} + +fn gap(result: Result) -> Gap { + match result { + Err(Error::Unsupported(gap)) => gap, + other => panic!("not a gap: {other:?}"), + } +} + +#[test] +fn a_copy_takes_formats_of_one_units_bytes_and_places_both_regions() { + let mut rgba = descriptor(TextureType::Type2D, PixelFormat::RGBA8Unorm, [13, 7, 1]); + rgba.mipmap_level_count = 3; + let mut words = descriptor(TextureType::Type2DArray, PixelFormat::R32Uint, [8, 8, 1]); + words.array_length = 3; + let source = side(&rgba, vk::Format::R8G8B8A8_UNORM, color(4)); + let destination = side(&words, vk::Format::R32_UINT, color(4)); + let copy = texture_copy( + &source, + at(0, 1, [1, 0, 0]), + [4, 3, 1], + &destination, + at(2, 0, [2, 4, 0]), + false, + ) + .expect("a copy"); + assert_eq!( + copy, + Some(ImageCopy { + from: placed(1, 0, [1, 0, 0], [4, 3, 1]), + to: placed(0, 2, [2, 4, 0], [4, 3, 1]), + aspect: vk::ImageAspectFlags::COLOR, + }) + ); + // A depth of 0 on 2D textures copies one image; a width of 0 copies nothing. + let flat = texture_copy( + &source, + at(0, 0, [0; 3]), + [2, 2, 0], + &destination, + at(0, 0, [0; 3]), + false, + ) + .expect("a copy") + .expect("one image"); + assert_eq!(flat.from.extent.depth, 1); + assert_eq!( + texture_copy( + &source, + at(0, 0, [0; 3]), + [0, 2, 1], + &destination, + at(0, 0, [0; 3]), + false + ) + .expect("nothing"), + None + ); + // A level, a slice or a region past either texture. + for (from, to, size) in [ + (at(0, 3, [0; 3]), at(0, 0, [0; 3]), [1, 1, 1]), + (at(0, 0, [0; 3]), at(3, 0, [0; 3]), [1, 1, 1]), + (at(0, 1, [3, 0, 0]), at(0, 0, [0; 3]), [4, 1, 1]), + (at(0, 0, [0; 3]), at(0, 0, [6, 0, 0]), [4, 1, 1]), + ] { + assert!( + matches!( + refused(texture_copy(&source, from, size, &destination, to, false)), + Refusal::TextureRegion { .. } + ), + "{from:?} {to:?} {size:?}" + ); + } +} + +#[test] +fn a_3d_image_copies_to_and_from_a_2d_slice_and_a_cube_face_is_its_slice() { + let volume = descriptor(TextureType::Type3D, PixelFormat::R8Unorm, [4, 4, 3]); + let plane = descriptor(TextureType::Type2D, PixelFormat::R8Unorm, [4, 4, 1]); + let cube = descriptor(TextureType::Cube, PixelFormat::R8Unorm, [4, 4, 1]); + let (v, p, c) = ( + side(&volume, vk::Format::R8_UNORM, color(1)), + side(&plane, vk::Format::R8_UNORM, color(1)), + side(&cube, vk::Format::R8_UNORM, color(1)), + ); + let copy = texture_copy( + &v, + at(0, 0, [1, 1, 2]), + [2, 2, 1], + &p, + at(0, 0, [2, 0, 0]), + false, + ) + .expect("a copy") + .expect("one image"); + assert_eq!(copy.from, placed(0, 0, [1, 1, 2], [2, 2, 1])); + assert_eq!(copy.to, placed(0, 0, [2, 0, 0], [2, 2, 1])); + let copy = texture_copy( + &c, + at(4, 0, [0; 3]), + [4, 4, 1], + &v, + at(0, 0, [0, 0, 1]), + false, + ) + .expect("a copy") + .expect("a face"); + assert_eq!(copy.from, placed(0, 4, [0; 3], [4, 4, 1])); + assert_eq!(copy.to, placed(0, 0, [0, 0, 1], [4, 4, 1])); + // Two images of a 3D texture do not fit one 2D slice. + assert!(matches!( + refused(texture_copy( + &v, + at(0, 0, [0; 3]), + [4, 4, 2], + &p, + at(0, 0, [0; 3]), + false + )), + Refusal::TextureRegion { .. } + )); + // One texture's two slices copy; one slice into itself is not built. + let mut array = descriptor(TextureType::Type2DArray, PixelFormat::R8Unorm, [4, 4, 1]); + array.array_length = 2; + let a = side(&array, vk::Format::R8_UNORM, color(1)); + assert!(texture_copy( + &a, + at(0, 0, [0; 3]), + [2, 2, 1], + &a, + at(1, 0, [2, 2, 0]), + true + ) + .expect("a copy") + .is_some()); + assert_eq!( + gap(texture_copy( + &a, + at(0, 0, [0; 3]), + [2, 2, 1], + &a, + at(0, 0, [2, 2, 0]), + true + )), + Gap::TextureCopy { + source: PixelFormat::R8Unorm, + destination: PixelFormat::R8Unorm + } + ); +} + +#[test] +fn what_metal_leaves_undefined_is_refused_and_what_one_command_does_not_make_is_a_gap() { + let d = |format, extent| descriptor(TextureType::Type2D, format, extent); + let rgba = d(PixelFormat::RGBA8Unorm, [8, 8, 1]); + let rg = d(PixelFormat::RG8Unorm, [8, 8, 1]); + let bc1 = d(PixelFormat::BC1RGBA, [8, 8, 1]); + let rg32 = d(PixelFormat::RG32Uint, [8, 8, 1]); + let depth = d(PixelFormat::Depth32Float, [8, 8, 1]); + let r32 = d(PixelFormat::R32Float, [8, 8, 1]); + let alpha = d(PixelFormat::A8Unorm, [8, 8, 1]); + let r8 = d(PixelFormat::R8Unorm, [8, 8, 1]); + let line = descriptor(TextureType::Type1D, PixelFormat::R8Unorm, [8, 1, 1]); + let mut msaa = descriptor( + TextureType::Type2DMultisample, + PixelFormat::RGBA8Unorm, + [8, 8, 1], + ); + msaa.sample_count = 4; + let whole = |source: &Side<'_>, destination: &Side<'_>| { + texture_copy( + source, + at(0, 0, [0; 3]), + [8, 1, 1], + destination, + at(0, 0, [0; 3]), + false, + ) + }; + let rgba = side(&rgba, vk::Format::R8G8B8A8_UNORM, color(4)); + let bc1 = side( + &bc1, + vk::Format::BC1_RGBA_UNORM_BLOCK, + Some(CopyUnit { + aspect: vk::ImageAspectFlags::COLOR, + bytes: 8, + block: [4, 4], + }), + ); + let depth = side( + &depth, + vk::Format::D32_SFLOAT, + Some(CopyUnit { + aspect: vk::ImageAspectFlags::DEPTH, + bytes: 4, + block: [1, 1], + }), + ); + let mismatch = |source, destination| Refusal::TextureCopyMismatch { + source, + destination, + }; + let not_built = |source, destination| Gap::TextureCopy { + source, + destination, + }; + assert_eq!( + refused(whole(&rgba, &side(&rg, vk::Format::R8G8_UNORM, color(2)))), + mismatch(PixelFormat::RGBA8Unorm, PixelFormat::RG8Unorm) + ); + assert_eq!( + refused(whole(&side(&msaa, vk::Format::R8G8B8A8_UNORM, None), &rgba)), + mismatch(PixelFormat::RGBA8Unorm, PixelFormat::RGBA8Unorm) + ); + let msaa = side(&msaa, vk::Format::R8G8B8A8_UNORM, None); + assert_eq!( + gap(whole(&msaa, &msaa)), + not_built(PixelFormat::RGBA8Unorm, PixelFormat::RGBA8Unorm) + ); + assert_eq!( + gap(whole(&bc1, &side(&rg32, vk::Format::R32G32_UINT, color(8)))), + not_built(PixelFormat::BC1RGBA, PixelFormat::RG32Uint) + ); + assert_eq!( + gap(whole(&depth, &side(&r32, vk::Format::R32_SFLOAT, color(4)))), + not_built(PixelFormat::Depth32Float, PixelFormat::R32Float) + ); + assert_eq!( + gap(whole( + &side(&alpha, vk::Format::A8_UNORM_KHR, color(1)), + &side(&r8, vk::Format::R8_UNORM, color(1)) + )), + not_built(PixelFormat::A8Unorm, PixelFormat::R8Unorm) + ); + // `A8Unorm` held in `R8_UNORM` copies as its byte. + assert!(whole( + &side(&alpha, vk::Format::R8_UNORM, color(1)), + &side(&r8, vk::Format::R8_UNORM, color(1)) + ) + .expect("a copy") + .is_some()); + assert_eq!( + gap(whole( + &side(&line, vk::Format::R8_UNORM, color(1)), + &side(&r8, vk::Format::R8_UNORM, color(1)) + )), + not_built(PixelFormat::R8Unorm, PixelFormat::R8Unorm) + ); + // A compressed region is whole blocks or reaches the level's edge on both sides. + assert!(texture_copy( + &bc1, + at(0, 0, [4, 0, 0]), + [4, 4, 1], + &bc1, + at(0, 0, [0, 4, 0]), + false + ) + .expect("a copy") + .is_some()); + assert!(matches!( + refused(texture_copy( + &bc1, + at(0, 0, [0; 3]), + [2, 4, 1], + &bc1, + at(0, 0, [0; 3]), + false + )), + Refusal::TextureRegion { .. } + )); + let mut chain = descriptor(TextureType::Type2D, PixelFormat::BC1RGBA, [8, 8, 1]); + chain.mipmap_level_count = 4; + let chain = side(&chain, vk::Format::BC1_RGBA_UNORM_BLOCK, bc1.unit); + // Level 2 is 2 x 2 texels, inside one block: its edge, but not the destination's. + assert!(texture_copy( + &chain, + at(0, 2, [0; 3]), + [2, 2, 1], + &chain, + at(0, 3, [0; 3]), + false + ) + .is_err()); + assert!(matches!( + refused(texture_copy( + &chain, + at(0, 2, [0; 3]), + [2, 2, 1], + &bc1, + at(0, 0, [0; 3]), + false + )), + Refusal::TextureRegion { .. } + )); +} + +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod on_device { + use crate::tests::command::on_device::{each_device, finished}; + use crate::{ + CommandBuffer, Device, DispatchType, Error, Gap, IndexClass, PixelFormat, Refusal, Region, + StorageMode, Texture, TextureDescriptor, TexturePlace, TextureType, TextureUsage, + }; + + /// A byte pattern of `len` bytes, different at every offset of one call and between calls. + fn pattern(len: usize, seed: u8) -> Vec { + (0..len) + .map(|i| (i as u8).wrapping_mul(31).wrapping_add(seed)) + .collect() + } + + /// One level and slice of a texture, whole, in elements of `unit` bytes covering `block` + /// texels square. + struct Level<'a> { + texture: &'a Texture, + slice: u32, + level: u32, + unit: usize, + block: u32, + } + + impl Level<'_> { + fn extent(&self) -> [u32; 3] { + let d = self.texture.descriptor(); + [d.width, d.height, d.depth].map(|e| (e >> self.level).max(1)) + } + + /// Elements across, rows and images. + fn grid(&self) -> [usize; 3] { + let [w, h, d] = self.extent(); + [ + w.div_ceil(self.block) as usize, + h.div_ceil(self.block) as usize, + d as usize, + ] + } + + fn layout(&self) -> (Region, u64, u64, usize) { + let [across, rows, images] = self.grid(); + let row = across * self.unit; + let region = Region { + origin: [0; 3], + size: self.extent(), + }; + (region, row as u64, (row * rows) as u64, row * rows * images) + } + + /// Writes a pattern of `seed` over the whole level and slice, and returns it. + fn write(&self, seed: u8) -> Vec { + let (region, row, image, len) = self.layout(); + let bytes = pattern(len, seed); + self.texture + .replace_region(region, self.level, self.slice, &bytes, row, image) + .expect("replace_region"); + bytes + } + + fn read(&self) -> Vec { + let (region, row, image, len) = self.layout(); + let mut bytes = vec![0; len]; + self.texture + .get_bytes(&mut bytes, row, image, region, self.level, self.slice) + .expect("get_bytes"); + bytes + } + + /// The place of element `at` in Metal's terms. + fn place(&self, at: [usize; 3]) -> TexturePlace { + let b = self.block as usize; + TexturePlace { + slice: self.slice, + level: self.level, + origin: [(at[0] * b) as u32, (at[1] * b) as u32, at[2] as u32], + } + } + } + + /// One copy of `size` elements, from `at` in `from`, whose bytes are `source`, to `to_at` in + /// `to`, whose bytes are `before`: the bytes `to` must hold after it. + struct Expect<'a> { + from: &'a Level<'a>, + source: &'a [u8], + at: [usize; 3], + to: &'a Level<'a>, + before: Vec, + to_at: [usize; 3], + size: [usize; 3], + } + + impl Expect<'_> { + fn record(&self, name: &str, command_buffer: &CommandBuffer) { + let mut encoder = command_buffer.blit_command_encoder().expect("an encoder"); + let b = self.from.block as usize; + let texels = [self.size[0] * b, self.size[1] * b, self.size[2]].map(|n| n as u32); + // A compressed level smaller than a block copies the texels it has. + let extent = self.from.extent(); + let texels = std::array::from_fn(|axis| texels[axis].min(extent[axis])); + encoder + .copy_from_texture( + self.from.texture, + self.from.place(self.at), + texels, + self.to.texture, + self.to.place(self.to_at), + ) + .unwrap_or_else(|error| panic!("{name}: {error}")); + encoder.end_encoding(); + } + + /// The destination's bytes after the copy. + fn after(&self) -> Vec { + let (from, to) = (self.from.grid(), self.to.grid()); + let unit = self.from.unit; + let mut bytes = self.before.clone(); + for z in 0..self.size[2] { + for y in 0..self.size[1] { + let element = |grid: [usize; 3], at: [usize; 3]| { + ((at[2] + z) * grid[1] + at[1] + y) * grid[0] + at[0] + }; + let (s, d) = ( + element(from, self.at) * unit, + element(to, self.to_at) * unit, + ); + let len = self.size[0] * unit; + bytes[d..d + len].copy_from_slice(&self.source[s..s + len]); + } + } + bytes + } + } + + fn texture( + device: &Device, + texture_type: TextureType, + format: PixelFormat, + extent: [u32; 3], + usage: TextureUsage, + index: u32, + ) -> Result { + let mut d = TextureDescriptor::new(texture_type, format, extent[0], extent[1]); + d.depth = extent[2]; + d.usage = usage; + d.storage_mode = StorageMode::Shared; + if matches!(texture_type, TextureType::Type2DArray) { + d.array_length = 3; + } + if texture_type == TextureType::Type2D && format == PixelFormat::RGBA8Unorm { + d.mipmap_level_count = 3; + } + device.new_texture(&d, Some(index)) + } + + /// Bytes land where each copy names, everything around them kept; one copy alone costs one + /// submission and three barriers and copies nothing of the runtime's own; an owed barrier is + /// paid by the copy's first. + #[test] + fn every_device_copies_between_textures() { + each_device("blit_textures", |name, _, device| { + device + .grant_indices(IndexClass::Texture, 4096, 16) + .expect("a grant"); + device + .grant_indices(IndexClass::StorageTexture, 1, 16) + .expect("a grant"); + let read = TextureUsage::SHADER_READ; + let write = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; + let make = |texture_type, format, extent, usage, index| { + texture(&device, texture_type, format, extent, usage, index) + .unwrap_or_else(|error| panic!("{name}: {format:?}: {error}")) + }; + let rgba = make( + TextureType::Type2D, + PixelFormat::RGBA8Unorm, + [13, 7, 1], + read, + 4096, + ); + let words = make( + TextureType::Type2DArray, + PixelFormat::R32Uint, + [8, 8, 1], + write, + 1, + ); + let cube = make( + TextureType::Cube, + PixelFormat::R8Unorm, + [4, 4, 1], + read, + 4097, + ); + let volume = make( + TextureType::Type3D, + PixelFormat::R8Unorm, + [4, 4, 3], + read, + 4098, + ); + let plane = make( + TextureType::Type2D, + PixelFormat::R8Unorm, + [4, 4, 1], + read, + 4099, + ); + let level = |texture, slice, level, unit| Level { + texture, + slice, + level, + unit, + block: 1, + }; + let (rgba1, words2) = (level(&rgba, 0, 1, 4), level(&words, 2, 0, 4)); + let (words0, words1) = (level(&words, 0, 0, 4), level(&words, 1, 0, 4)); + let (face, image) = (level(&cube, 4, 0, 1), level(&volume, 0, 0, 1)); + let flat = level(&plane, 0, 0, 1); + let sources = [rgba1.write(1), face.write(2), words0.write(3)]; + let befores = [ + words2.write(4), + image.write(5), + flat.write(6), + words1.write(7), + ]; + let queue = device.new_command_queue(4).expect("a queue"); + // The textures' uploads go with a command buffer of their own. + let first = queue.command_buffer().expect("a command buffer"); + first.commit().expect("a commit"); + finished(name, &first); + + // A level of a 2D texture into a slice of an array of another format. + let into_array = Expect { + from: &rgba1, + source: &sources[0], + at: [1, 0, 0], + to: &words2, + before: befores[0].clone(), + to_at: [2, 4, 0], + size: [4, 3, 1], + }; + let counters = device.counters(); + let before = counters.metrics(); + let command_buffer = queue.command_buffer().expect("a command buffer"); + into_array.record(name, &command_buffer); + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + assert_eq!(command_buffer.error(), None, "{name}"); + let after = counters.metrics(); + assert_eq!( + ( + after.submissions - before.submissions, + after.barriers - before.barriers, + after.bytes_copied - before.bytes_copied, + after.passes - before.passes, + ), + (1, 3, 0, 1), + "{name}: submissions, barriers, bytes copied, passes" + ); + assert_eq!(words2.read(), into_array.after(), "{name}: into the array"); + + // A cube's face into a 3D image, a 3D image into a 2D texture, and a slice of an + // array into another of it, in one encoder; then a barrier an encoder owed, paid by + // a copy's first. + let into_volume = Expect { + from: &face, + source: &sources[1], + at: [0, 0, 0], + to: &image, + before: befores[1].clone(), + to_at: [0, 0, 1], + size: [4, 4, 1], + }; + let volume_after = into_volume.after(); + let into_plane = Expect { + from: &image, + source: &volume_after, + at: [1, 1, 1], + to: &flat, + before: befores[2].clone(), + to_at: [2, 0, 0], + size: [2, 2, 1], + }; + let across = Expect { + from: &words0, + source: &sources[2], + at: [0, 0, 0], + to: &words1, + before: befores[3].clone(), + to_at: [3, 3, 0], + size: [5, 5, 1], + }; + let command_buffer = queue.command_buffer().expect("a command buffer"); + for copy in [&into_volume, &into_plane, &across] { + copy.record(name, &command_buffer); + } + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + assert_eq!(command_buffer.error(), None, "{name}"); + assert_eq!(image.read(), volume_after, "{name}: into the volume"); + assert_eq!(flat.read(), into_plane.after(), "{name}: into the plane"); + assert_eq!(words1.read(), across.after(), "{name}: across slices"); + + let before = counters.metrics(); + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut compute = command_buffer + .compute_command_encoder(DispatchType::Serial) + .expect("an encoder"); + compute.memory_barrier(); + assert!(matches!( + command_buffer.blit_command_encoder(), + Err(Error::Refused(Refusal::EncoderOpen)) + )); + compute.end_encoding(); + into_array.record(name, &command_buffer); + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + let after = counters.metrics(); + assert_eq!( + after.barriers - before.barriers, + 3, + "{name}: the owed barrier" + ); + + // A block-compressed region, where the device makes the format. + let bc = |index| { + texture( + &device, + TextureType::Type2D, + PixelFormat::BC1RGBA, + [8, 8, 1], + read, + index, + ) + }; + match (bc(4100), bc(4101)) { + (Ok(a), Ok(b)) => { + let (from, to) = ( + Level { + texture: &a, + slice: 0, + level: 0, + unit: 8, + block: 4, + }, + Level { + texture: &b, + slice: 0, + level: 0, + unit: 8, + block: 4, + }, + ); + let source = from.write(8); + let blocks = Expect { + from: &from, + source: &source, + at: [1, 0, 0], + to: &to, + before: to.write(9), + to_at: [0, 1, 0], + size: [1, 1, 1], + }; + let command_buffer = queue.command_buffer().expect("a command buffer"); + blocks.record(name, &command_buffer); + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + assert_eq!(to.read(), blocks.after(), "{name}: BC1 blocks"); + } + (Err(Error::Unsupported(Gap::TextureFormat { .. })), _) => { + println!("{name}: no BC1 texture on this device") + } + (a, b) => panic!("{name}: BC1: {:?} {:?}", a.err(), b.err()), + } + + // A slice past the array is refused, and the encoder goes on. + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = command_buffer.blit_command_encoder().expect("an encoder"); + let past = TexturePlace { + slice: 3, + level: 0, + origin: [0; 3], + }; + assert!(matches!( + encoder.copy_from_texture(&words, past, [1, 1, 1], &plane, TexturePlace::default()), + Err(Error::Refused(Refusal::TextureRegion { + level: 0, + slice: 3 + })) + )); + encoder.end_encoding(); + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + assert!(matches!( + command_buffer.blit_command_encoder(), + Err(Error::Refused(Refusal::Committed)) + )); + }); + } +} diff --git a/crates/metal2vulkan-rt/src/tests/mod.rs b/crates/metal2vulkan-rt/src/tests/mod.rs index 05e8aab7f..946ce4376 100644 --- a/crates/metal2vulkan-rt/src/tests/mod.rs +++ b/crates/metal2vulkan-rt/src/tests/mod.rs @@ -1,4 +1,5 @@ mod arrays; +mod blit; mod cache; mod command; mod compute; diff --git a/crates/metal2vulkan-rt/src/texture.rs b/crates/metal2vulkan-rt/src/texture.rs index 4db15e924..2f1450f0e 100644 --- a/crates/metal2vulkan-rt/src/texture.rs +++ b/crates/metal2vulkan-rt/src/texture.rs @@ -133,7 +133,10 @@ struct TextureInner { device: Device, descriptor: TextureDescriptor, image: Arc, - /// How bytes move between the image and the CPU; `None` where no copy is built. + /// The image's format. + format: vk::Format, + /// How bytes move between the image and the CPU or another image; `None` where no copy is + /// built. unit: Option, /// Its class and index; `None` for a texture no shader reaches. index: Option<(IndexClass, u32)>, @@ -205,13 +208,13 @@ pub(crate) enum Backing { Own(vk::DeviceMemory), } -/// The unit of a copy between an image and bytes: the aspect, an element's bytes and the texels -/// an element covers. -#[derive(Clone, Copy)] -struct CopyUnit { - aspect: vk::ImageAspectFlags, - bytes: u32, - block: [u32; 2], +/// The unit of a copy between an image and bytes or another image: the aspect, an element's +/// bytes and the texels an element covers. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct CopyUnit { + pub(crate) aspect: vk::ImageAspectFlags, + pub(crate) bytes: u32, + pub(crate) block: [u32; 2], } impl CopyUnit { @@ -347,6 +350,7 @@ impl Device { device: self.clone(), descriptor: d, image, + format: plan.format, unit: plan.unit, index, word: plan.word, @@ -818,15 +822,90 @@ impl Made { } } +/// A region of one level and slice of a texture, checked against the texture. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Placed { + pub(crate) level: u32, + /// The image's array layer: the slice, 0 for a 3D texture. + pub(crate) layer: u32, + pub(crate) offset: vk::Offset3D, + pub(crate) extent: vk::Extent3D, +} + +impl Placed { + /// Its level and layer in `aspect`, for a copy command. + pub(crate) fn layers(&self, aspect: vk::ImageAspectFlags) -> vk::ImageSubresourceLayers { + vk::ImageSubresourceLayers { + aspect_mask: aspect, + mip_level: self.level, + base_array_layer: self.layer, + layer_count: 1, + } + } +} + +/// Checks `region` of `level` and `slice` of a texture of `d` whose copy unit covers `block` +/// texels: the level and slice are the texture's (a cube's slices are six a cube, a 3D texture +/// has slice 0 alone), and the region lies inside the level, its origin on the block grid and its +/// size whole blocks or reaching the level's edge. `None` for an empty region. +/// +/// Err: [`Refusal::TextureRegion`]. +pub(crate) fn place( + d: &TextureDescriptor, + block: [u32; 2], + region: Region, + level: u32, + slice: u32, +) -> Result, Error> { + let outside = || Error::Refused(Refusal::TextureRegion { level, slice }); + let three_d = d.texture_type == TextureType::Type3D; + let slices = match d.texture_type { + TextureType::Cube | TextureType::CubeArray => d.array_length * 6, + _ => d.array_length, + }; + if level >= d.mipmap_level_count || slice >= slices { + return Err(outside()); + } + let extent = [d.width, d.height, d.depth].map(|e| (e >> level).max(1)); + let [bw, bh] = block; + let block = [bw, bh, 1]; + for axis in 0..3 { + let (origin, size) = (region.origin[axis], region.size[axis]); + let end = origin.checked_add(size).ok_or_else(outside)?; + let on_grid = origin % block[axis] == 0 && (size % block[axis] == 0 || end == extent[axis]); + if end > extent[axis] || !on_grid { + return Err(outside()); + } + } + if region.size.contains(&0) { + return Ok(None); + } + let [x, y, z] = region.origin; + let [width, height, depth] = region.size; + Ok(Some(Placed { + level, + layer: match three_d { + true => 0, + false => slice, + }, + offset: vk::Offset3D { + x: x as i32, + y: y as i32, + z: z as i32, + }, + extent: vk::Extent3D { + width, + height, + depth, + }, + })) +} + /// A copy between the texture and bytes, checked: the subresource, the region and how its rows /// lie in the bytes. struct Transfer { unit: CopyUnit, - level: u32, - /// The array layer; 0 for a 3D texture. - layer: u32, - offset: vk::Offset3D, - extent: vk::Extent3D, + placed: Placed, /// One row of elements' bytes. row: u64, /// Rows of elements in an image. @@ -869,14 +948,9 @@ impl Transfer { buffer_offset: offset, buffer_row_length: 0, buffer_image_height: 0, - image_subresource: vk::ImageSubresourceLayers { - aspect_mask: self.unit.aspect, - mip_level: self.level, - base_array_layer: self.layer, - layer_count: 1, - }, - image_offset: self.offset, - image_extent: self.extent, + image_subresource: self.placed.layers(self.unit.aspect), + image_offset: self.placed.offset, + image_extent: self.placed.extent, } } } @@ -903,30 +977,10 @@ impl TextureInner { let unit = self.unit.ok_or(Error::Unsupported(Gap::TextureBytes { pixel_format: d.pixel_format, }))?; - let outside = || Error::Refused(Refusal::TextureRegion { level, slice }); - let three_d = d.texture_type == TextureType::Type3D; - let slices = match d.texture_type { - TextureType::Cube | TextureType::CubeArray => d.array_length * 6, - _ => d.array_length, - }; - if level >= d.mipmap_level_count || slice >= slices { - return Err(outside()); - } - let extent = [d.width, d.height, d.depth].map(|e| (e >> level).max(1)); - let [bw, bh] = unit.block; - let block = [bw, bh, 1]; - for axis in 0..3 { - let (origin, size) = (region.origin[axis], region.size[axis]); - let end = origin.checked_add(size).ok_or_else(outside)?; - let on_grid = - origin % block[axis] == 0 && (size % block[axis] == 0 || end == extent[axis]); - if end > extent[axis] || !on_grid { - return Err(outside()); - } - } - if region.size.contains(&0) { + let Some(placed) = place(d, unit.block, region, level, slice)? else { return Ok(None); - } + }; + let [bw, bh] = unit.block; let [width, height, depth] = region.size; let row = u64::from(width.div_ceil(bw)) * u64::from(unit.bytes); let rows = u64::from(height.div_ceil(bh)); @@ -949,24 +1003,9 @@ impl TextureInner { len, })); } - let [x, y, z] = region.origin; Ok(Some(Transfer { unit, - level, - layer: match three_d { - true => 0, - false => slice, - }, - offset: vk::Offset3D { - x: x as i32, - y: y as i32, - z: z as i32, - }, - extent: vk::Extent3D { - width, - height, - depth, - }, + placed, row, rows, images, @@ -975,6 +1014,62 @@ impl TextureInner { })) } + /// The barrier that moves `placed`'s level and layer, every aspect, from home to `layout` + /// (a transfer layout) for a copy's `access` (its reads or its writes), after every earlier + /// command's writes. + fn away( + &self, + placed: &Placed, + layout: vk::ImageLayout, + access: vk::AccessFlags2, + ) -> vk::ImageMemoryBarrier2<'static> { + use vk::AccessFlags2 as Access; + use vk::PipelineStageFlags2 as Stage; + self.barrier(placed, self.image.home, layout) + .src_stage_mask(Stage::ALL_COMMANDS) + .src_access_mask(Access::MEMORY_WRITE) + .dst_stage_mask(Stage::COPY) + .dst_access_mask(access) + } + + /// The barrier that moves `placed`'s level and layer back home from `layout` once a copy has + /// run, its writes (into `TRANSFER_DST_OPTIMAL`) visible to every later command. + fn back(&self, placed: &Placed, layout: vk::ImageLayout) -> vk::ImageMemoryBarrier2<'static> { + use vk::AccessFlags2 as Access; + use vk::PipelineStageFlags2 as Stage; + let written = match layout { + vk::ImageLayout::TRANSFER_DST_OPTIMAL => Access::TRANSFER_WRITE, + _ => Access::NONE, + }; + self.barrier(placed, layout, self.image.home) + .src_stage_mask(Stage::COPY) + .src_access_mask(written) + .dst_stage_mask(Stage::ALL_COMMANDS) + .dst_access_mask(Access::MEMORY_READ | Access::MEMORY_WRITE) + } + + /// A layout change of `placed`'s level and layer, every aspect, with no scopes yet. + fn barrier( + &self, + placed: &Placed, + old: vk::ImageLayout, + new: vk::ImageLayout, + ) -> vk::ImageMemoryBarrier2<'static> { + vk::ImageMemoryBarrier2::default() + .old_layout(old) + .new_layout(new) + .src_queue_family_index(vk::QUEUE_FAMILY_IGNORED) + .dst_queue_family_index(vk::QUEUE_FAMILY_IGNORED) + .image(self.image.image) + .subresource_range(vk::ImageSubresourceRange { + aspect_mask: self.image.aspects, + base_mip_level: placed.level, + level_count: 1, + base_array_layer: placed.layer, + layer_count: 1, + }) + } + /// Records `copy` between its staging and the image, `to_image` for a replace: the /// subresource leaves home for the transfer layout and comes back, and a read's bytes are /// made visible to the host. @@ -999,46 +1094,8 @@ impl TextureInner { ), false => (vk::ImageLayout::TRANSFER_SRC_OPTIMAL, Access::TRANSFER_READ), }; - let range = vk::ImageSubresourceRange { - aspect_mask: self.image.aspects, - base_mip_level: copy.level, - level_count: 1, - base_array_layer: copy.layer, - layer_count: 1, - }; - let barrier = |old, new, src: (Stage, Access), dst: (Stage, Access)| { - vk::ImageMemoryBarrier2::default() - .src_stage_mask(src.0) - .src_access_mask(src.1) - .dst_stage_mask(dst.0) - .dst_access_mask(dst.1) - .old_layout(old) - .new_layout(new) - .src_queue_family_index(vk::QUEUE_FAMILY_IGNORED) - .dst_queue_family_index(vk::QUEUE_FAMILY_IGNORED) - .image(self.image.image) - .subresource_range(range) - }; - let anything = ( - Stage::ALL_COMMANDS, - Access::MEMORY_READ | Access::MEMORY_WRITE, - ); - let away = [barrier( - self.image.home, - layout, - (Stage::ALL_COMMANDS, Access::MEMORY_WRITE), - (Stage::COPY, access), - )]; - let written = match to_image { - true => Access::TRANSFER_WRITE, - false => Access::NONE, - }; - let home = [barrier( - layout, - self.image.home, - (Stage::COPY, written), - anything, - )]; + let away = [self.away(©.placed, layout, access)]; + let home = [self.back(©.placed, layout)]; let host = [vk::MemoryBarrier2::default() .src_stage_mask(Stage::COPY) .src_access_mask(Access::TRANSFER_WRITE) @@ -1088,6 +1145,42 @@ impl Texture { Arc::ptr_eq(self.inner.device.core(), core) } + /// Its image. + pub(crate) fn image(&self) -> vk::Image { + self.inner.image.image + } + + /// Its image's format. + pub(crate) fn format(&self) -> vk::Format { + self.inner.format + } + + /// The unit its copies move; `None` where no copy is built. + pub(crate) fn unit(&self) -> Option { + self.inner.unit + } + + /// The barrier that moves `placed` from home to the transfer `layout` for a copy's + /// `access`, after every earlier command's writes. + pub(crate) fn away( + &self, + placed: &Placed, + layout: vk::ImageLayout, + access: vk::AccessFlags2, + ) -> vk::ImageMemoryBarrier2<'static> { + self.inner.away(placed, layout, access) + } + + /// The barrier that moves `placed` back home from the transfer `layout` once a copy has run, + /// its writes visible to every later command. + pub(crate) fn back( + &self, + placed: &Placed, + layout: vk::ImageLayout, + ) -> vk::ImageMemoryBarrier2<'static> { + self.inner.back(placed, layout) + } + /// `gpuResourceID`: its index (0 for a texture no shader reaches) and the translator's /// `TextureWord` of its pixel format and swizzle. pub fn gpu_resource_id(&self) -> ResourceId { diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index b5e70a8a0..10877c011 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2312,6 +2312,9 @@ field metal2vulkan-rt::TextureDescriptor.swizzle pub swizzle: TextureSwizzleChan field metal2vulkan-rt::TextureDescriptor.texture_type pub texture_type: TextureType field metal2vulkan-rt::TextureDescriptor.usage pub usage: TextureUsage field metal2vulkan-rt::TextureDescriptor.width pub width: u32 +field metal2vulkan-rt::TexturePlace.level pub level: u32 +field metal2vulkan-rt::TexturePlace.origin pub origin: [u32; 3] +field metal2vulkan-rt::TexturePlace.slice pub slice: u32 field metal2vulkan-rt::TextureSwizzleChannels.alpha pub alpha: TextureSwizzle field metal2vulkan-rt::TextureSwizzleChannels.blue pub blue: TextureSwizzle field metal2vulkan-rt::TextureSwizzleChannels.green pub green: TextureSwizzle @@ -9220,6 +9223,8 @@ method metal2vulkan-air::tensor_ops::OperandForm::is_cooperative pub const fn is method metal2vulkan-air::tensor_ops::OperandIndex::from_raw pub fn from_raw(raw: u64) -> Option method metal2vulkan-air::tensor_ops::RunForm::arity pub fn arity(&self) -> usize method metal2vulkan-air::tensor_ops::RunForm::operand_args pub fn operand_args(&self) -> [usize; 3] +method metal2vulkan-rt::BlitCommandEncoder::copy_from_texture pub fn copy_from_texture(&mut self, source: &Texture, from: TexturePlace, size: [u32; 3], destination: &Texture, to: TexturePlace) -> Result<(), Error> +method metal2vulkan-rt::BlitCommandEncoder::end_encoding pub fn end_encoding(mut self) method metal2vulkan-rt::BlockId::get pub fn get(self) -> u32 method metal2vulkan-rt::Buffer::block pub fn block(&self) -> BlockId method metal2vulkan-rt::Buffer::contents pub fn contents(&self) -> Option> @@ -9229,6 +9234,7 @@ method metal2vulkan-rt::Buffer::length pub fn length(&self) -> u64 method metal2vulkan-rt::Buffer::offset pub fn offset(&self) -> u64 method metal2vulkan-rt::CommandBuffer::add_completed_handler pub fn add_completed_handler(&self, handler: impl FnOnce(&CommandBuffer) + Send + 'static) -> Result<(), Error> method metal2vulkan-rt::CommandBuffer::add_scheduled_handler pub fn add_scheduled_handler(&self, handler: impl FnOnce(&CommandBuffer) + Send + 'static) -> Result<(), Error> +method metal2vulkan-rt::CommandBuffer::blit_command_encoder pub fn blit_command_encoder(&self) -> Result method metal2vulkan-rt::CommandBuffer::commit pub fn commit(&self) -> Result<(), Error> method metal2vulkan-rt::CommandBuffer::compute_command_encoder pub fn compute_command_encoder(&self, dispatch_type: DispatchType) -> Result method metal2vulkan-rt::CommandBuffer::encode_signal_event pub fn encode_signal_event(&self, event: &Event, value: u64) -> Result<(), Error> @@ -11354,6 +11360,7 @@ struct metal2vulkan-air::ir::ValueId #[derive(Clone, Copy, Debug, PartialEq, Eq, struct metal2vulkan-air::ir::ValueIndex #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct ValueIndex struct metal2vulkan-air::tensor_ops::Descriptor #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Descriptor struct metal2vulkan-air::tensor_ops::RunForm #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct RunForm +struct metal2vulkan-rt::BlitCommandEncoder pub struct BlitCommandEncoder struct metal2vulkan-rt::BlockId #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct BlockId(u32) struct metal2vulkan-rt::BlockInfo #[derive(Clone, Copy, Debug)] #[non_exhaustive] pub struct BlockInfo struct metal2vulkan-rt::Buffer #[derive(Clone)] pub struct Buffer @@ -11383,6 +11390,7 @@ struct metal2vulkan-rt::SamplerState #[derive(Clone)] pub struct SamplerState struct metal2vulkan-rt::SharedEvent #[derive(Clone)] pub struct SharedEvent struct metal2vulkan-rt::Texture #[derive(Clone)] pub struct Texture struct metal2vulkan-rt::TextureDescriptor #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct TextureDescriptor +struct metal2vulkan-rt::TexturePlace #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct TexturePlace struct metal2vulkan-rt::TextureSwizzleChannels #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct TextureSwizzleChannels struct metal2vulkan-rt::floor::BelowFloor #[derive(Clone, Debug, PartialEq, Eq)] pub struct BelowFloor struct metal2vulkan-rt::floor::Capabilities pub struct Capabilities @@ -11925,6 +11933,7 @@ trait-impl metal2vulkan-air::ir::BlockId impl NodeId impl NodeId for BlockId trait-impl metal2vulkan-air::ir::Body impl Graph impl Graph for Body trait-impl metal2vulkan-air::ir::DataLayout impl Default impl Default for DataLayout trait-impl metal2vulkan-air::tensor_ops::Descriptor impl fmt::Display impl fmt::Display for Descriptor +trait-impl metal2vulkan-rt::BlitCommandEncoder impl Drop impl Drop for BlitCommandEncoder trait-impl metal2vulkan-rt::BlockInfo impl fe impl Send unsafe impl Send for BlockInfo trait-impl metal2vulkan-rt::BlockInfo impl fe impl Sync unsafe impl Sync for BlockInfo trait-impl metal2vulkan-rt::ComputeCommandEncoder impl Drop impl Drop for ComputeCommandEncoder @@ -13280,6 +13289,7 @@ variant metal2vulkan-rt::Gap::PartialSimdgroups PartialSimdgroups { threads_per_ variant metal2vulkan-rt::Gap::PartialThreadgroups PartialThreadgroups { threads_per_grid: [u32; 3], threads_per_threadgroup: [u32; 3] } variant metal2vulkan-rt::Gap::TextureBuffer TextureBuffer variant metal2vulkan-rt::Gap::TextureBytes TextureBytes { pixel_format: PixelFormat } +variant metal2vulkan-rt::Gap::TextureCopy TextureCopy { source: PixelFormat, destination: PixelFormat } variant metal2vulkan-rt::Gap::TextureFormat TextureFormat { pixel_format: PixelFormat } variant metal2vulkan-rt::IndexClass::Sampler Sampler variant metal2vulkan-rt::IndexClass::StorageTexture StorageTexture @@ -13401,6 +13411,7 @@ variant metal2vulkan-rt::Refusal::TextureArgumentIndex TextureArgumentIndex { in variant metal2vulkan-rt::Refusal::TextureArrayLength TextureArrayLength { array_length: u32 } variant metal2vulkan-rt::Refusal::TextureBytesLayout TextureBytesLayout { bytes_per_row: u64, bytes_per_image: u64, len: u64 } variant metal2vulkan-rt::Refusal::TextureBytesPrivate TextureBytesPrivate +variant metal2vulkan-rt::Refusal::TextureCopyMismatch TextureCopyMismatch { source: PixelFormat, destination: PixelFormat } variant metal2vulkan-rt::Refusal::TextureCubeNotSquare TextureCubeNotSquare variant metal2vulkan-rt::Refusal::TextureExtentForType TextureExtentForType variant metal2vulkan-rt::Refusal::TextureIndex TextureIndex { index: Option } diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 98246a518..f6f6afef6 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -37,9 +37,9 @@ Columns: | What a call did wrong | 73 | 73 | 0 | 0 | 0 | 0 | 0 | | What a call did wrong, in detail | 174 | 157 | 0 | 0 | 0 | 0 | 0 | | Devices below the new runtime's floor | 7 | 7 | 0 | 0 | 0 | 0 | 0 | -| The new runtime's `Refusal` | 32 | 32 | 0 | 0 | 0 | 0 | 0 | +| The new runtime's `Refusal` | 33 | 33 | 0 | 0 | 0 | 0 | 0 | | The new runtime's `Limit` | 10 | 10 | 0 | 0 | 0 | 0 | 0 | -| The new runtime's `Gap` | 10 | 10 | 0 | 0 | 0 | 0 | 0 | +| The new runtime's `Gap` | 11 | 11 | 0 | 0 | 0 | 0 | 0 | ## Totals by basis @@ -55,9 +55,9 @@ Columns: | What a call did wrong | 22 | 3 | 5 | 0 | 18 | 8 | 17 | 0 | | What a call did wrong, in detail | 60 | 26 | 23 | 0 | 39 | 26 | 0 | 0 | | Devices below the new runtime's floor | 0 | 0 | 0 | 7 | 0 | 0 | 0 | 0 | -| The new runtime's `Refusal` | 9 | 8 | 0 | 0 | 15 | 0 | 0 | 0 | +| The new runtime's `Refusal` | 9 | 8 | 1 | 0 | 15 | 0 | 0 | 0 | | The new runtime's `Limit` | 0 | 0 | 0 | 7 | 3 | 0 | 0 | 0 | -| The new runtime's `Gap` | 0 | 0 | 0 | 0 | 10 | 0 | 0 | 0 | +| The new runtime's `Gap` | 0 | 0 | 0 | 0 | 11 | 0 | 0 | 0 | ## 1. Translator and front-end refusals (`Unsupported`: a `Feature` and its `Needs`) @@ -619,7 +619,7 @@ Columns: | `ManagedBlockNotShared` | A Managed buffer whose bytes are in a Private block (`Device::new_managed_buffer`) | every device (a public call's own check of its arguments) | `ours`: a Managed buffer's bytes are the consumer's, which it maps; a Private block has no mapping | 1: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` | `-` | | `ModifiedRange` | A changed range that leaves its buffer (`Buffer::did_modify_range`) | every device (a public call's own check of its arguments) | `ours`: the copy of such a range would write past the buffer's device copy | 1: `crates/metal2vulkan-rt/src/buffer.rs (did_modify_range)` | `-` | | `Committed` | A call on a command buffer already committed | every device (a public call's own check of its arguments) | `metal-documented`: Metal's validation asserts "commit an already committed command buffer", "Completed handler provided after commit call" and "Scheduled handler provided after commit call" | 1: `crates/metal2vulkan-rt/src/command.rs (open)` | `-` | -| `OtherDevice` | An event, a buffer or a pipeline state of another device in an encode call (`CommandBuffer::encode_wait_for_event`,... | every device (a public call's own check of its arguments) | `ours`: an event's semaphore, a buffer's block and a pipeline belong to the `VkDevice` that made them | 8: `crates/metal2vulkan-rt/src/command.rs (check)`, `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)` (+5) | `-` | +| `OtherDevice` | An event, a buffer, a texture or a pipeline state of another device in an encode call (`CommandBuffer::encode_wait_for_event`,... | every device (a public call's own check of its arguments) | `ours`: an event's semaphore, a buffer's block, a texture's image and a pipeline belong to the `VkDevice` that made them | 9: `crates/metal2vulkan-rt/src/blit.rs (copy_from_texture)`, `crates/metal2vulkan-rt/src/command.rs (check)` (+6) | `-` | | `NoCommandBuffers` | A queue that may hold no command buffer (`Device::new_command_queue` with a count of 0) | every device (a public call's own check of its arguments) | `ours`: its first `commandBuffer` call would wait forever | 1: `crates/metal2vulkan-rt/src/queue.rs (new_command_queue)` | `-` | | `EncoderOpen` | A second encoder, an encode call, or a commit or enqueue, while an encoder of the command buffer is open | every device (a public call's own check of its arguments) | `metal-documented`: a command buffer has one active encoder at a time, ended by `endEncoding` before another is made or the command buffer is committed | 1: `crates/metal2vulkan-rt/src/command.rs (open)` | `-` | | `NoPipeline` | A dispatch with no pipeline state set | every device (a public call's own check of its arguments) | `metal-documented`: a compute dispatch needs a compute pipeline state set first | 1: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` | `-` | @@ -643,8 +643,9 @@ Columns: | `TextureSampleCount` | A texture with a sample count of 0, or other than 1 of a type that is not multisample | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max, macOS 27.0.1: plain Metal asserts "has sampleCount set but is using a type that does not allow sampleCount" for 0 and for 2 of a 2D texture | 1: `crates/metal2vulkan-rt/src/texture.rs (shape)` | `-` | | `TextureSwizzleWithWrites` | A texture with a swizzle other than each channel from itself and shader-write or render-target usage | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max, macOS 27.0.1: plain Metal asserts "Texture swizzling is not compatable with MTLTextureUsageShaderWrite", where a swizzle of read usage alone is made | 1: `crates/metal2vulkan-rt/src/texture.rs (new_texture)` | `-` | | `TextureBytesPrivate` | `Texture::replace_region` or `Texture::get_bytes` of a Private or Memoryless texture | every device (a public call's own check of its arguments) | `metal-documented`: Apple's documentation of `MTLStorageModePrivate`: "The resource is accessible only to the GPU." | 1: `crates/metal2vulkan-rt/src/texture.rs (copy)` | `-` | -| `TextureRegion` | `Texture::replace_region` or `Texture::get_bytes` of a level or slice past the texture's, or of a region that leaves the level or is off the... | every device (a public call's own check of its arguments) | `ours`: no texel of the texture is there to copy | 1: `crates/metal2vulkan-rt/src/texture.rs (copy)` | `-` | +| `TextureRegion` | `Texture::replace_region`, `Texture::get_bytes` or a blit copy (`BlitCommandEncoder::copy_from_texture`) of a level or slice past the texture's,... | every device (a public call's own check of its arguments) | `ours`: no texel of the texture is there to copy | 1: `crates/metal2vulkan-rt/src/texture.rs (place)` | `-` | | `TextureBytesLayout` | `Texture::replace_region` or `Texture::get_bytes` with rows closer than a row of the region, images closer than an image of it, or bytes too few... | every device (a public call's own check of its arguments) | `ours`: the call would read or write past the bytes it is given, or one texel's bytes over another's | 1: `crates/metal2vulkan-rt/src/texture.rs (copy)` | `-` | +| `TextureCopyMismatch` | `BlitCommandEncoder::copy_from_texture` between formats whose copy units differ in bytes, or between textures of different sample counts | every device (a public call's own check of its arguments) | `metal-takes`: an M4 and an Apple M3 Max, macOS 27.0.1: plain Metal completes the copy with no error; between formats of different units the bytes follow the GPU's own texel layout, and between sample counts its own twiddled or compressed sample layout, so there is no defined answer to put in its place | 1: `crates/metal2vulkan-rt/src/blit.rs (texture_copy)` | `-` | ## 12. The new runtime's `Limit` (`Error::Limit(Limit)`) @@ -675,6 +676,7 @@ Columns: | `CubicSampler` | A sampler state whose minification or magnification filter is cubic (`Device::new_sampler_state`) | every device (a public call's own check of its arguments) | `ours`: the translator's identity domains do not filter bicubically, and Vulkan's cubic filter is not Metal's | 1: `crates/metal2vulkan-rt/src/sampler.rs (new_sampler_state)` | `-` | | `TextureBytes` | `Texture::replace_region` or `Texture::get_bytes` of a texture whose image is no plain copy of Metal's bytes in one aspect | every device (a public call's own check of its arguments) | `ours`: no copy between such an image and bytes is built | 1: `crates/metal2vulkan-rt/src/texture.rs (copy)` | `-` | | `FloatDepthUpload` | `Texture::replace_region` 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 | 1: `crates/metal2vulkan-rt/src/texture.rs (replace_region)` | `-` | +| `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-rt/src/blit.rs (texture_copy)` | `-` | ## Appendix: every site @@ -1169,7 +1171,7 @@ Each refusal's sites, with the function that builds it. - `rt:Refusal::ManagedBlockNotShared`: `crates/metal2vulkan-rt/src/buffer.rs (new_managed_buffer)` - `rt:Refusal::ModifiedRange`: `crates/metal2vulkan-rt/src/buffer.rs (did_modify_range)` - `rt:Refusal::Committed`: `crates/metal2vulkan-rt/src/command.rs (open)` -- `rt:Refusal::OtherDevice`: `crates/metal2vulkan-rt/src/command.rs (check)`; `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`; `crates/metal2vulkan-rt/src/encoder.rs (set_buffer)`; `crates/metal2vulkan-rt/src/encoder.rs (set_compute_pipeline_state)`; `crates/metal2vulkan-rt/src/encoder.rs (set_sampler_state)`; `crates/metal2vulkan-rt/src/encoder.rs (set_texture)`; `crates/metal2vulkan-rt/src/encoder.rs (use_resource, 2 sites)` +- `rt:Refusal::OtherDevice`: `crates/metal2vulkan-rt/src/blit.rs (copy_from_texture)`; `crates/metal2vulkan-rt/src/command.rs (check)`; `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`; `crates/metal2vulkan-rt/src/encoder.rs (set_buffer)`; `crates/metal2vulkan-rt/src/encoder.rs (set_compute_pipeline_state)`; `crates/metal2vulkan-rt/src/encoder.rs (set_sampler_state)`; `crates/metal2vulkan-rt/src/encoder.rs (set_texture)`; `crates/metal2vulkan-rt/src/encoder.rs (use_resource, 2 sites)` - `rt:Refusal::NoCommandBuffers`: `crates/metal2vulkan-rt/src/queue.rs (new_command_queue)` - `rt:Refusal::EncoderOpen`: `crates/metal2vulkan-rt/src/command.rs (open)` - `rt:Refusal::NoPipeline`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` @@ -1193,8 +1195,9 @@ Each refusal's sites, with the function that builds it. - `rt:Refusal::TextureSampleCount`: `crates/metal2vulkan-rt/src/texture.rs (shape)` - `rt:Refusal::TextureSwizzleWithWrites`: `crates/metal2vulkan-rt/src/texture.rs (new_texture)` - `rt:Refusal::TextureBytesPrivate`: `crates/metal2vulkan-rt/src/texture.rs (copy)` -- `rt:Refusal::TextureRegion`: `crates/metal2vulkan-rt/src/texture.rs (copy)` +- `rt:Refusal::TextureRegion`: `crates/metal2vulkan-rt/src/texture.rs (place)` - `rt:Refusal::TextureBytesLayout`: `crates/metal2vulkan-rt/src/texture.rs (copy)` +- `rt:Refusal::TextureCopyMismatch`: `crates/metal2vulkan-rt/src/blit.rs (texture_copy)` - `rt:Limit::BlockLen`: `crates/metal2vulkan-rt/src/memory.rs (dedicated_len)` - `rt:Limit::BlockIds`: `crates/metal2vulkan-rt/src/memory.rs (number)` - `rt:Limit::ThreadgroupShape`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` @@ -1215,4 +1218,5 @@ Each refusal's sites, with the function that builds it. - `rt:Gap::CubicSampler`: `crates/metal2vulkan-rt/src/sampler.rs (new_sampler_state)` - `rt:Gap::TextureBytes`: `crates/metal2vulkan-rt/src/texture.rs (copy)` - `rt:Gap::FloatDepthUpload`: `crates/metal2vulkan-rt/src/texture.rs (replace_region)` +- `rt:Gap::TextureCopy`: `crates/metal2vulkan-rt/src/blit.rs (texture_copy)`