Textures
- Tags
- opengl
A texture is an image that opengl can load and apply onto a surface at runtime.
Different image formats need to be loaded seperately. Writing an image loader for all
of these is too time consuming to be practical so we use pre-made libraries for this.
The stb_image
library is a common choice. We can load an image like so:
int width, height, nrChannels;
unsigned char *data = stbi_load("container.jpg", &width, &height, &nrChannels, 0);
// free with `stbi_image_free(data)`.
Loading a texture
First we create an ID to reference the texture on the GPU.
unsigned int texture;
glGenTextures(1, &texture);
// let's also go ahead and bind it now.
glBindTexture(GL_TEXTURE_2D, texture);
Then we assign the texture data
glTexImage2D(
GL_TEXTURE_2D, // Specify the texture target. Each bound texture has space for 1D, 2D and 3D. Assigning a 2D texture doesn't overwrite any existing 1D/3D texture.
0, // mipmap level, in-case we want to assign it manually.
GL_RGB, // The kind of format we'll store the texture in.
width, // The width of the texture being loaded.
height, // The height of the texture being loaded.
0, // don't care... just always make it 0. *legacy stuff*
GL_RGB, // The format of the texture data we're loading from.
GL_UNSIGNED_BYTE, // The datatype of the texture data we're loading from.
data // Texture data to load.
);
We can also optionally declare it as a mipmap.
glGenerateMipmap(GL_TEXTURE_2D);