OpenGL Textures

I'm having a hard time figuring out how to import custom textures / sprites into OpenGL through C++.

I have looked around and most of the codes doesn't texture the shape.

All I want to know is how do I texture, say a 64x64 rectangle with a bmp file type?

I would appreciate if someone posted the code and explained it so I can understand how to do it.

Thanks
First you have to read the .bmp file into the program. There are libraries for this, but OpenGL will not do it for you.

After that, this code should set up the texture:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
glEnable(GL_TEXTURE_2D);
glEnableClientState(GL_TEXTURE_COORD_ARRAY); //only if you are using VBOs before OpenGL 3.0

GLuint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);

//texture parameters; check the reference pages for alternate settings
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);

//optional extension for anisotropic filtering (requires the extension to be available)
float maximumAnisotropy;
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maximumAnisotropy);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, maximumAnisotropy);

gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB8, textureSizeX, textureSizeY, GL_BGR, GL_UNSIGNED_BYTE, texturePixelsPointer);


gluBuild2DMipmaps might be deprecated in your OpenGL version, but it should work anywhere.

When you draw the rectangle, you need to supply texture coordinates to each vertex. This is easy for rectangles: set the bottom left to (0, 0), the bottom right to (1, 0), the upper left to (0, 1), and the upper right to (1, 1). If the texture ends up rotated, play with these values until it faces the right way.

If you're using shaders, you'll have to change the fragment shader instead of enabling GL_TEXTURE_2D. I'm assuming this is not the case.
Last edited on
Making it read the .bmp into the texture it the bit I'm mainly having problems with.

Can I used fstream? or fopen? Or something which is standard C++? Or will I have to download another library for it?
While you could potentially use fstream, this would be a bad idea. The Wikipedia page for BMP file format shows that there are many options that can appear in the header, and you would have to account for all of them in order to read all bitmaps.

What library did you use to create the window?
Using Windows, so <Windows.h>, it is a Win32 project too.

And checking the wiki page out now
Topic archived. No new replies allowed.