Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to specify image format as GL_RED instead of GL_ALPHA when loading single-byte alpha value texture?

I'm loading a texture that consists just of the alpha channel. When sending the data, I need to use GL_RED for both the image format and internal format when calling glTexImage2D, such as the following

glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, 512, 512, 0, GL_RED, GL_UNSIGNED_BYTE, temp_bitmap);

If I use GL_ALPHA for either/both of those instead, nothing will get rendered (changing the shader appropriately to use the alpha channel as well).

I was told that GL_RED is supposed to be used for alpha channels, but why is this the case, and why is there still GL_ALPHA?

like image 375
Jakub Arnold Avatar asked May 04 '16 12:05

Jakub Arnold


1 Answers

I'm loading a texture that consists just of the alpha channel.

No, you're not. You're loading a texture that consists of one color channel.

"Alpha" is merely an interpretation of your data. And you are free to interpret data however you wish. But to OpenGL, "one color channel" is spelled "red". Two color channels are spelled "red/green". And so forth.

If you want to make a one channel shader look like it is alpha-only to your shader, then you should use a texture swizzle:

GLint swizzleMask[] = {GL_ZERO, GL_ZERO, GL_ZERO, GL_RED};
glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask);

why is there still GL_ALPHA?

Are you asking why the enumerator exists? If so, then you may not understand the separation between the internal format of a texture (the third parameter) and the pixel transfer format (the third-to-last parameter). The former defines what data exists in the texture. GL_RED means that the texture will have one color channel with unsigned, normalized values of an indeterminate size (stop using unsized image formats).

The latter defines how data from your application is read into the image. It is legal (though nobody would call it fast) to only upload data to specific color channels of an image. For example, if you have a 4-channel image, you could upload data to just the green channels in it using the GL_GREEN transfer format.

like image 112
Nicol Bolas Avatar answered Oct 15 '22 06:10

Nicol Bolas