Issue with blending

I have 2 objects one behind the other. I have enabled alpha blending and using uniform variable to pass alpha value in fragment shader. My Frag shader:


#version 130
uniform float a;
out vec4 color;
void main (void)  
{  
    if(a==1.0)
    color=vec4(0.3, 0.7, 0.5,a);
else 
          color=vec4(1.0,1.0,1.0,a);    
}


Before 1st draw call I set a=1 and before 2nd draw call i set a=0.5. Now when I see from front I can see 1st object through second one. But when I change the camera and go back in front of 1st object, I can see second one through first one even if i have a=1 for 1st object. My blending equation is:

glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

I think what you’re missing is that you’re not drawing the geometry furthest-to-nearest, which conventional alpha blending requires.

For instance, when your eyepoint is closer to the opaque object, draw it last.

I guess I am missing something here. I am drawing furthest to nearest, when I rotate my camera and go in front of furthest object so that nearest object would be on the back I can see nearest object through farthest. What should be the output in this case?

It’s not the nearest anymore. It’s the furthest, so it now needs drawn first.

…I can see nearest object through farthest. What should be the output in this case?

If you do have alpha blending enabled properly and set as you describe above, if you render the alpha=0.5 object last (which you would if it was closest), then you’ll get a 50%/50% blend. If you render the alpha=1.0 object last (which you would if it was closest), then you’ll get 100% of its color and 0% of the other.

Thank you for your reply. Issue solved.

Very basic doubt, what should be the state of depth test when blending?

It depends. If you have potentially other objects (possibly opaque) rasterized to your depth buffer already, and you want these translucent objects to be occluded by those opaque objects, then you want depth test. However, in the case where you know nothing can occlude your translucent object, or your are handling occlusion a different way, then you don’t need depth test nor a depth buffer.