Pixel accurate 2D texture mapping

Ok, this is embarrassing, and I should probably know how to do it. Nonetheless, I cannot get it to work.

Task: Render a 2D image stored in a texture of size w by h. The output image is also supposed to have a size of w by h, and is supposed to look exactly the same. (This is obviously for a shader-based image processing step.) The output goes into an FBO larger than w by h.

My approach:

glViewport(0, 0, w, h);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, w - 1.0, 0.0, h - 1.0);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

glBegin(GL_QUADS);
    glTexCoord2f(0.0, 0.0);
    glVertex2i(0, 0);

    glTexCoord2f(1.0, 0.0);
    glVertex2i(w - 1, 0);

    glTexCoord2f(1.0, 1.0);
    glVertex2i(w - 1, h - 1);

    glTexCoord2f(0.0, 1.0);
    glVertex2i(0, h - 1);
glEnd();

Looks easy enough. The maximum coordinates used are (w - 1) and (h - 1). Therefore, the subtraction of 1 for gluOrtho2D, and when defining the rectangle vertices. glViewport, which expects absolute widths and heights, is simply passed w and h.

Somehow, bottom column(s) and/or right row(s) from the original are missing in the output. In the output, the image is slightly distorted and shifted. Under normal circumstances, that would hardly be perceptible, but for multi-stage image processing, it’s deadly.

I have also tried to debug the process by drawing a clearly visible red outline rectangle (glBegin(GL_LINE_LOOP)) at these exact coordinates. I was not able to produce an output, in which the rectangle lines occupy exactly the outmost pixels of the output image.

I have played around with many parameters here, removing the subtraction of 1 pixel, altering the parameters passed to gluOrtho2D etc. Still, I did not manage to produce the desired result. Somehow, there always appears to be some inaccuracy in the produced output image.

Any help is greatly appreciated!

Nevermind. The code is correct. The error was in my debugging code for storing the images to file.

Well…