Texture Mapping: Applying Textures to a Cube in OpenGL

Zerihun M.
3 min readAug 24, 2024

--

Welcome back to our OpenGL adventure! Have you ever thought about how cool it would be to make your 3D objects look more realistic, like giving them the appearance of wood, metal, or even grass? This is where textures come in handy! Today, we’re going to learn how to apply textures to 3D objects in OpenGL using a BMP image without relying on any external libraries.

What is a Texture?

A texture is like a picture that you can wrap around your 3D objects, just like putting a label on a can. This makes the object look like it’s made of whatever is in the picture, such as bricks, wood, or fabric.

Steps to Apply a Texture in OpenGL

Let’s go step by step to apply a texture to a 3D object in OpenGL. We’ll use a simple square (a 2D quad) for this example.

1. Loading a BMP Image as a Texture

Since we’re not using any external libraries, we need to write a function to load a BMP image and turn it into a texture. Here’s a simple function that does just that:

bmp texture loader function

2. Enable Texturing in OpenGL

Once you have your BMP image loaded, you need to enable 2D texturing in OpenGL and bind your texture.

3. Apply the Texture to a 3D Cube

Now, let’s apply the texture to a 3D cube. A cube has six faces, so we’ll apply the texture to each face.

draw cube function

4. Run Your Program

Set up your main function to initialize OpenGL, set up the display function, and start the main loop.

Output:

To access the complete source code and texture file, click here and get started with texturing your own 3D objects!

How Does the Code Work?

Let’s break down the code:

  • loadBMP(): This function loads a BMP file and creates an OpenGL texture from it.
  • glEnable(GL_TEXTURE_2D);: Turns on 2D texturing in OpenGL.
  • glBindTexture(GL_TEXTURE_2D, texture);: Binds the texture we loaded to the cube.
  • glTexCoord2f(): Maps each vertex of the cube to a specific point on the texture.

Experimenting with Textures

Try using different BMP images as textures and applying them to the cube. Notice how each face of the cube can have a different part of the texture!

Conclusion

Texturing a 3D object like a cube in OpenGL can make your objects look more detailed and realistic. With just a BMP image and a bit of code, you can create cool effects and bring your 3D scenes to life. Now that you’ve learned how to apply textures to a cube, go ahead and try it with different textures and objects.

Related Posts:

--

--

Zerihun M.

OpenGL expert sharing insights and tutorials on basic and advanced graphics programming and development techniques.