kiwixz
kiwixz

Reputation: 1398

OpenGL: Can't get textures to display

I'm trying to add a texture to a simple square for more than 5h now but I still don't manage to do so.

Here's the code I'm using in paintGL():

glEnable(GL_TEXTURE_2D);

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

float pixels[] = {
    0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f
};

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, GL_RGB, GL_FLOAT, pixels);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
glBegin(GL_QUADS);
    glTexCoord2f(0.0f, 0.0f); glVertex3f(0,0,0);
    glTexCoord2f(1.0f, 0.0f); glVertex3f(1,0,0);
    glTexCoord2f(1.0f, 1.0f); glVertex3f(1,1,0);
    glTexCoord2f(0.0f, 1.0f); glVertex3f(0,1,0);
glEnd();

if (glGetError() != 0)
{
    qDebug() << glGetError();
}

There is no errors nor OpenGL's ones. I initialized the clear color to grey. When I try to change color with glColor3f(...), it works.

I read about all tutorials that I could find with Google but no one helped.

SOLUTION: I never put

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

at the right place: just after the glTexImage2D! Code above is edited and now work like a charm.

Upvotes: 0

Views: 774

Answers (2)

Anonymous
Anonymous

Reputation: 2172

You HAVE to specify filtering for your texture:

glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

Because default filter uses mipmaps, but you don't generate them.

Upvotes: 1

user1118321
user1118321

Reputation: 26395

It looks to me like you're only using one quarter of your texture. It's only 4 pixels, and you've set the texture coordinates to be just the first pixel. If that pixel is white and your texture environment is set to multiply the quad's color by the texture, and you're set to use nearest neighbor sampling, then you'll get just the color. Try changing the texture coordinates to be (0,0) to (1,1) instead of (0,0) to (0.5,0.5) and see if that gives you the expected result. You can also try setting the various texture parameters and environments differently to see how that affects your drawing.

Upvotes: 1

Related Questions