I need to call this kind of function many many times in my GLSL code.
vec2 minx(vec2 a, vec2 b) {
if (a.x < b.x) return a;
else return b;
}
I'm concerned of the excessive branching. Is there a way to do this avoiding if-else constructs?
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:
vec2 minx(vec2 a, vec2 b)
{
return mix( a, b, step( b.x, a.x ) );
}
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.