I have GLSL mobile shader (ES 2.0) and inside I have this:
float b = texture2D(t, texCoord).r;
float s = 0.0;
if (b > 240.0) s = b - 2322.2;
else if (b > 90.0) s = b - 74.0;
else if (b < 10.0) s = b / 10.0;
else s = b - 10.0;
Is it going to be slow? I know, that branching in shader should be avoided. Is there any way, how to rewrite this to remove ifs?
I suggest to use the GLSL functions mix and step.
mix interpolates between 2 values according to a floating point interpolation value a in the range [0.0, 1.0]. If the a is equal 0.0 then the 1st value is returned and if the a is equal 1.0 then the 2nd value is returned.
step tests whether a value is less than an edge value. If it is less then 0.0 is returned, else 1.0 is returned.
If you combine the 2 functions your code will look like this:
float b = texture2D(t, texCoord).r;
float s = mix(
mix( b/10.0, b-10.0, step(10.0, b) ),
mix( b-74.0, b-2322.2, step(240.0, b) ),
step(90.0, b) );
Note, the result of step is either exactly 0.0 or exactly 1.0, this causes that mix either returns the 1st value or returns the 2nd value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With