Sign in to follow this  
ardmax1

GLSL - pixel color based on alpha

Recommended Posts

ardmax1    127
Hi,
is it possible to write GLSL shader such that it will change each texture pixel color based on its alpha value ?
Something like:
[source lang="cpp"]
vec4 pixel = texture2D( texture, pos );
if( pixel.a > 0.5f ){
pixel = vec4( 0.0, 1.0, 0.0, 1.0 );
}else{
pixel = vec4( 1.0, 0.0, 0.0, 1.0 );
}[/source]
If it is, could you guys give me tips on how to make it ?

Share this post


Link to post
Share on other sites
Relfos    349
Yes, it is possible, and you just gave the answer yourself [img]http://public.gamedev.net//public/style_emoticons/default/tongue.png[/img]

Share this post


Link to post
Share on other sites
ardmax1    127
If it should work, then i have error somewhere else.

This produces just red
fragment:
[sourcelang="cpp"]varying vec4 pos;
uniform sampler2D texture;

void main(){
vec4 pixel = texture2D(texture, vec2(pos));
if (pixel.a > 0.5){
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}else{
gl_FragColor = vec4(0.0, 0.0, 1.0, 0.3);
}
}
[/source]
vertex:
[source lang="cpp"]varying vec4 pos;

void main(){
pos = gl_MultiTexCoord0;
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}[/source]

Share this post


Link to post
Share on other sites
Cornstalks    7030
Have you enabled alpha blending? How have you created the texture? The shaders look ok, so I'm guessing the problem is outside of the shaders. Edited by Cornstalks

Share this post


Link to post
Share on other sites
clb    2147
Sampling the alpha channel of a texture does not require alpha blending to the framebuffer to be enabled. Make sure that your texture actually does have an alpha channel, and it's not all 1.f in each pixel.

Try debugging visually the contents of the alpha channel with the following fragment shader:

[code]

varying vec4 pos;
uniform sampler2D texture;

void main(){
vec4 pixel = texture2D(texture, vec2(pos));
gl_FragColor = vec4(pixel.aaa, 1.0);
}
[/code]

this should render the alpha channel out in grayscale, so you can confirm that it is not all white.

Share this post


Link to post
Share on other sites
ardmax1    127
ok I found out was the problem.
First it was caused by clearing texture, which is used to apply shaders on whole screen rather that on parts that are drawn (This is I think SFML problem).
Second, I had to normalize position, so it looks like this now
[source]pixel = texture2D(texture, pos.xy / texResolution);[/source]
but why this makes texture flip vertically?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this