How to render a texture with alpha?
How to render a texture with alpha?
I have a texture, and need to render it w开发者_如何学编程ith different alpha values at different locations. Any way to do so? (My texture is GL_RGBA)
If not possible to change alpha value on the fly, I have to create different textures for different alpha levels?
First, make sure that your texture has an alpha channel. You mention you are loading an RGBA format, but it's always good to check the original file in an image editing program. Then make sure your texture is ready for rendering in openGL. A common mistake is to forget to set up the texture's filtering mode through glTexParameter*
. It starts on a setting requiring mipmaps, so I find that it's easiest to start with:
glTexParameteri(GL_TEXTURE_2D, GL_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_MAG_FILTER, GL_LINEAR);
Secondly, you will need to set up openGL to be ready for blending. This involves a glEnable
call with GL_BLEND
and a glBlendFunc
call. Most of the time, you will want the function call to be glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
, as most other combinations of tokens will give you effects you are not after (see the glBlendFunc
spec page for more info).
Finally, ensure you are sampling your texture at different points. If you are using immediate mode (you are using glVertex*
to draw your scene), you will need to either use glTexGen*
or manually specify texture points using glTexCoord*
before calls to glVertex*
. If using array data to draw your scene, make sure you have enabled the texture pointer using glEnableClientState(GL_TEXTURE_COORD_ARRAY)
and glTexCoordPointer
.
Your texture is GL_RGBA so it has a different alpha value for each texel.
If you want to change the alpha value used for render, I can think of the following methods:
- Change the texture alpha values (not sure if you say that you don't want to do that).
- Use
glColor4f
to change the alpha value of the vertices. It will multiply the texture values. You may need to useglEnable(GL_COLOR_MATERIAL)
and/orglColorMaterial()
. - Use a vertex shader to change the vertex alpha values. It will multiply the texture values.
- Use a fragment shader to change the sampled texture values on the fly.
- Use two texture stages and multiply them. The second one will have the modified alpha values (see
glActiveTexture()
and friends). - Use a fragment shader and two (or more) texture stages. This is the coolest!
精彩评论