d7samurai
d7samurai

Reputation: 3216

Dynamic branching in HLSL Shader Model 4.1

I can't seem to find a conclusive answer to this anywhere, so perhaps someone here can help. I am building a vertex shader (HLSL Shader Model 4.1) for Direct3D 11, and to reduce the number of draw calls I need to do, I want this shader to execute either of two branches, based on a flag.

Pseudo code:

if (flag)
    calculate corners of axis aligned quad
else
    calculate corners of rotated quad
end if

I keep reading that shaders execute both branches and select the appropriate result afterwards (which means it's costly and that using two different shaders (and more draw calls) might be better after all), but that this might be different in newer shader models (where only the relevant branch will be executed, meaning I get the flexibility practically for free). Which is the case for Shader Model 4.1?

When it comes to pixel shaders, apparently branches are executed per groups of pixels (which might affect what branches are executed), but how would this work in a vertex shader?

Upvotes: 0

Views: 1663

Answers (1)

Chuck Walbourn
Chuck Walbourn

Reputation: 41077

You provide the HLSL compiler a hint as noted on the MSDN page about whether you want to use dynamic branching or static branching:

[branch] if (flag)
    calculate corners of axis aligned quad
else
    calculate corners of rotated quad
end if

or

[flatten] if (flag)
    calculate corners of axis aligned quad
else
    calculate corners of rotated quad
end if

It's very difficult to completely generalize performance advice like this, and it really depends on the details of your shader, your target hardware, and how the code interacts with the shader. Generally speaking, static branching is preferred, but this is not as critical with newer SM 4.0+ models as it was back in the days of SM 2.0/3.0.

Upvotes: 1

Related Questions