Creating a Uniform Buffer

A uniform buffer holds data that will be passed to uniform variables in shaders

In addition to the vertex attributes, the vertex shader also has another input, a uniform variable for the transformation matrix. As before, this has to be stored somewhere so the shader can read in the data. A uniform buffer can be used to do this.

What is a uniform buffer?

Uniform variables in shaders act as parameters which can be passed into the shader by the developer. This means they will stay the same for all vertices or fragments during a single render pass. A uniform buffer is used to hold the data that will be passed to these uniform variables.

Example: initUniformBuffers()

In the guide example, as mentioned before, the transformation matrices are the product of a fixed orthographic projection matrix and a rotation matrix. The rotation matrix is calculated from a rotation value which is incremented on every frame. This means that the rotation matrix will change between frames and therefore the transformation matrix must be recalculated on every frame. This implies that the uniform buffers which are used to store the transformation matrices have to be dynamic because they are going to be rewritten regularly.

The number of uniform buffers that are required will be equal to the number of images in the swapchain because each image corresponds to a different frame with a slightly different rotation value. Instead of creating several buffers, initUniformBuffers() creates one large buffer with a slice allotted for each image. The data for each individual buffer can then be accessed by using an offset. The large buffer is created using the createBuffer() helper function which was used before to create the vertex buffer.