开发者

OpenGL - Using texture's alpha channel AND a "global" opacity level

I'm trying to get a fairly simple effect; I'd like my sprites to be able to have their alpha channels used by GL (that is, translucent across parts of the image, but not all of it) as well as the entire sprite to have an "opacity" level that affects the entire sprite.

I've got the latter part, that was a simple enough matter of using GL_MODULATE and passing a color4d(opacity, opacity, opacity, opacity). Works like a dream.

But the problem is in the first part; partially translucent images. I'd thought that i could just fling out a glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); and enable blending, but unfortunately it doesn't do it. What it seems to do is "whiten" the color of the image开发者_如何学Go in question, rather than making it translucent. Any other sprites passing under it behave as if it were a solid block of color, and get directly cut off.

For reference, i've disabled lighting, z-buffer, color material, and alpha test. Did shade model flat, just in case. But other than that, i'm using default ortho settings. I'm using teximage2d for the texture in question, and i've been sure the formats and GL_RGBA are all set correctly.

How can i get GL to consider the texture's alpha channel during blending?


The simplest and fastest solution is to have a fragment shader.

uniform float alpha;
uniform sampler2D texture;
main(){
    gl_FragColor = texture2d(texture, gl_TexCoords);
    gl_FragColor.a *= alpha;
}


  • GL_MODULATE is the way to tell GL to use the texture alpha for the final alpha of the fragment (it's also the default).
  • Your blending is also correct as to how to use that generated alpha in the blending stage.

So the problem lies elsewhere... Your description sounds like you did not in fact disable Z-test, and you do not render your sprites back to front. Alpha blending in GL will only do what you want if you draw your sprites back to front. Otherwise, the sprites get blended in the wrong order, and this does not produce the correct output.

It would be easier to verify this with a picture of what you observe though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜