Image layouts are RI's business¶
What you never see¶
On both Vulkan and D3D12, a texture is not just raw memory. The GPU keeps each texture in a layout, an internal arrangement suited to one kind of use (such as a render target, depth test, shader read, or copy). Before a texture can be used in a different way, the program must transition it by naming the texture, its old layout, and its new layout. In a renderer written directly against Vulkan or D3D12, this tracking is a large share of the code and a common source of bugs.
In RI you never name, track, or transition a layout. No portable RI function takes a layout, no portable RI struct has one, and your code is the same on every backend and every GPU. Instead, you specify:
- usage flags at texture creation (
TextureUsage), which declare what the texture is used for; - rendering sections, clears, copies, and discards, which are RI's own operations;
- barriers between your own commands, which name pipeline stages rather than textures
(
cmdBarrier).
The rest of this page explains how each backend implements this model. You do not need these details to use RI, but they explain the rules you do see (why cmdDiscard exists, why barriers name no texture, and what each usage flag costs).
The idea: every texture rests in one layout¶
RI's layout model is called A' in the design notes. Each texture is assigned one resting layout when it is created, chosen from its usage flags and format. Between operations, every texture is in its resting layout:
- Your shaders (compute, vertex, pixel) read and write textures in their resting layout. Because RI cannot see which textures a bindless shader accesses, the resting layout must already allow shader access.
- RI's own operations (rendering sections, clears, and copies) know exactly which textures they touch. When an operation needs a different layout, RI switches the texture into that layout at the start of the operation and switches it back to its resting layout at the end.
Because every operation begins and ends with textures at rest, a texture is never left in an unexpected layout, there is no per-texture state to track across command lists, and every command list starts and ends with all textures in their resting layouts.
D3D12: resting layouts per usage¶
D3D12 (with enhanced barriers) provides DIRECT_QUEUE_COMMON, a layout that allows shader reads, shader writes, and copies on the direct queue without transitions. RI uses it whenever a texture can be accessed by shaders or copies:
| Texture usage | Resting layout |
|---|---|
any of eSampled, eStorage, eCopySrc, eCopyDst |
DIRECT_QUEUE_COMMON |
eRenderTarget only |
RENDER_TARGET |
eDepthStencil only |
DEPTH_STENCIL_WRITE |
For example, a render target that shaders also sample rests in DIRECT_QUEUE_COMMON: cmdBeginRendering switches it to RENDER_TARGET, and cmdEndRendering switches it back. A render target that is only ever rendered to rests in RENDER_TARGET and needs no switch at all.
Vulkan: three modes¶
Vulkan has more layouts, and drivers differ in how fast each layout is. The Vulkan backend selects one of three layout modes when the device is created. The mode is internal to the backend and requires no changes to your code.
| Mode | Used when | Resting layout | Switches |
|---|---|---|---|
eUnified |
the driver supports VK_KHR_unified_image_layouts and its unifiedImageLayouts feature is enabled |
GENERAL for every texture |
none: the extension makes GENERAL as fast as specialized layouts |
eTransitions (mode T) |
the driver lacks VK_KHR_unified_image_layouts (or its feature is off) |
per usage, like D3D12 | around RI's operations |
eGeneral (mode G) |
forced for testing or measuring | GENERAL for every texture |
none, though attachments may lose compression on some GPUs |
In eTransitions (mode T), the resting layouts are:
| Texture usage | Resting layout |
|---|---|
eStorage (with any other flags) |
GENERAL |
eSampled (color) |
READ_ONLY_OPTIMAL |
eSampled (depth) |
SHADER_READ_ONLY_OPTIMAL (fastest for sampling; read-only depth sections switch it) |
eSampled + eReadOnlyDepthSampling (depth) |
READ_ONLY_OPTIMAL (no switch in read-only depth sections) |
eRenderTarget (without eStorage or eSampled) |
COLOR_ATTACHMENT_OPTIMAL |
eDepthStencil (without eStorage or eSampled) |
ATTACHMENT_OPTIMAL |
| copies only | GENERAL |
You can read the active mode from RI::Vk::native(device).layoutMode, and force a specific mode at device creation (Vulkan: device creation).
RI's switches: an exact half and a full half¶
A layout switch is a barrier, and a barrier has two halves: what earlier work it waits for, and what later work it blocks. Because RI knows its own operation, the half touching that operation is exact, while the half touching your surrounding work is full:
- A switch into an RI operation (at
cmdBeginRendering, or before a clear or copy) waits for all earlier work and blocks only that operation. - A switch back to rest after an RI operation (at
cmdEndRendering, or after a clear or copy) waits only for that operation and blocks all later work.
RI emits these switches immediately when the operation is recorded. It never defers or merges your barriers, so there is no hidden barrier state.
When a rendering section switches into an attachment layout and the load operation is eClear or eDontCare (so the old contents are not needed), the switch starts from UNDEFINED and the GPU skips preserving them. On D3D12, cmdClearTexture on a render-target or depth-stencil texture also starts its switch from UNDEFINED.
Your barriers are global¶
Because textures are always in their resting layouts between operations, a barrier between your own commands never needs to change a layout. It only needs to order work and make writes visible, which is what a global barrier does: it names pipeline stages, not individual resources. See Barriers.
Global barriers cover everything that textures at rest allow: shader reads and writes, copies, and clears. Attachment writes are a special case because they happen inside a rendering section, and on D3D12 a global barrier cannot name render-target or depth-stencil accesses. On D3D12 and in Vulkan mode T, RI's switch back to rest at cmdEndRendering is what makes attachment writes visible to later shaders or copies; a texture that rests in its attachment layout can only be used by later attachment or clear work, which the GPU orders itself.
Write the barrier between rendering and sampling anyway, every time:
// The section's writes, then shaders that sample color and depth.
RI::cmdBarrier(cmd, RI::Stage::eRenderTarget | RI::Stage::eDepthStencil, RI::Stage::eCompute | RI::Stage::ePixel);
On Vulkan in eUnified and eGeneral modes, there is no layout switch at cmdEndRendering, so this global barrier is what orders the shader sampling after rendering. On D3D12 it adds no extra cost.
What a texture taking over memory needs¶
A texture placed over memory previously used by another resource contains garbage, including garbage in its hidden compression metadata, which a rendering load operation does not reset. Because RI cannot know when aliased memory changes hands, you must call cmdDiscard before using the new texture. cmdDiscard transitions the texture from UNDEFINED to its resting layout, which resets the metadata. See Textures and views.
Is this fast enough?¶
Hiding layouts has a potential cost: on D3D12 and in Vulkan mode T, an attachment that shaders also read makes a round trip through its resting layout on every rendering section, which can trigger decompression work. Model A' was benchmarked against hand-written optimal transitions under a pass/fail rule fixed before measuring: at most 2% slower per realistic frame and 10% per pass (unless the difference is under 0.05 ms) on every tested GPU.
It passes on every tested GPU: an NVIDIA RTX 3080 (D3D12, Vulkan eUnified), an AMD RDNA2 iGPU (D3D12, Vulkan mode T), and an AMD RDNA2 680M (Vulkan mode T), at both 1080p and 4K, with the realistic frame within +1.5% of hand-written transitions. One pass initially failed (AMD Vulkan reading a depth texture); that led to sampled depth textures resting in the fastest layout for sampling, with eReadOnlyDepthSampling reserved for textures sampled during a read-only depth section. Because mode G is never faster on AMD, mode T is chosen automatically when VK_KHR_unified_image_layouts is unavailable.
In native code¶
// Clear both attachments at the start of the section and keep the results.
RI::cmdBeginRendering(cmd, {
.colors = {{.view = color.view, .load = RI::LoadOp::eClear, .clear = {.color = {0.1f, 0.1f, 0.1f, 1.0f}}}},
.depth = RI::DepthAttachment{.view = depth.view,
.load = RI::LoadOp::eClear,
.stencilLoad = RI::LoadOp::eClear,
.clear = {.depth = 1.0f, .stencil = 0}},
});
RI::cmdSetPipeline(cmd, pipeline);
RI::Helpers::cmdSetRootData(cmd, DrawRoot{.color = {1.0f, 0.5f, 0.0f, 1.0f}, .depth = 0.5f});
RI::cmdDraw(cmd, 3); // three vertices, one instance
// Draw again into the top-left quarter only; the next section starts with
// the whole attachments again.
RI::cmdSetViewport(cmd, {.x = 0.0f, .y = 0.0f, .width = 128.0f, .height = 128.0f});
RI::cmdSetScissor(cmd, {.x = 0, .y = 0, .width = 128, .height = 128});
RI::cmdDraw(cmd, 3);
RI::cmdEndRendering(cmd);
Every transition is yours, written with vkCmdPipelineBarrier2:
// One layout transition of a whole image (every mip and layer of `aspect`),
// with the stages and accesses on each side.
void transition(VkCommandBuffer cmd, VkImage image, VkImageAspectFlags aspect, VkImageLayout oldLayout,
VkImageLayout newLayout, VkPipelineStageFlags2 srcStage, VkAccessFlags2 srcAccess,
VkPipelineStageFlags2 dstStage, VkAccessFlags2 dstAccess) {
const VkImageMemoryBarrier2 barrier{
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
.srcStageMask = srcStage,
.srcAccessMask = srcAccess,
.dstStageMask = dstStage,
.dstAccessMask = dstAccess,
.oldLayout = oldLayout, // UNDEFINED: the contents may be thrown away
.newLayout = newLayout,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = image,
.subresourceRange = {.aspectMask = aspect,
.baseMipLevel = 0,
.levelCount = VK_REMAINING_MIP_LEVELS,
.baseArrayLayer = 0,
.layerCount = VK_REMAINING_ARRAY_LAYERS},
};
const VkDependencyInfo dependency{
.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO, .imageMemoryBarrierCount = 1, .pImageMemoryBarriers = &barrier};
vkCmdPipelineBarrier2(cmd, &dependency);
}
// Into attachment layouts. The old layout is UNDEFINED because both are
// cleared: their previous contents are not needed.
transition(cmd, color, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, VK_ACCESS_2_NONE,
VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT,
VK_ACCESS_2_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT);
transition(cmd, depth, VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT, VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT,
VK_ACCESS_2_NONE, kDepthStages,
VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT);
VkRenderingAttachmentInfo colorAttachment{
.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO,
.imageView = colorView,
.imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
.storeOp = VK_ATTACHMENT_STORE_OP_STORE,
};
colorAttachment.clearValue.color = {{0.1f, 0.1f, 0.1f, 1.0f}};
VkRenderingAttachmentInfo depthAttachment{
.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO,
.imageView = depthView,
.imageLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
.storeOp = VK_ATTACHMENT_STORE_OP_STORE,
};
depthAttachment.clearValue.depthStencil = {.depth = 1.0f, .stencil = 0};
const VkRenderingInfo rendering{
.sType = VK_STRUCTURE_TYPE_RENDERING_INFO,
.renderArea = {.offset = {0, 0}, .extent = {kWidth, kHeight}},
.layerCount = 1,
.colorAttachmentCount = 1,
.pColorAttachments = &colorAttachment,
.pDepthAttachment = &depthAttachment,
.pStencilAttachment = &depthAttachment, // the same view: its stencil aspect
};
vkCmdBeginRendering(cmd, &rendering);
// A negative height flips y, so clip space points up as in D3D12.
const VkViewport viewport{.x = 0.0f,
.y = static_cast<float>(kHeight),
.width = static_cast<float>(kWidth),
.height = -static_cast<float>(kHeight),
.minDepth = 0.0f,
.maxDepth = 1.0f};
const VkRect2D scissor{.offset = {0, 0}, .extent = {kWidth, kHeight}};
vkCmdSetViewport(cmd, 0, 1, &viewport);
vkCmdSetScissor(cmd, 0, 1, &scissor);
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
const DrawRoot root{.color = {1.0f, 0.5f, 0.0f, 1.0f}, .depth = 0.5f};
vkCmdPushConstants(cmd, pipelineLayout, VK_SHADER_STAGE_ALL, 0, sizeof(root), &root);
vkCmdDraw(cmd, 3, 1, 0, 0);
vkCmdEndRendering(cmd);
// Out of attachment layouts, into the layouts shaders read: this barrier
// also makes the attachment writes visible to the pixel and compute shaders.
transition(cmd, color, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT,
VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT,
VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT,
VK_ACCESS_2_SHADER_SAMPLED_READ_BIT);
transition(cmd, depth, VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT,
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL,
kDepthStages, VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT | kDepthStages,
VK_ACCESS_2_SHADER_SAMPLED_READ_BIT | VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_READ_BIT);
What to watch for: a descriptor names the layout the image will be in when the shader
reads it, so the layout at draw time must match the descriptor. Separate depth and stencil
layouts need separateDepthStencilLayouts.
Every layout change is a texture barrier (enhanced barriers):
// One layout change of a whole texture (every mip, layer and plane), with the
// sync and access on each side. `flags`: DISCARD drops the old contents.
void textureBarrier(ID3D12GraphicsCommandList7 *cmd, ID3D12Resource *texture, D3D12_BARRIER_LAYOUT before,
D3D12_BARRIER_LAYOUT after, D3D12_BARRIER_SYNC syncBefore, D3D12_BARRIER_ACCESS accessBefore,
D3D12_BARRIER_SYNC syncAfter, D3D12_BARRIER_ACCESS accessAfter,
D3D12_TEXTURE_BARRIER_FLAGS flags = D3D12_TEXTURE_BARRIER_FLAG_NONE) {
const D3D12_TEXTURE_BARRIER barrier{
.SyncBefore = syncBefore,
.SyncAfter = syncAfter,
.AccessBefore = accessBefore,
.AccessAfter = accessAfter,
.LayoutBefore = before,
.LayoutAfter = after,
.pResource = texture,
.Subresources = {.IndexOrFirstMipLevel = 0xffffffff}, // all subresources
.Flags = flags,
};
const D3D12_BARRIER_GROUP group{.Type = D3D12_BARRIER_TYPE_TEXTURE, .NumBarriers = 1, .pTextureBarriers = &barrier};
cmd->Barrier(1, &group);
}
// The textures are in RENDER_TARGET and DEPTH_STENCIL_WRITE already (above);
// otherwise, a texture barrier into those layouts comes first.
cmd->OMSetRenderTargets(1, &rtv, FALSE, &dsv);
const float clearColor[4] = {0.1f, 0.1f, 0.1f, 1.0f};
cmd->ClearRenderTargetView(rtv, clearColor, 0, nullptr); // clears are commands, not load ops
cmd->ClearDepthStencilView(dsv, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, nullptr);
const D3D12_VIEWPORT viewport{0.0f, 0.0f, static_cast<float>(kWidth), static_cast<float>(kHeight), 0.0f, 1.0f};
const D3D12_RECT scissor{0, 0, static_cast<LONG>(kWidth), static_cast<LONG>(kHeight)};
cmd->RSSetViewports(1, &viewport);
cmd->RSSetScissorRects(1, &scissor);
ID3D12DescriptorHeap *heaps[] = {viewHeap.Get()};
cmd->SetDescriptorHeaps(1, heaps); // before the root signature that indexes it
cmd->SetGraphicsRootSignature(rootSignature.Get());
cmd->SetPipelineState(pipeline.Get());
cmd->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
const DrawRoot root{.color = {1.0f, 0.5f, 0.0f, 1.0f}, .depth = 0.5f};
cmd->SetGraphicsRoot32BitConstants(0, sizeof(root) / 4, &root, 0);
cmd->DrawInstanced(3, 1, 0, 0);
// There is no "end": the next barrier moves the textures to where shaders
// read them, and makes the attachment writes visible.
textureBarrier(cmd.Get(), color.Get(), D3D12_BARRIER_LAYOUT_RENDER_TARGET, D3D12_BARRIER_LAYOUT_SHADER_RESOURCE,
D3D12_BARRIER_SYNC_RENDER_TARGET, D3D12_BARRIER_ACCESS_RENDER_TARGET,
D3D12_BARRIER_SYNC_PIXEL_SHADING | D3D12_BARRIER_SYNC_COMPUTE_SHADING,
D3D12_BARRIER_ACCESS_SHADER_RESOURCE);
textureBarrier(cmd.Get(), depth.Get(), D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE,
D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ, D3D12_BARRIER_SYNC_DEPTH_STENCIL,
D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE,
D3D12_BARRIER_SYNC_PIXEL_SHADING | D3D12_BARRIER_SYNC_DEPTH_STENCIL,
D3D12_BARRIER_ACCESS_SHADER_RESOURCE | D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ);
What to watch for: the sync and access values must be allowed by the layouts on each side, and global barriers cannot change layouts.
Native code that operates on RI's textures reads each texture's resting layout from RI::Vk::native(texture).restingLayout or RI::D3D12::native(texture).restingLayout, and must return the texture to that layout before RI uses it again. See Vulkan: native handles and D3D12: native objects.