0
votes

I'm trying to write some code that will render a texture onto a simple square, but have been having a lot of trouble getting it to work. I downloaded some example source code for texture mapping here and compiled it and it seems to do texture mapping fine onto their cylinder. Then, I added some of my code to see if it would render the texture onto my square, but it just textures it with a solid color that seems to be halfway between red and black instead of a checkerboard like it appears on the cylinder. Here is the code I added, right after the call to gluCylinder on the first pass:

glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glVertex2f(-1, -1);
glTexCoord2f(1,0);
glVertex2f(1, -1);
glTexCoord2f(1, 1);
glVertex2f(1,  1);
glTexCoord2f(0,1);
glVertex2f(-1,  1);
glEnd();

Is there any reason why textures would render normally on the cylinder but not on my quad?

1

1 Answers

5
votes

The example code is enabling automatic texture coordinate generation, so your glTexCoord2f calls are being ignored. The automatic generation is being projected onto a Z plane. Since your quad is a Y plane, it's essentially just stretching one pixel of your texture across the entire quad.

To get it to work, disable the automatic texture generation before your glBegin, and then re-enable it after the glEnd.

i.e.:

glDisable(GL_TEXTURE_GEN_S);
glDisable(GL_TEXTURE_GEN_T);

glBegin(GL_QUADS);
   glTexCoord2f(0, 0);
   glVertex2f(-1, -1);
   glTexCoord2f(1,0);
   glVertex2f(1, -1);
   glTexCoord2f(1, 1);
   glVertex2f(1,  1);
   glTexCoord2f(0,1);
   glVertex2f(-1,  1);
glEnd();

glEnable (GL_TEXTURE_GEN_S);
glEnable (GL_TEXTURE_GEN_T);

Alternatively, you could set the automatic texture generation to project on the Y plane, and omit the glTexCoord2f calls, and then set it back to Z when you're done:

float zPlane[4] = {0., 0., 1., 0.};
float yPlane[4] = {0., 1., 0., 0.};
glTexGenfv (GL_T, GL_OBJECT_PLANE, yPlane);

glBegin(GL_QUADS);
   glVertex2f(-1, -1);
   glVertex2f(1, -1);
   glVertex2f(1,  1);
   glVertex2f(-1,  1);
glEnd();

glTexGenfv (GL_T, GL_OBJECT_PLANE, zPlane);