I have a TGA texture containing this image:
The texture is 256x256.
So I'm trying to load it and map it to a cube:
#import <OpenGL/OpenGL.h>
#import <GLUT/GLUT.h>
#import <stdlib.h>
#import <stdio.h>
#import <assert.h>
GLuint width=640, height=480;
GLuint texture;
const char* const filename= "/Users/ramy/Documents/C/OpenGL/Test/Test/texture.tga";
void init()
{
// Initialization
glEnable(GL_DEPTH_TEST);
glViewport(-500, -500, 1000, 1000);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, width/(float)height, 1, 1000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, 0, -100, 0, 0, 0, 0, 1, 0);
// Texture
char bitmap[256][256][3];
FILE* fp=fopen(filename, "r");
assert(fp);
assert(fread(bitmap, 3*sizeof(char), 256*256, fp) == 256*256);
fclose(fp);
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 256, 256, 0, GL_RGB, GL_UNSIGNED_BYTE, bitmap);
}
void display()
{
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture);
glColor3ub(255, 255, 255);
glBegin(GL_QUADS);
glVertex3f(0, 0, 0);
glTexCoord2f(0.0, 0.0);
glVertex3f(40, 0, 0);
glTexCoord2f(0.0, 1.0);
glVertex3f(40, 40, 0);
glTexCoord2f(1.0, 1.0);
glVertex3f(0, 40, 0);
glTexCoord2f(1.0, 0.0);
glEnd();
glDisable(GL_TEXTURE_2D);
glutSwapBuffers();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
glutInitWindowPosition(100, 100);
glutInitWindowSize(width, height);
glutCreateWindow(argv[0]);
glutDisplayFunc(display);
init();
glutMainLoop();
return 0;
}
But this is what I get when the window loads:
So just half of the image is correctly displayed, and also with different colors.Then if I resize the window I get this:
Magically the image seems to fix itself, even if the colors are wrong.Why?