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

StackOverflow https://stackoverflow.com/questions/23600116

  •  20-07-2023
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top