Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In OpenGL Fragment Shader, what's the difference between gl_FragColor.a = 0 and discard?

As titled, gl_FragColor.a = 0 is supposed to make thing transparent. So what's the diff from discard?

For the following code

varying vec3 f_color; 
uniform sampler2D mytexture; 
varying vec2 texCoords;
float cutoff = 0.5;

void main(void) { 
  gl_FragColor = texture2D(mytexture,texCoords); 
  if( gl_FragColor.a < cutoff) discard;
}

discard will work but if I replace discard with gl_FragColor.a=0; , it has no effect. Why?

like image 818
new2cpp Avatar asked Mar 20 '23 15:03

new2cpp


1 Answers

First, alpha to zero will only hide the pixel if blending is enabled. Discard will prevent the fragment from being written entirely. For example, if you write a fragment of alpha zero it will still update the depth buffer and stencil buffer even if you haven't altered the pixel's color. With discard it will not affect either of these.

For a full example let's say I render a tree branch with one quad and use alpha testing as you're doing. By discarding the fragments that are transparent I can later render something behind that branch because the depth buffer won't drop those fragments in between. If you just set alpha to zero, the depth buffer would hold the full quad and anything rendered afterwards would be occluded by the entire quad, not the leaves that passed the discard test.

like image 102
voodoogiant Avatar answered Apr 25 '23 05:04

voodoogiant