RI::copyLayout, RI::cmdCopyBufferToTexture, RI::cmdCopyTextureToBuffer, RI::cmdCopyTexture¶
What it does¶
These functions copy texels between buffers and texture views, or between two texture views:
RI::copyLayout(device, view, region)returns aRI::CopyLayoutdescribing how the texels ofview(withinregion) are laid out in a buffer:rowPitchis the byte stride from one row to the next,layerPitchis the byte stride from one layer to the next,sizeis the total number of bytes the copy reads or writes from the buffer offset, andalignmentis the required alignment of that buffer offset. Because these pitches and alignments depend on the backend and GPU, always query them withcopyLayoutinstead of computing them yourself.RI::cmdCopyBufferToTexture(cmd, src, srcOffset, dst, region)copies texels from buffersrc(starting at byte offsetsrcOffset) into texture viewdst(for example, an upload fromMemoryKind::eUploadmemory).RI::cmdCopyTextureToBuffer(cmd, src, dst, dstOffset, region)copies texels from texture viewsrcinto bufferdst(starting at byte offsetdstOffset; for example, a readback intoMemoryKind::eReadbackmemory).RI::cmdCopyTexture(cmd, src, dst, region, dstOffset)copiesregionfrom texture viewsrctodstOffsetin texture viewdst.
Every copy covers one mip and every layer of the view, so create a view of the mip
and layers you want to copy. Within each layer, region (an RI::Rect with x, y, width,
and height) selects the texels to copy; if left at
its default ({}, where x, y, width, and height are all 0), it selects the whole mip.
Pass the same region to RI::copyLayout to get the buffer layout for that region; the returned
CopyLayout sets width and height to the region's dimensions. For example, reading the single
pixel under the mouse uses a 1x1 region rather than copying the whole frame. For depth-stencil
formats, copy one aspect at a time using a view with Aspect::eDepth or Aspect::eStencil.
RI::copyBytesPerTexel(format, aspect) returns the texel size in bytes: 2 bytes for
Format::eD16Unorm, 4 bytes for other depth formats (including 24-bit depth, which is padded to 4
bytes), 1 byte for stencil, and the format's texel size for color formats.
For a 3D texture, the view's layerCount selects depth slices instead of
array layers: layout.layers equals the number of slices in the view, and those slices follow
each other in the buffer with no padding (layout.layerPitch equals layout.rowPitch *
layout.height, as D3D12 requires). You can also copy between a 3D view and a 2D-array view that
has the same number of layers using RI::cmdCopyTexture.
For buffer-to-buffer copies, use RI::cmdCopyBuffer.
Signature¶
// <RI/RI.hpp>, namespace RI
CopyLayout copyLayout(Device &device, const TextureView &view, Rect region = {});
From the header: Copies (P47). A texture view covers one mip (and one aspect of a depth format); the buffer side follows copyLayout(). Copies count as Stage::eCopy. region selects texels in each layer of the view (P108); the default, width and height 0, is the whole mip. Depth, stencil and multisampled views copy whole (D3D12 copies their subresources only whole).
// <RI/RI.hpp>, namespace RI
CopyLayout copyLayout(Device &device, const TextureView &view, Rect region = {});
From the header: Copies (P47). A texture view covers one mip (and one aspect of a depth format); the buffer side follows copyLayout(). Copies count as Stage::eCopy. region selects texels in each layer of the view (P108); the default, width and height 0, is the whole mip. Depth, stencil and multisampled views copy whole (D3D12 copies their subresources only whole).
// <RI/RI.hpp>, namespace RI
void cmdCopyBufferToTexture(CommandList &cmd, const Buffer &src, uint64 srcOffset, const TextureView &dst, Rect region = {});
// <RI/RI.hpp>, namespace RI
void cmdCopyTextureToBuffer(CommandList &cmd, const TextureView &src, const Buffer &dst, uint64 dstOffset, Rect region = {});
// <RI/RI.hpp>, namespace RI
void cmdCopyTexture(CommandList &cmd, const TextureView &src, const TextureView &dst, Rect region = {}, Offset dstOffset = {});
From the header: region of src lands at dstOffset in dst, in every layer. Same layer count, sample count and texel size.
From the header: Part of a texture (P73): a mip range, a layer range, an aspect, a format. Bytes per texel as copies read and write one aspect (P47): the color size, 4 for depth (2 for eD16Unorm; 24-bit depth is padded to 4), 1 for stencil. eDefault means color, or depth for depth formats.
Example¶
// Ask where each row goes, then write the rows at that pitch.
const RI::CopyLayout layout = RI::copyLayout(device, texture.view);
RI::Buffer staging = RI::createBuffer(device, uploadMemory, 0,
{.size = layout.size, .usage = RI::BufferUsage::eCopySrc});
for (uint32 y = 0; y < layout.height; ++y) {
std::memcpy(static_cast<std::byte *>(staging.mapped) + y * layout.rowPitch, &image[y * 256],
uint64{layout.width} * layout.bytesPerTexel);
}
RI::CommandList cmd = RI::createCommandList(device);
RI::cmdBegin(cmd);
RI::cmdCopyBufferToTexture(cmd, staging, 0, texture.view);
// Copies count as Stage::eCopy: order them before the shaders that read.
RI::cmdBarrier(cmd, RI::Stage::eCopy, RI::Stage::eCompute | RI::Stage::ePixel);
RI::Buffer readback = RI::createBuffer(device, readbackMemory, 0,
{.size = layout.size, .usage = RI::BufferUsage::eCopyDst});
RI::cmdBarrier(cmd, RI::Stage::eAll, RI::Stage::eCopy);
RI::cmdCopyTextureToBuffer(cmd, texture.view, readback, 0);
RI::cmdEnd(cmd);
RI::wait(device.graphicsQueue, RI::submit(device.graphicsQueue, cmd));
// Row y is at readback.mapped + y * layout.rowPitch.
The same in native code¶
// Ask where each row goes, then write the rows at that pitch.
const RI::CopyLayout layout = RI::copyLayout(device, texture.view);
RI::Buffer staging = RI::createBuffer(device, uploadMemory, 0,
{.size = layout.size, .usage = RI::BufferUsage::eCopySrc});
for (uint32 y = 0; y < layout.height; ++y) {
std::memcpy(static_cast<std::byte *>(staging.mapped) + y * layout.rowPitch, &image[y * 256],
uint64{layout.width} * layout.bytesPerTexel);
}
RI::CommandList cmd = RI::createCommandList(device);
RI::cmdBegin(cmd);
RI::cmdCopyBufferToTexture(cmd, staging, 0, texture.view);
// Copies count as Stage::eCopy: order them before the shaders that read.
RI::cmdBarrier(cmd, RI::Stage::eCopy, RI::Stage::eCompute | RI::Stage::ePixel);
void upload(VkCommandBuffer commands, VkBuffer staging, VkImage image, uint32_t width, uint32_t height) {
VkImageMemoryBarrier2 toTransfer{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
.srcStageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT,
.dstStageMask = VK_PIPELINE_STAGE_2_COPY_BIT,
.dstAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT,
.oldLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.image = image,
.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
VkDependencyInfo dependency{.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO,
.imageMemoryBarrierCount = 1,
.pImageMemoryBarriers = &toTransfer};
vkCmdPipelineBarrier2(commands, &dependency);
// bufferRowLength 0: rows are tightly packed (Vulkan's offset only needs
// to be a multiple of the texel size and of 4).
const VkBufferImageCopy region{.bufferOffset = 0,
.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.imageExtent = {width, height, 1}};
vkCmdCopyBufferToImage(commands, staging, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion);
VkImageMemoryBarrier2 back = toTransfer;
back.srcStageMask = VK_PIPELINE_STAGE_2_COPY_BIT;
back.srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT;
back.dstStageMask = VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT;
back.dstAccessMask = VK_ACCESS_2_SHADER_SAMPLED_READ_BIT;
back.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
back.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
dependency.pImageMemoryBarriers = &back;
vkCmdPipelineBarrier2(commands, &dependency);
}
What to watch for: the image must be in TRANSFER_DST_OPTIMAL (or GENERAL) during the
copy, so a sampled texture needs a transition there and back. bufferRowLength is in
texels, not bytes.
void upload(ID3D12Device *device, ID3D12GraphicsCommandList *list, ID3D12Resource *staging, ID3D12Resource *texture) {
const D3D12_RESOURCE_DESC desc = texture->GetDesc();
D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{};
UINT rows = 0;
UINT64 rowBytes = 0, total = 0;
device->GetCopyableFootprints(&desc, 0, 1, 0, &footprint, &rows, &rowBytes, &total);
// Write each of `rows` rows (rowBytes long) at footprint.Footprint.RowPitch
// into `staging` first. The texture must be in a layout that allows copies.
D3D12_TEXTURE_COPY_LOCATION to{.pResource = texture, .Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX};
to.SubresourceIndex = 0;
D3D12_TEXTURE_COPY_LOCATION from{.pResource = staging, .Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT};
from.PlacedFootprint = footprint;
list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr);
}
What to watch for: rows are 256-byte aligned and each subresource's data starts on a
512-byte boundary; GetCopyableFootprints gives the exact layout. Record one
CopyTextureRegion call per subresource (per layer and per plane).
How RI does it¶
- Vulkan: Uses
vkCmdCopyBufferToImage2,vkCmdCopyImageToBuffer2, andvkCmdCopyImage2with one region, mapping the copyregionto the image offset and extent.copyLayoutalignsrowPitchtooptimalBufferCopyRowPitchAlignment(and a whole multiple of the texel size), andalignmentto at leastoptimalBufferCopyOffsetAlignment, the texel size, and 4. A texture that rests inVK_IMAGE_LAYOUT_GENERALis copied in place; textures inLayoutMode::eTransitions(mode T) switch to the transfer layout (VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMALorVK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) before the copy and back afterward, using RI's exact/full barrier halves. - D3D12: Uses
CopyTextureRegiononce per layer (or once for all slices of a 3D view in buffer copies, and once per slice incmdCopyTexture).copyLayoutalignsrowPitchto 256 bytes andalignment(and non-3DlayerPitch) to 512 bytes. The buffer footprint takes the region'swidthandheight;region.xandregion.yset the destination offset incmdCopyBufferToTextureand the sourceD3D12_BOXincmdCopyTextureToBufferandcmdCopyTexture(withdstOffsetas the destination offset). Textures with copy usage rest inDIRECT_QUEUE_COMMON, which allows copies directly without a layout switch.
Rules and errors¶
- A texture written by a copy needs
TextureUsage::eCopyDst, and a texture read by a copy needsTextureUsage::eCopySrc(programmer error in validation builds). A buffer read by a copy needsBufferUsage::eCopySrc, and a buffer written by a copy needsBufferUsage::eCopyDst(programmer error). - The texture view must cover one mip and one aspect (not both depth and stencil). Buffer copies require a single-sampled texture.
- The buffer offset must be a multiple of
layout.alignment, andoffset + layout.sizemust fit within the buffer. regionmust not be empty and must lie inside the mip; if left default (widthandheight0),xandymust also be 0. Depth, stencil, and multisampled views can only be copied whole, as D3D12 requires (programmer error for a smaller region on both backends).- In
cmdCopyTexture,regionplaced atdstOffsetmust fit inside the destination mip, and the source and destination views must have the same layer count, sample count, and texel byte size. - Copies cannot be recorded inside a rendering section. They count as
Stage::eCopyfor barriers: place a barrier after the work that wrote the source, and another before the work that reads the destination. - A texture placed over memory that another resource used must be discarded before a copy writes to it (validation builds report this).