how to use glDrawPixels to render a picture as a background

3.4k views Asked by At

Here is the thing: I want to load a picture as a background filled in the whole viewport. This background should always face to the camera no matter where the camera face to. First I naturally think use a texture as a background, my code is below:

glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0,1,0,1,0,1);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();

glBindTexture(GL_TEXTURE_2D, myimage.GetID());
glEnable(GL_TEXTURE_2D);

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

glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glDisable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);

Believe me, myimage is a CIMAGE class that can load pics into textures, it works well. However, for some unknown reason, my application cannot load a texture into a rectangle. (I described this problem here click) As a result, I only can see a rectangle frame around my viewport.

So, I figure out another solution.

I use the glDrawPixels instead of a texture. My code is below:

glRasterPos2i(0, 0);
glDrawPixels(myimage.GetWidth(), myimage.GetHeight(), (myimage.GetBPP() == 24)?GL_RGB:GL_RGBA, GL_UNSIGNED_BYTE, 
    myimage.GetData());

The picture appeared! However, the pic didn't always face to my camera. It only appears in a particular direction. You know, like a object in the scene, but not a background always face to the camera.

So anybody know how to use the glDrawPixels to implement a background?

By the way, I think this background is not a object placed in the 3D scene. So billboards may not be my solution. Again, this background filled in the whole view port and always face to camera.

1

There are 1 answers

1
Ani On BEST ANSWER

One of the reasons your texture loading might not work is because it might not have power-of-two dimensions. Try a square 256x256 texture (or the like) to see if this is the problem. Look here for more info on Rectangle Textures.

Coming back to your background issue - the right way to do this would be to

  1. Set up an orthographic projection/viewport that fills the entire screen.

    glViewport(0,0,nw,nh);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0,1,0,1,0,1);
    glMatrixMode(GL_MODELVIEW);
    
  2. Disable depth testing

  3. Draw the fullscreen quad with the texture/texture rectangle you have loaded.

    glBegin(GL_QUADS);
    glVertex2f(0,0);
    glVertex2f(1,0);
    glVertex2f(1,1);
    glVertex2f(0,1);
    glEnd();
    
  4. Set up your regular projection/modelview and continue.

Hope this helps!