Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unused Varying Variables in Fragment Shader GLSL - Can they hurt Perf

What happens to the unused varying variables in GLSL GPU's have inter shader buffers which would get populated with these values but since fragment shader is not using it , Wouldnt that be unnesscary computation which was being done in vertex shader (per vertex) & then dropped since it's not used in fragment shader.

  1. Can GLSL compilers optimize these kind of wrong practices ?
  2. If NOT , Would there be any performance improvement if these varying can completely be removed from vertex shader from below exapmle ?

Note : I havent written this shader - I have come across this shader while profiling & debugging an GL app , So was curious to know if these could be causing any perf. issues or compiler would have optimized it - If not used in FS.

Example:

Vertex Shader

attribute vec3 Normal;
attribute vec4 Vertex;
uniform mat3 NormalMatrix;
uniform mat4 ModelViewProjectionMatrix;
uniform mat4 ModelViewMatrix;
precision mediump float;
**varying vec3 N;**
**varying vec3 v;**
varying vec2 texCor;
void main(void)
{
    v = vec3(ModelViewMatrix * Vertex);
    N = normalize(NormalMatrix * Normal);
    gl_Position = ModelViewProjectionMatrix * Vertex;
    texCor = MultiTexCoord0.xy;
}

Fragment Shader

precision mediump float;
uniform sampler2D data;
**varying vec3 N;**
**varying vec3 v;**
varying vec2 texCor;
void main (void)
{
    vec2 TexCoord = texCor;
    vec4 RGB      = texture2D( data, TexCoord );
    gl_FragColor = vec4(0.0, 0.0, 0.0 , RGB.r);
}
like image 850
Go kart Avatar asked Oct 27 '25 10:10

Go kart


1 Answers

Can GLSL compilers optimize these kind of wrong practices ?

In principle yes, although there is no guarantee they do as it requires state which is only available a link-time, not at shader compile time. It will be easier in Vulkan when all shaders in the pipeline are compiled at the same time.

If NOT , Would there be any performance improvement if these varying can completely be removed from vertex shader

Quite probably yes, but YMMV. Don't tell the GPU to do something that you don't actually need it to do, that's just common sense ...

The main optimization here which is critical is actually data side. Most applications will interleave vertex data for all attributes, so if you have unused data elements in your interleaved buffers then that will get pulled into the GPU, wasting bandwidth, cache space, burning power, etc. It is highly unlikely that the graphics drivers can remove this inefficiency because the application can call glMapBuffer at any time.

In summary - optimize your shaders and your data structures to remove stuff you don't need. Also upload things at the correct precision (don't upload fp32 data if the shader only needs fp16, etc).

like image 185
solidpixel Avatar answered Oct 30 '25 13:10

solidpixel