glTexImage2d 2 pxl texture problem

I can’t figure out how this is producing a magenta pixel (255,128,255 sampled from a screenshot) in corner of this 2 pixel texture.

glGenTextures(1, &arid[10]);

glBindTexture(GL_TEXTURE_2D, arid[10]);
unsigned char b2[2][2][3];

b2[0][0][0] = 255;
b2[0][0][1] = 255;
b2[0][0][2] = 255;
		
b2[0][1][0] = 255;
b2[0][1][1] = 255;
b2[0][1][2] = 255;
		
b2[1][0][0] = 255;
b2[1][0][1] = 255;
b2[1][0][2] = 255;
		
b2[1][1][0] = 255;
b2[1][1][1] = 255;
b2[1][1][2] = 255;
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, GL_RGB, GL_UNSIGNED_BYTE, b2);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

I’m looking at the values set in the debugger and b2[0][0][0] to b[1][1][2] are set to 255. But I can see that the values 255,128,255 are stored in b[1][1][2] and what would be b[1][2][0] and b[1][2][1] if they part of the array. Have I done anything wrong here? I’m stumped.

b2[1][1][2] is 255 because you initialized it to that value. I don’t know why you would want to access b2[1][2][0] and b2[1][2][1] since you did not initialize them.
But my guess is that you’re just accessing the next memory block containing other variables or an array that has been assigned to your program. The MMU does not generate a segfault since no boundary checks are performed when accessing memory.

N.

yeah that wasn’t clear. I don’t want to access the junk data in b2[1][2][0] and b2[1][2][0] but glTexImage is going into those because it skips two bytes in my array.

So pixels 3 and 4 end up with incorrect colors. I commented where it happens:

glGenTextures(1, &arid[10]);

glBindTexture(GL_TEXTURE_2D, arid[10]);
unsigned char b2[2][2][3];
//pixel 1
b2[0][0][0] = 255;
b2[0][0][1] = 255;
b2[0][0][2] = 255;
//pixel 2
b2[0][1][0] = 255;
b2[0][1][1] = 255;
b2[0][1][2] = 255;
//pixel 3
b2[1][0][0] = 255; //it skips these two bytes
b2[1][0][1] = 255; //it skips these two bytes
b2[1][0][2] = 255; //now pixel 3 starts here and takes from pixel 4
//pixel 4
b2[1][1][0] = 255;
b2[1][1][1] = 255;
b2[1][1][2] = 255;

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, GL_RGB, GL_UNSIGNED_BYTE, b2);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

Clicky. Check out GL_UNPACK_ALIGNMENT, what it’s default value is, and how that will affect your image.

That was it, I’m all set after throwing down glPixelStorei(GL_UNPACK_ALIGNMENT, 1). Odd that anything higher than 4pxl squared comes out pixel-perfect (i compared in ms paint) without that call. Thanks for the link!

That’s because textures, which are powers of two only (not counting extensions), are always aligned properly as long as they are 4 or more pixels wide.