Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GLSL/HLSL - Multiple single line conditional statements as opposed to single block

Doing some research into antialiasing methods, I stumbled upon this piece of code (grabbed from Nvidia's FXAA shader):

if(!pairN) lumaN = lumaS;
if(!pairN) gradientN = gradientS;
if(!pairN) lengthSign *= -1.0;

Is there a good reason it's not written as the following instead?

if (!pairN) {
    lumaN = lumaS;
    gradientN = gradientS;
    lengthSign *= -1.0;
}

I assume it's an optimization of some sort? Just seems really counterintuitive...

like image 575
Fault Avatar asked Jan 07 '14 21:01

Fault


1 Answers

It is trivial for a GLSL compiler to convert this code:

if(!pairN) lumaN = lumaS;
if(!pairN) gradientN = gradientS;
if(!pairN) lengthSign *= -1.0;

into this branchless code:

lumaN = pair ? lumaN : lumaS;
gradientN = pair ? gradientN : gradientS;
lengthSign *= pair ? 1.0 : -1.0;

It is branchless in the sense it can be expressed as:

float a = float( pair );
float b = 1.0 - a;
lumaN = a * lumaN + b * lumaS;
gradientN = a * gradientN + b * gradientS;
lengthSign *= a * 1.0 + b * -1.0;

This is somewhat efficient optimization on mobile GPUs.

Automatically optimizing an entire if block is not so trivial.

like image 158
Sergey K. Avatar answered Oct 11 '22 17:10

Sergey K.