Tuesday, February 24, 2009

Shader tip

Tired of recompiling shaders all the time to try different combinations or code branches? Use this little hack in pseudo-code for selecting values: (I guess this was more useful on pre-shader model 3.0 hardware)

float4 g_vControl = float4( 1, 0, 0, 0 ); // Default to Branch1

float4 MainPS() : COLOR0
{
  float fValue0 = ResultFromBranch1();
  float fValue1 = ResultFromBranch2();
  float fValue2 = ResultFromBranch3();
  float fValue3 = ResultFromBranch4();
  float4 vValues = float4( fValue0, fValue1, fValue2, fValue3 );
  float fResult = dot( g_vControl, vValues );

// Do more math with the result...
}


Then on your main C#/C++ code, you can just set g_vControl to ( 1, 0, 0, 0) for Branch1, ( 0, 1, 0, 0 ) for Branch2, etc.

Of course, on release code you should remove this, or set g_vControl to be static bool so the compiler will optimize out the remaining branches. But for developing it's quite useful.

Also, you could blend the values: g_vControl = ( 0.5, 0, 0.5, 0 ) for example to blend Branch1() and Branch3().

No comments: