Hello,
I am making my first attempt to use textures. I create a 128x128 texture filled with gray, except for one red pixel at the beginning. Then I draw a 128x128 square with this texture. The result that I get is a 128x128 red square, instead of the gray square that I should get. Similar thing happens if I change the color the first pixel to whatever color.
I have spent considerable time reading tutorials and examples, still I cannot see what is wrong with my code. Is there anything obvious I forgot ?
I programming under Ubuntu Lucid Lynx (64bits) with an ATI Radeon HD 5600 and gcc.
OpenGL version string: 3.2.9756 Compatibility Profile Context
Here is the code itself. For readability, I made my best to minimize it. In particular, I removed every call to glError().
#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int window_width;
int window_height;
GLuint id_texture;
GLubyte* texture;
void display()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glBindTexture(GL_TEXTURE_2D,id_texture);
glBegin(GL_QUADS);
glVertex2f(0, 0);
glVertex2f(128, 0);
glVertex2f(128, 128);
glVertex2f(0, 128);
glEnd();
glFlush();
glutPostRedisplay();
}
void reshape (int w, int h)
{
window_width = w;
window_height = h;
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
glViewport (0, 0, (GLsizei)window_width, (GLsizei)window_height);
glOrtho (0, window_width, window_height, 0, 0, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void init()
{
window_width = glutGet(GLUT_WINDOW_WIDTH);
window_height = glutGet(GLUT_WINDOW_HEIGHT);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
glViewport (0, 0, (GLsizei)window_width, (GLsizei)window_height);
glOrtho (0, window_width, window_height, 0, 0, 1);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();
glEnable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
glGenTextures(1,&id_texture);
glBindTexture(GL_TEXTURE_2D,id_texture);
texture = (GLubyte*) malloc(4*128*128*sizeof(GLubyte));
for (int i = 0; i < 128*128*4; i++)
{
texture[i] = 127;
}
texture[0]= 255;
texture[1]= 0;
texture[2]= 0;
texture[3]= 255;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, 128, 128, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture);
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA | GLUT_DEPTH);
glutCreateWindow("texture test");
glutDisplayFunc(display);
init();
glutReshapeFunc (reshape);
glutMainLoop();
free(texture);
return 0;
}