Search code examples
c++opengltexture-mapping

stretching one texture over multiple quads


To texture map a single quad the following code works:

glBegin( GL_QUADS);
  glTexCoord2f( 0,0 ) ;
  glVertex3f( -1,-1,0);

  glTexCoord2f(1,0);
  glVertex3f(  1,-1,0);

  glTexCoord2f(1,1);
  glVertex3f(  1, 1,0);

  glTexCoord2f(0,1);
  glVertex3f( -1, 1,0);
glEnd();

My question is, how can I map the following multiple quad with one texture. The for loop creates a 10x10 quad made by smaller quads of 2 unit edges, I want to stretch my texture from 1x1th quad to 10x10th quad:

void wall(int num)
{
int wallx;
int wally;
for(wallx=0;wallx<num;wallx++)
{
    for(wally=0;wally<num;wally++)
    {
    glPushMatrix();
        glBegin( GL_QUADS);
        glVertex3f( -1 + wallx*2,-1+ wally*2,0 );           
        glVertex3f(  1+ wallx*2,-1+ wally*2,0 );             
        glVertex3f(  1+ wallx*2, 1+ wally*2,0 );             
        glVertex3f(  -1+ wallx*2, 1+ wally*2,0 );           
            glEnd();
    glPopMatrix();
    }
}

}


Solution

  • If you think about it, this is just about specifying the correct texture coordinate for each quad.

    float unitx = 1.0f/(float)num;
    float unity = 1.0f/(float)num;
    for(wallx=0;wallx<num;wallx++)
    {
        for(wally=0;wally<num;wally++)
        {
        glPushMatrix();
            glBegin( GL_QUADS);
            glTexCoord2f( unitx * (float) wallx, unity * (float) wally );
            glVertex3f( -1 + wallx*2,-1+ wally*2,0 );    
            glTexCoord2f( unitx * (float) (wallx+1), unity * (float) wally );
            glVertex3f(  1+ wallx*2,-1+ wally*2,0 );             
            glTexCoord2f( unitx * (float) (wallx+1), unity * (float) (wally+1) );
            glVertex3f(  1+ wallx*2, 1+ wally*2,0 );             
            glTexCoord2f( unitx * (float) wallx, unity * (float) (wally+1) );
            glVertex3f(  -1+ wallx*2, 1+ wally*2,0 );           
                glEnd();
        glPopMatrix();
        }
    }