Shader Flow control problem

Started by
4 comments, last by JB3DG 10 years, 8 months ago

Hi guys

I am having some trouble with if statements in my pixel shader.


Texture2D shaderTextures[3];
SamplerState SampleType;

struct VS_Output
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
};

cbuffer Lights
{
    float g;
    float c;
    float t;
}

float4 Blender(VS_Output input):SV_TARGET
{
	float4 color1;
	float4 color2;
	float4 color3;
	float4 color4;
	
	if( g != 0 && c == 0 && t == 0)
	{
		color2 = shaderTextures[0].Sample(SampleType, input.tex);
		color1 = color2 * g;
	}
	
	if( g == 0 && c != 0 && t == 0)
	{
		color3 = shaderTextures[1].Sample(SampleType, input.tex);
		color1 = color3 * c;
	}

	if( g == 0 && c == 0 && t != 0)
	{
		color4 = shaderTexture[2].Sample(SampleType, input.tex);
		color1 = color4 * t;
	}
	
	return color1;
}

If i remove the if blocks leaving any one of the statements inside,

D3DX11CompileFromFile is successful. But the moment i include any if control, it fails. Where am i going wrong?

Thanks

JB

Advertisement

Use SampleLevel instead of Sample in your branches.Otherwise the compiler will move them out of the loop before processing - if you have warnings on or anything of that sort, the compile will fail.

Thanks a bunch. All working now.

I think color1 is considered uninitialized because all the the assignments of color1 are inside ifs that could be false in some case.

float4 color1 = float4(0,0,0,0);

Use SampleLevel if you want to set your mip level manually or sample in a shader that's not the pixel shader.

use that code if it fits your needs (I'm not pretty shure what you're trying to achieve)

index = g*1 + c*2 + t*3 -1;
color = shaderTextures[index].Sample(SampleType, input.tex);

color *= g + c + t;

always try to avoid branching

Got sorted. I was making a shader that blended textures by RGB values (the lower the RGB the more transparent it is) and at least 3+ textures were involved. Was trying to keep certain blends from occuring if the g/c/t values in the constant buffer were zero to improve efficiency.

This topic is closed to new replies.

Advertisement