openglglsllwjgl

How can I use something like "discard;" to increase performance?


I would like to use shaders to increase my in-game performance.

enter image description here

As you can see, I am cutting out the far-away pixels from rendering, using the discard function.

However, for some reason this is not increasing FPS. I have got the exact same 5 FPS that I have got without any shaders at all! The low FPS is because I chose to render an absolute ton of trees, but since they are not seen... Then why are they causing lag!?

My fragment shader code:

varying vec4 position_in_view_space;
uniform sampler2D color_texture;

void main()
{
   float dist = distance(position_in_view_space, 
      vec4(0.0, 0.0, 0.0, 1.0));
   if (dist < 1000.0)
   {
       gl_FragColor = gl_Color;
         // color near origin
   }
   else
   {
      //kill;
      discard;
      //gl_FragColor = vec4(0.3, 0.3, 0.3, 1.0); 
         // color far from origin
   }
}

My vertex shader code:

varying vec4 position_in_view_space;

void main()
{
   gl_TexCoord[0] = gl_MultiTexCoord0;
   gl_FrontColor = gl_Color;
   position_in_view_space = gl_ModelViewMatrix * gl_Vertex;
      // transformation of gl_Vertex from object coordinates 
      // to view coordinates;

   gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
   
}

(I have got very slightly modified fragment shader for the terrain texturing and a lower distance for the trees (Ship in that screenshot is too far from trees), however it is basically the same idea.)

So, could someone please tell me why discard is not improving performance? If it can't, is there another way to make unwanted vertices not render (or render less vertices further away) to increase performance?


Solution

  • Using discard will actually prevent the GPU from using the depth buffer before invoking the fragment shader.

    It's much simpler to adjust the far plane of the projection matrix so unwanted vertices are outside the render box.

    Also consider not calling the glDraw for distant trees in the first place.

    You can for example group the trees per island and then per island check if it is close enough for the trees to render and just not call glDraw* when it's not.