Search code examples
arraysopengltexture-mapping

Texturing GL_QUADS with (3x3) color array ignores the 4th color in each row


I'm trying to generate a 3x3 texture from an byte array.

My problem is i need to give one extra color in the final of each row to get what I want, and i want to know why.

Is there a problem in the byte count that I'm ignoring or something like that?

Here's my array:

GLubyte data[33] = { 
                    //bottom row
                    0, 0, 150,
                    150, 10, 220,
                    150, 150, 56,

                    0, 0, 0,        //must be here to get what I want but don't render

                    //middle row
                    150, 150, 150,
                    150, 0, 21,
                    0, 255, 0,

                    0, 0, 0,        //must be here to get what I want but don't render

                    //top row
                    250, 150, 0,
                    250, 0, 150,
                    0, 150, 0 };

And my texture generation:

GLuint texture;

glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);

//I thing the problem is right here
glTexImage2D(GL_TEXTURE_2D, 0, 3, 3, 3, 0, GL_RGB, GL_UNSIGNED_BYTE, data);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

return texture;

And I'm applying the texture like this:

GLuint texture = genTexture(0);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture);

glBegin(GL_QUADS);
    glTexCoord2f(1.0f, 0.0f); glVertex2f(0.5f, -0.5f);
    glTexCoord2f(1.0f, 1.0f); glVertex2f(0.5f, 0.5f);
    glTexCoord2f(0.0f, 1.0f); glVertex2f(-0.5f, 0.5f);
    glTexCoord2f(0.0f, 0.0f); glVertex2f(-0.5f, -0.5f);
glEnd();

And the result is ignoring these 24 bits for each row:

Result


Solution

  • You need to set the GL_UNPACK_ALIGNMENT pixel storage parameter to make this work:

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    

    This controls the alignment of rows in the data passed to glTexImage2D(). The default values is 4. In your case, since each row consists of 9 bytes of data (3 colors with 3 bytes each), an alignment value of 4 would round up the row size to 12. This means that 12 bytes will be read per row, and explains why it works when you add an extra 3 bytes at the end of each row.

    With the alignment set to 1, you will not need extra padding.