0
votes

To be short, why couldn't I put two glBindTexture into one glBegin(GL_QUADS)...glEnd()?

I am following chapter 9 of OpenGL red book, http://www.glprogramming.com/red/chapter09.html

In example 9-5, program texbind.c produces two quads with different texture, like this: enter image description here

The quad on the left has a white checker board texture while the quad on the right has a red one.

Here is the code which maps the textures to two quads:

void display(void)
{
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glBindTexture(GL_TEXTURE_2D, texName[0]);
  glBegin(GL_QUADS);
  glTexCoord2f(0.0, 0.0); glVertex3f(-2.0, -1.0, 0.0);
  glTexCoord2f(0.0, 1.0); glVertex3f(-2.0, 1.0, 0.0);
  glTexCoord2f(1.0, 1.0); glVertex3f(0.0, 1.0, 0.0);
  glTexCoord2f(1.0, 0.0); glVertex3f(0.0, -1.0, 0.0);
  glEnd();
  glBindTexture(GL_TEXTURE_2D, texName[1]);
  glBegin(GL_QUADS);
  glTexCoord2f(0.0, 0.0); glVertex3f(1.0, -1.0, 0.0);
  glTexCoord2f(0.0, 1.0); glVertex3f(1.0, 1.0, 0.0);
  glTexCoord2f(1.0, 1.0); glVertex3f(2.41421, 1.0, -1.41421);
  glTexCoord2f(1.0, 0.0); glVertex3f(2.41421, -1.0, -1.41421);
  glEnd();
  glFlush();
}

We can see that even though the code uses GL_QUADS it draws one quad in each GL_QUADS state. However, if I comment out the glEnd() and glBegin(GL_QUADS) in the middle of this code, like this:

void display(void)
{
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glBindTexture(GL_TEXTURE_2D, texName[0]);
  glBegin(GL_QUADS);
  glTexCoord2f(0.0, 0.0); glVertex3f(-2.0, -1.0, 0.0);
  glTexCoord2f(0.0, 1.0); glVertex3f(-2.0, 1.0, 0.0);
  glTexCoord2f(1.0, 1.0); glVertex3f(0.0, 1.0, 0.0);
  glTexCoord2f(1.0, 0.0); glVertex3f(0.0, -1.0, 0.0);
  // glEnd();
  glBindTexture(GL_TEXTURE_2D, texName[1]);
  // glBegin(GL_QUADS);
  glTexCoord2f(0.0, 0.0); glVertex3f(1.0, -1.0, 0.0);
  glTexCoord2f(0.0, 1.0); glVertex3f(1.0, 1.0, 0.0);
  glTexCoord2f(1.0, 1.0); glVertex3f(2.41421, 1.0, -1.41421);
  glTexCoord2f(1.0, 0.0); glVertex3f(2.41421, -1.0, -1.41421);
  glEnd();
  glFlush();
}

It turns out the second glBindTexture(GL_TEXTURE_2D, texName1) does not work anymore. And the result is:

enter image description here

Could anyone tell me why I cannot put two glBindTexture into one GL_QUADS state?

1

1 Answers

5
votes

Because OpenGL doesn't support doing that.

The only calls you can make to OpenGL while inside glBegin/glEnd are vertex submission calls like glTexCoord*, glVertex*, etc. Anything else is an error.

As to "why", one reason is "because the specification says so". More likely, the GPU processes the entire data set (or significant chunks of it) in parallel, during which it cannot switch textures.

Also consider the newer way of drawing with OpenGL: uploading your data to a Vertex Buffer Object and calling one of the glDraw* commands. There's no way you can even call glBindTexture in between primitives using that.