Constant float values in GLSL shaders - any reason to use uniforms?

前端 未结 2 1881
天涯浪人
天涯浪人 2021-02-13 00:43

I\'m looking at the source of an OpenGL application that uses shaders. One particular shader looks like this:

uniform float someConstantValue;
void main()
{
             


        
2条回答
  •  时光取名叫无心
    2021-02-13 01:22

    Huge reason:

    Error: Loop index cannot be compared with non-constant expression.

    If I use:

    uniform float myfloat;
    ...
    for (float i = 0.0; i < myfloat; i++)
    

    I get an error because myfloat isn't a constant expression.


    However this is perfectly valid:

    const float myfloat = 10.0;
    ...
    for (float i = 0.0; i < myfloat; i++)
    

    Why?

    When GLSL (and HLSL for that matter) are compiled to GPU assembly instructions, loops are unrolled in a very verbose (yet optimized using jumps, etc) way. Meaning the myfloat value is used during compile time to unroll the loop; if that value is a uniform (ie. can change each render call) then that loop cannot be unrolled until run time (and GPUs don't do that kind of JustInTime compilation, at least not in WebGL).

提交回复
热议问题