Fastest way to do min-max based on specific component of vectors in GLSL?

≡放荡痞女 提交于 2019-12-12 20:43:05

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/45597118/fastest-way-to-do-min-max-based-on-specific-component-of-vectors-in-glsl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!