Creating the Command Buffers

A command buffer stores a sequence of commands

Each image created alongside the swapchain in the previous section must have an associated command buffer.

What is a command buffer?

A command buffer is a section of memory which stores a sequence of commands such as draw calls and memory transfer operations. Commands are recorded into command buffers in advance, and then, later in the application, these command buffers are submitted to a queue ready for execution by the GPU. Vulkan makes very few implicit guarantees about the order in which the GPU will execute commands but it can be assumed that commands in the same command buffer will be executed in the order they were recorded. Synchronisation of operations between different command buffers requires synchronisation objects such as semaphores, fences and events. These will be covered later in this guide.

This approach of splitting the recording of the GPU commands from their submission to the queue should improve performance. This is because the driver will know, in advance, how much work is incoming and can therefore divide this work more optimally between multiple threads.

Command buffers are allocated from a larger memory pool called a command pool. This object allows the application to spread the cost of resource creation and command recording. The amount of memory allocated is determined dynamically when the command buffer is recorded.

Command pools are linked to a specific queue family, so only command buffers allocated from that command pool can be submitted to queues from that specific queue family. Command pools also have flags which can be used to specify the usage behaviour of the command buffers allocated from the command pool.

In this example, the command buffer associated with each image will contain the commands to render that image. The final rendered output to each image will be slightly different depending on the rotation value of the triangle. This will be explained more fully when creating the uniform buffer to store the transformation matrices.

Example: initCommandPoolAndBuffer()

In the example code, a command pool is created and is linked to the graphics queue family found earlier. The usage flag is also set to VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT during creation which allows the command buffers to be reset individually rather than all at once.

A number of primary command buffers equal to the number of swapchain images are then allocated. It is also possible to create secondary command buffers in Vulkan which can only be executed from primary command buffers but this is not required here.