Creating a Texture Image

A texture determines how to colour the fragments inside the triangle

The application needs a way of determining how to colour the fragments inside the triangle. A simple way to do this is texture mapping.

What is texture mapping?

Texture mapping is a graphics technique where the fragment shader samples a 2D image (texture) for the colour information at a particular pixel (texel) and then applies this colour to the corresponding fragment in the triangle.

The way that the texture maps onto the triangle is determined by the texture co-ordinates (u,v) at each vertex. These are written into the vertex buffer along with the position co-ordinates. These texture co-ordinates refer to the locations on the 2D texture which should be sampled to determine the colour of the fragment at the vertex. They also act as anchor points from which the texture co-ordinates of each of the remaining fragments in a triangle can be interpolated.

Example: initTexture()

Vulkan offers an image object (VkImage) which can hold the texel data (this is the terminology for pixels in a texture) and allows the fragment shader to access it (via a descriptor set). This is the same kind of object which holds the images created with the swapchain.

The code example demonstrates the multi-step process to create an image object and upload texture data into it. The texture data is not loaded from file in this case, instead a custom function generates a checkered pattern texture on-the fly. It also makes use of a custom helper function for buffer creation that was used earlier to create the vertex and uniform buffers.

This procedure is fairly complex because the application has to ensure the texture data is laid out correctly in the GPU memory.