GLuint createTexture(const char* filename, int width=128, int height=128)
{
GLuint texture;
Use C99 variadic array to allocate width*height*3 bytes of memory on the stack. If there's not enough stack left, the program crashes with a stack overflow.
char bitmap[width][height][3];
Try opening the file to fetch the texture from. The file must be a headerless, raw, tight array of 8 bit per channel RGB data.
FILE* fp=fopen(filename, "rb");
Terminate the program if opening the file failed. Technically using assert for this purpose is a programming error, because a) assert does nothing in release builds and b) this is an easy to recover from error. The function should just return 0 if the file couldn't be opened.
assert(fp);
Read width*height chunks of 3 bytes. sizeof(char)
indicates the writer of this had no clue about C, because the C standard defines sizeof(char) == 1
, so there's no point in doing that multiplication.
If not the expected amount of data could be read, crash the program if in debug mode. In case of error and a release build do strange things.
assert(fread(bitmap, 3*sizeof(char), width*height, fp) == width*height);
Close the file.
fclose(fp);
Allocate a OpenGL texture object handle.
glGenTextures(1, &texture);
Bind the texture handle so that subsequent OpenGL operations affecting textures are operating on the given object.
glBindTexture(GL_TEXTURE_2D, texture);
Set the texture magnification and minification filters. Use linear, so that mipmap levels are not required.
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
Copy the data into the OpenGL texture. Since this uses a newly allocated texture object handle, the texture is also initialized by this.
A lot of important steps are missing here. Namely glPixelStorei must be used to prepare OpenGL to read data from the array. Line alignment, strides and so on.
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE,bitmap);
Unbind the texture object.
glBindTexture( GL_TEXTURE_2D,0);
Return texture object handle.
return texture;
}
Major issues with this code: No OpenGL error checks and crashing the program if in debug builds. In release builds no file operation errors are detected and handled.
DON'T USE THIS CODE!