Search code examples
c++opengltextures

Texture buffer flip x and y axis


It seems that OpenGL reads texture buffers with the assumption that the buffer starts on the bottom left corner of the screen. This is fine, but the issue I have is with how it reads subsequent pixels. If I set up a texture buffer like so:

//texture_pixels[0][0][] is the bottom left corner
//texture_pixels[x][y][rgb]
unsigned char texture_pixels[1024][512][3];
for (int x = 0; x < 1024; x++) {
    for (int y = 0; y < 512; y++) {
        texture_pixels[x][y][0] = 0;
        texture_pixels[x][y][1] = 0;
        texture_pixels[x][y][2] = 0;

        if (x == 0 && y < 256) {
            texture_pixels[x][y][0] = 255;//set the first 256 values to red and everything else black
        }

    }
}

And then create a texture, framebuffer object, and glBlitFramebuffer this texture, we see the following:

enter image description here

If treating this as a Cartesian coordinate system with the bottom left corner being 0,0, the red line should be going up instead of right. Is there a way to change how OpenGL reads the texture buffer so that this is the case, or is the only option to flip the x and y axis (texture_pixels[y][x][rgb]) before passing the buffer?


Solution

  • The OpenGL texture image is stored row by row, but your image is stored column by column. You need to swap x and y. (512 rows with 1024 pixels and 3 color channels each)

    unsigned char texture_pixels[512][1024][3];
    for (int x = 0; x < 1024; x++) {
        for (int y = 0; y < 512; y++) {
            texture_pixels[y][x][0] = 0;
            texture_pixels[y][x][1] = 0;
            texture_pixels[y][x][2] = 0;
            if (x == 0 && y < 256) {
                texture_pixels[y][x][0] = 255;
            }
        }
    }