IF in shaders

Programmers and people with programming knowledge sit here
User avatar
xizer
Posts: 87
Joined: Mon Oct 05, 2020 9:51 am

Re: IF in shaders

Post by xizer »

It was bad until the predicate register appeared. Now, in many cases, you can get performance gains if the blocks of computation are large enough.

Usually conditional jumps are replaced with lerp / step constructs. In your case, it will be something monstrous like:

Code: Select all

fixed k1 = step(_Y2, IN.worldPos.y);
fixed k2 = step(IN.worldPos.y, _Y1) * step(0.9, k1);
fixed k3 = step(0.9, k1 + k2);

fixed4 c = _Color2 * k1 + _Color1 * k2 + lerp(_Color1, _Color2, (IN.worldPos.y - _Y1) / (_Y2 - _Y1)) * k3;
wazzcob
Posts: 24
Joined: Fri Feb 05, 2021 5:11 am

Re: IF in shaders

Post by wazzcob »

What do you mean "bad"? Slow?
Firstly, for such a construction (assigning a value to a vector), there is no point in taking care of time at all, because it is negligible here.
Secondly, this statement (conditions in a shader are bad) made sense many years ago. In those days, at first all branches were executed, and only then the result was selected according to the condition. But this is no longer the case. So don't worry about it.
User avatar
xizer
Posts: 87
Joined: Mon Oct 05, 2020 9:51 am

Re: IF in shaders

Post by xizer »

wazzcob wrote: Tue Jun 15, 2021 5:09 am What do you mean "bad"? Slow?
Firstly, for such a construction (assigning a value to a vector), there is no point in taking care of time at all, because it is negligible here.
Secondly, this statement (conditions in a shader are bad) made sense many years ago. In those days, at first all branches were executed, and only then the result was selected according to the condition. But this is no longer the case. So don't worry about it.
Listen. Such ifs are bad not only in shaders, but in any code. not just because you think, but because they create the appearance of branching in code in which there is actually no branching. What you need is done through saturate or through clamp, it is easier to read and more difficult to make mistakes, and strumming in this case does not make sense.
Post Reply