Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opengl Shader, what's the gl_FragColor's alpha components?

I think it'll be a little bit simple answer.
But I can't find the answer with googling.
It's OpenGLES shader thing. I am using cocos2d-x engine.

This is my fragment shader code.

precision lowp float;
varying vec2 v_texCoord;
uniform sampler2D u_texture;
uniform vec4 u_lightPosition;

void main()
{
    vec4 col=texture2D(u_texture,v_texCoord);

    mediump float lightDistance = distance(gl_FragCoord, u_lightPosition);
    mediump float alpha = 100.0/lightDistance;
    alpha = min(alpha, 1.0);
    alpha = max(alpha, 0.0);
    col.w = alpha;
    //col.a = alpha;


    gl_FragColor=col;

}

I just want to give opacity in some circle area. So I change the color's w value because I thought it's the alpha value of the texel. But the result was very odd. I am afraid it's not alpha value.

Even if I set the value to 1.0 for testing, whole sprite change to be bright and white.


Its vertex shader is very normal, there is nothing special to attached.


Any idea please.



Updated: For reference, I attach some result image.

case 1)

col.w = alpha;

enter image description here

case 2)

col.w = 1.0

enter image description here


and normal texture before applying shader.)

enter image description here

like image 831
Jinbom Heo Avatar asked Jul 01 '14 02:07

Jinbom Heo


1 Answers

The GL ES 2.0 reference card defines:

Variable
mediump vec4 gl_FragColor;

Description
fragment color

Units or coordinate system
RGBA color

It further states:

Vector Components
In addition to array numeric subscript syntax, names of vector components are denoted by a single letter. Components can be swizzled and replicated, e.g.: pos.xx, pos.zy

{x, y, z, w} Use when accessing vectors that represent points or normals

{r, g, b, a} Use when accessing vectors that represent colors

{s, t, p, q} Use when accessing vectors that represent texture coordinates

So, sure, using .a would be more idiomatic but it's explicitly the case that what you store to .w is the output alpha for gl_FragColor.

To answer the question you've set as a title rather than the question in the body, the value returned by texture2D will be whatever is correct for that texture. Either an actual stored value if the texture is GL_RGBA or GL_LUMINANCE_ALPHA or else 1.0.

So you're outputting alpha correctly.

If your output alpha isn't having the mixing effect that you expect then you must have glBlendFunc set to something unexpected, possibly involving GL_CONSTANT_COLOR.

like image 88
Tommy Avatar answered Sep 20 '22 04:09

Tommy