Hi, I do currently have this code which task is to read a bitmap file and then store it as an OpenGL texture.
This code does compile, but whenever I run it, it will crash. Note that if I remove all the gl-commands after the loop (glBindTexture() to gluBuild2DMipmaps()) it will not crash, but I will not have gotten my texture either.
Am I doing something wrong? Is there an easier way to accomplish this task?
int LoadBitmap(std::string filename)
{
unsigned char *l_texture; // The pointer to the memory zone in which we will load the texture
int width, height, size; //Storage for bitmap-info
num_texture++; // A variable which keeps track of the number of textures
FILE *mf;
mf = fopen(filename.c_str(), "rb"); //Open file
if (mf == NULL) //Check if the file opened
exit(13);
fseek(mf, 18, SEEK_SET);
fread(&width, sizeof(int), 1, mf); //Read in the width of the image
fseek(mf, 22, SEEK_SET);
fread(&height, sizeof(int), 1, mf); //Read in the height of the image
size = height * width * 4; //The size for all the important bytes
// Now we need to allocate the memory for our image (width * height * color deep)
l_texture = (unsigned char *) malloc(size);
// And fill it with zeros
memset(l_texture, 0, size);
// At this point we can read every pixel of the image
for (int i=0; i < size; i += 4)
{
// We load the red, green and blue values
char r, g, b;
fread(&r, 1, 1, mf);
fread(&g, 1, 1, mf);
fread(&b, 1, 1, mf);
// And store it
l_texture[i+0] = r; // Red component
l_texture[i+1] = g; // Green component
l_texture[i+2] = b; // Blue component
l_texture[i+3] = 255; // Alpha value
}
fclose(mf); // Closes the file stream
glBindTexture(GL_TEXTURE_2D, num_texture); // Bind the ID texture specified by the 2nd parameter
// The next commands sets the texture parameters
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // If the u,v coordinates overflow the range 0,1 the image is repeated
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // The magnification function ("linear" produces better results)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); //The minifying function
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); // We don't combine the color with the original surface color, use only the texture map.
// Finally we define the 2d texture
glTexImage2D(GL_TEXTURE_2D, 0, 4, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, l_texture);
// And create 2d mipmaps for the minifying function
gluBuild2DMipmaps(GL_TEXTURE_2D, 4, width, height, GL_RGBA, GL_UNSIGNED_BYTE, l_texture);
free(l_texture); // Free the memory we used to load the texture
return num_texture; // Returns the current texture OpenGL ID
}
Properly formatted with colors at pastebin
Note, this is c++ ,but I am mainly worried about the gl-calls.