user2654137
user2654137

Reputation: 17

Missing green color component using glTexImage2D function, why?

I'm writing my 3D engine, without OpenGL or DirectX. Every 3D calculations are my own code. When a whole frame is calculated (a 2D color array), I have to draw it to a window, and to do this I use GLUT and OpenGL. But, I don't use OpenGL's 3D features.

So I have a 2D color array (actually a 1D unsigned char array, which is used as a 2D array), and I have to draw it with OpenGL/GLUT, in an efficient way.

There are two important things:

I wrote 3 possible solutions:

Some hours ago, I used float array, 3 components, and 0...1 values. Green was missing, so I decided to use unsigned char array, because it's smaller. Now, I use 4 components, but the 4th is always unused. Values are 0...255. Green is still missing. My texturing code:

GLuint TexID;
glGenTextures(1, &TexID);
glPixelStorei(GL_UNPACK_ALIGNMENT, TexID); // I tried PACK/UNPACK and ALIGNMENT/ROW_LENGTH, green is still missing
glTexImage2D(GL_TEXTURE_2D, 0, RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, a->output);
glTexParametri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParametri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParametri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParametri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glBindTexture(GL_TEXTURE_2D, TexID);
glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
    // glTexCoord2f ... glVertex2f ... four times
glEnd();
glDisable(GL_TEXTURE_2D);
glDeleteTextures(1, &TexID);

If I use glDrawPixels, it is working good, R, G and B components are on the window. But when I use the code above with glTexImage2D, green component is missing. I tried a lots of things, but nothing solved this green-issue.

I draw coloured cubes with my 3D engine, and which contains green component (for example orange, white or green), it has a different color, without the green component. Orange is red-like, green is black, etc. 3D objects which doesn't contain green component, are good, for example red cubes are red, blue cubes are blue.

I think, glTexImage2D's parameters are wrong, and I have to change them.

Upvotes: 0

Views: 283

Answers (1)

Andon M. Coleman
Andon M. Coleman

Reputation: 43319

glPixelStorei(GL_UNPACK_ALIGNMENT, TexID); is very wrong.

Accepted values for that function are:

  • 1, 2, 4 and 8

And they represent the row-alignment (in bytes) for the image data you upload. For an 8-bit per-component RGBA image, you generally want either 1 or 4 (default).

You are extremely lucky here if this actually works. Miraculously TexID must be 1 (probably because you only have 1 texture loaded). As soon as you have 3 textures loaded and you wind up with a value for TexID of 3 you're going to generate GL_INVALID_VALUE and your program's not going to work at all.

Upvotes: 1

Related Questions