Command Buffers and Sort Keys
Gameplay code should not talk to the GPU directly. If every system called glUseProgram and glDrawElements the moment it wanted something on screen, draws would arrive in whatever order the systems happened to run. The GPU would switch shaders, textures and blend states again and again, and the renderer could never move to another thread.
Most engines therefore split rendering into two halves:
| Half | Runs | Does |
|---|---|---|
| Front end | on the game or render thread | culls the scene, then records small draw commands into a command buffer |
| Back end | on the render thread | sorts the commands, then executes them with the real graphics API |
A command is plain data: which mesh, which material, which shader, how far from the camera. Because it is data, it can be sorted, merged, sent to another thread, recorded on several threads at once and replayed for debugging. Vulkan, Direct3D 12 and Metal use the same idea at the API level: you record a GPU command buffer and submit it later.
A 64-bit sort key
Sorting structs with a custom comparator that looks at five fields is slow and easy to get wrong. Instead, pack everything that decides the order into one 64-bit integer, most important bits first. Sorting the keys then sorts by layer, then by shader, then by material, then by depth, with a single integer comparison.
| Bits | Field | Why it is there |
|---|---|---|
| 63–60 | layer / pass (opaque, transparent, UI) | layers must draw in order |
| 59–52 | shader id | shader switches are the most expensive state change |
| 51–40 | material id | textures and constants next |
| 39–16 | depth (24 bits) | front to back for opaque objects (early-z rejects hidden pixels) |
| 15–0 | command index | keeps the sort stable and finds the payload |
Transparent objects must be drawn back to front for blending to look right, so in the transparent layer the depth bits are inverted and placed above the shader bits: correctness beats saving state changes.
#include <algorithm>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
enum Layer : std::uint64_t { Opaque = 0, Transparent = 1, UI = 2 };
struct DrawCmd {
std::string name;
Layer layer;
std::uint32_t shader, material;
float depth; // 0 = near plane, 1 = far plane
};
std::uint64_t depthBits(float d) { return std::uint64_t(d * 0xFFFFFF) & 0xFFFFFF; }
std::uint64_t makeKey(const DrawCmd& c, std::uint16_t index) {
std::uint64_t k = std::uint64_t(c.layer) << 60;
if (c.layer == Transparent) {
k |= (0xFFFFFF - depthBits(c.depth)) << 36; // far first, then shader
k |= std::uint64_t(c.shader & 0xFF) << 28;
} else {
k |= std::uint64_t(c.shader & 0xFF) << 52;
k |= std::uint64_t(c.material & 0xFFF) << 40;
k |= depthBits(c.depth) << 16; // near first
}
return k | index;
}
int execute(const std::vector<DrawCmd>& cmds, const std::vector<std::uint64_t>& order, bool print) {
std::uint32_t shader = ~0u, material = ~0u;
int changes = 0;
for (std::uint64_t key : order) {
const DrawCmd& c = cmds[key & 0xFFFF];
if (c.shader != shader) { shader = c.shader; changes++; }
if (c.material != material) { material = c.material; changes++; }
if (print) std::cout << " " << std::left << std::setw(10) << c.name << " shader " << c.shader
<< " material " << c.material << " depth " << c.depth << "\n";
}
return changes;
}
int main() {
std::cout << std::fixed << std::setprecision(2);
std::vector<DrawCmd> cmds = {
{"rock", Opaque, 1, 10, 0.40f}, {"window", Transparent, 3, 30, 0.20f},
{"tree", Opaque, 2, 20, 0.70f}, {"health", UI, 4, 40, 0.00f},
{"rock2", Opaque, 1, 10, 0.10f}, {"smoke", Transparent, 3, 31, 0.60f},
{"tree2", Opaque, 2, 20, 0.30f}, {"crate", Opaque, 1, 11, 0.50f},
};
std::vector<std::uint64_t> keys;
for (std::uint16_t i = 0; i < cmds.size(); i++) keys.push_back(makeKey(cmds[i], i));
int unsorted = execute(cmds, keys, false);
std::sort(keys.begin(), keys.end());
std::cout << "sorted draw order:\n";
int sorted = execute(cmds, keys, true);
std::cout << "state changes: " << unsorted << " unsorted, " << sorted << " sorted\n";
}sorted draw order:
rock2 shader 1 material 10 depth 0.10
rock shader 1 material 10 depth 0.40
crate shader 1 material 11 depth 0.50
tree2 shader 2 material 20 depth 0.30
tree shader 2 material 20 depth 0.70
smoke shader 3 material 31 depth 0.60
window shader 3 material 30 depth 0.20
health shader 4 material 40 depth 0.00
state changes: 16 unsorted, 10 sorted
Opaque draws are grouped by shader, then material, then near to far. The transparent smoke (farther) draws before window, and the UI comes last. Counting a change whenever the shader or the material differs from the previous draw, sorting brought 16 changes down to 10. With thousands of draws the saving is much larger, because most objects share a handful of shaders.
Note: Don't sort full structs. Sort the 8-byte keys (or
key, indexpairs) and look the payload up through the index bits. Radix sort on 64-bit keys is a common upgrade when profiling shows the sort itself matters.
Commands are a small instruction set
Draws are not the only commands. The back end also needs "set viewport", "clear", "update this uniform buffer", "copy this texture". A common layout is a tagged union or a linear byte buffer of variable-sized packets, each starting with a type field:
enum class CmdType : uint8_t { Clear, SetViewport, UpdateBuffer, Draw };
struct CmdHeader { CmdType type; uint16_t size; }; // followed by the command's payload
struct DrawPacket {
CmdHeader header{CmdType::Draw, sizeof(DrawPacket)};
uint32_t mesh, material, firstIndex, indexCount;
float worldMatrix[16];
};The front end writes packets into a per-thread linear allocator (see Linear and Stack Allocators) that is reset every frame, so recording costs a pointer bump. Each worker thread records into its own buffer; the back end merges the keys of all buffers and sorts them once. No locks are needed while recording.
Double buffering between threads
A render thread executes frame N while the game thread records frame N+1. That means two (or three) sets of command buffers, swapped at a sync point:
game thread: [update N+1][record N+1] | [update N+2][record N+2] |
render thread: [sort+execute N ] | [sort+execute N+1 ] |
swap ---^ swap ---^Everything a command points to must stay alive until the back end has used it. That is why commands carry handles to meshes and materials (see Generational Handles) and copies of small data such as matrices, never pointers into gameplay objects that might be destroyed in the meantime.
How engines and APIs expose this
| Where | What it looks like |
|---|---|
| Vulkan | vkBeginCommandBuffer, vkCmdBindPipeline, vkCmdDraw…, vkQueueSubmit |
| Direct3D 12 | ID3D12GraphicsCommandList, executed with ExecuteCommandLists |
| bgfx | bgfx::submit(view, program, depth) records a draw; bgfx builds and sorts the keys itself |
| Unreal Engine | the render thread consumes commands queued with ENQUEUE_RENDER_COMMAND, then RHI command lists |
The next lesson, Render Graphs, works one level up: it orders whole passes rather than individual draws.
Test yourself
Why are the shader bits placed above the material bits in an opaque sort key?
- Shader ids are smaller numbers
- Switching shaders costs more than switching materials, so grouping by shader saves the most
- The GPU requires it
- It makes transparent objects sort back to front
Why are transparent draws sorted by depth before shader, back to front?
- To save shader switches
- Blending gives the right result only if farther surfaces are drawn first
- Because early-z only works for transparent objects
- Transparent objects have no material
Why should a recorded draw command hold a handle and a copied matrix instead of a pointer to the game object?
- Pointers are bigger
- The back end may execute it later or on another thread, after the object has moved or been destroyed
- Handles are faster to dereference
- Matrices can't be pointed to