adding attenuation to hlsl point light

Started by
14 comments, last by cozzie 11 years, 2 months ago

Hi,

I've been playing around with point lights in my d3d engine and got one working using my shader.

Although on the 'attenuation' side I have a challenge:

- I can now only control attenuation by changing "lightRange" from a range of 0.0 to 1.0 (0.1 being a 'big' range, 0.9 being a 'small' range), and with this, the range is far to high, meaning that meshes far away are also lit (a little).

What I want to achieve is that I can use "lightRange" to pass in a value/range in 'units' in my scene, up to which the light falls of and at 'lightRange' also ends. For now linear falloff is fine (or another falloff calculation which is relatively easiest).

Can someone help me in the right direction?


/***********************************************************/
/**  VARS NOT CONTROLLED BY ENGINE YET             *********/
/***********************************************************/

float4 diffuseColor = { 0.8f, 0.8f, 0.8f, 0.0f };    // NEW
float3 lightPosition = { 0.0f, 2.0f, 0.0f };   // NEW
float lightRange = 0.9f;    // NEW

// modelfile, just for effectedit
string XFile = "paving.x";   // model

/***********************************************************/
/**       VARS CONTROLLED BY ENGINE                *********/
/***********************************************************/

float4x4    World         : WORLD;
float4x4    WorldInvTransp: WORLDINVTRANSP;
float4x4    ViewProj      : VIEWPROJECTION;

float4      AmbientColor;
float       AmbientIntensity;

float4      MatAmb : MATERIALAMBIENT; 
float4      MatDiff: MATERIALDIFFUSE; 
            
texture     Tex0 < string name = "hungary009.jpg"; >;

/***********************************************************/
/**          SAMPLER STATES FOR TEXTURING          *********/
/***********************************************************/

sampler2D textureSampler = sampler_state
{
    Texture         = (Tex0);
                                 
    MinFilter       = ANISOTROPIC;
    MagFilter       = LINEAR;
    MipFilter       = LINEAR;    
    MaxAnisotropy   = 4;            
};

struct VS_INPUT
{
    float4    Pos      : POSITION0;
    float4    Normal   : NORMAL0;
    float2    TexCoord : TEXCOORD0;
};

struct VS_OUTPUT
{
    float4 Pos     : POSITION;
    float3 Normal  : TEXCOORD1;
    float2 TexCoord: TEXCOORD2;
    float3 LightPos: TEXCOORD3; 
    float3 Att     : TEXCOORD4;
};

/***********************************************************/
/**          THE VERTEXSHADER        PROGRAM       *********/
/***********************************************************/

VS_OUTPUT VS_function(VS_INPUT input)
{
    VS_OUTPUT Out = (VS_OUTPUT)0;

    float4 worldPosition = mul(input.Pos, World);
    Out.Pos = mul(worldPosition, ViewProj);

    float4 normal = mul(input.Normal, WorldInvTransp);
    Out.Normal = normal;
    Out.TexCoord = input.TexCoord;

    Out.LightPos = lightPosition.xyz - worldPosition;   
    Out.LightPos = normalize(Out.LightPos);           

    Out.Att = Out.LightPos * lightRange;

    return Out;
}

/***********************************************************/
/**          THE PIXELSHADER        PROGRAM        *********/
/***********************************************************/

float4 PS_function(VS_OUTPUT input): COLOR0
{
    float4 textureColor = tex2D(textureSampler, input.TexCoord);

    float lightIntensity = saturate(dot(input.Normal, input.LightPos));    
    float4 color = diffuseColor * lightIntensity;          

    float4 amb = AmbientColor * AmbientIntensity * MatAmb;
    float4 attenuation = mul(input.Att, input.Att);

    return saturate((color + amb) * textureColor) * MatDiff * (1-attenuation); 
}

/***********************************************************/
/**          OPAUQE SHADER, REGULAR MESHES         *********/
/***********************************************************/

technique OpaqueShader
{
    pass P0              
    {
        AlphaBlendEnable    = FALSE;
                              
        VertexShader = compile vs_2_0 VS_function();
        PixelShader = compile ps_2_0 PS_function();
    }  
}

/***********************************************************/
/**   BLENDING SHADER, MESHES WITH BLENDED TEXTURES  *******/
/***********************************************************/

technique BlendingShader
{
    pass P0              
    {
        AlphaBlendEnable    = TRUE;
        SrcBlend            = SRCALPHA;
        DestBlend           = INVSRCALPHA;
        AlphaOp[0]          = SelectArg1;
        AlphaArg1[0]        = Texture;
                               
        VertexShader = compile vs_2_0 VS_function();
        PixelShader = compile ps_2_0 PS_function();
    }  
}

Crealysm game & engine development: http://www.crealysm.com

Looking for a passionate, disciplined and structured producer? PM me

Advertisement

no one? maybe some pointers to a good tutorial/ article?

Crealysm game & engine development: http://www.crealysm.com

Looking for a passionate, disciplined and structured producer? PM me

What I want to achieve is that I can use "lightRange" to pass in a value/range in 'units' in my scene, up to which the light falls of and at 'lightRange' also ends. For now linear falloff is fine (or another falloff calculation which is relatively easiest).

Maybe no one answered because it's still unclear what you want. Do you to pass in just a single value that indicates the number of world units over which the light goes from full to zero (with linear falloff)?
Hi phil. Thanks

That's the aimed result i want to achieve, yes.
With hopefully a little understanding how it's been calculated in the shader/math

Crealysm game & engine development: http://www.crealysm.com

Looking for a passionate, disciplined and structured producer? PM me

Well it's basically just the equation of a line, clamped to (0, 1).

Conceptually, I would think of it like this:

- If d is the distance between the light and the current point being shaded,
- And FallOffDistance is a shader constant for the fall off distance of the light in world units,
- Then (d / FallOffDistance) gives you a number that goes from (0 -> 1) as distance increases.
- That's the opposite of what you want, so invert it by subtracting it from 1.

float lightIntensity = 1f - (d / FallOffDistance);

Of course, you need to account for d being larger than FallOffDistance, so clamp the original term to (0, 1):

float lightIntensity = 1f - saturate(d / FallOffDistance);

If you want the light to remain full power for a certain distance before beginning to fall off, you can adjust distance by this value:

float lightIntensity = 1f - saturate((d - FullPowerDistance) / FallOffDistance);

And if you want a more realistic falloff (like 1 / R^2), since the lightIntensity is between (0, 1), it is easy to apply a power curve:

lightIntensity = pow(lightIntensity, 2);


Hi Phil,

Thanks for your help. I've been playing around but unfortunately didn't get it to work yet.

Here's what I have now, based on your help/ explanation.

Resulting in a "error X4502: invalid reference to input semantic 'POSITION0'.

I found out that it's caused by the line where I calculatie 'distt' (distance from point light to shaded point in worldspace)


/***********************************************************/
/**  VARS NOT CONTROLLED BY ENGINE YET             *********/
/***********************************************************/

float4 	diffuseColor 	= { 0.8f, 0.8f, 0.8f, 0.0f };    	// NEW
//float3 	lightPosition 	= { 0.0f, 2.0f, 0.0f };   		// NEW
float4 	lightPosition 	= { 0.0f, 2.0f, 0.0f, 1.0f };   	// NEW
float 	lightRange 		= 5.0f;    					// NEW

// modelfile, just for effectedit
string XFile = "paving.x";   // model

/***********************************************************/
/**       VARS CONTROLLED BY ENGINE                *********/
/***********************************************************/

float4x4		World         : WORLD;
float4x4    	WorldInvTransp: WORLDINVTRANSP;
shared float4x4 	ViewProj      : VIEWPROJECTION;

float4      	AmbientColor;
float       	AmbientIntensity;

float4      	MatAmb : MATERIALAMBIENT; 
float4      	MatDiff: MATERIALDIFFUSE; 
            
texture     	Tex0 < string name = "hungary009.jpg"; >;

/***********************************************************/
/**          SAMPLER STATES FOR TEXTURING          *********/
/***********************************************************/

sampler2D textureSampler = sampler_state
{
	Texture         	= (Tex0);
                                 
    	MinFilter       	= ANISOTROPIC;
   	MagFilter       	= LINEAR;
    	MipFilter       	= LINEAR;    
    	MaxAnisotropy	= 4;            
};

struct VS_INPUT
{
	float4    Pos     : POSITION0;
    	float4    Normal  : NORMAL0;
    	float2    TexCoord: TEXCOORD0;
};

struct VS_OUTPUT
{
	float4 Pos     	: POSITION;
    	float3 Normal  	: TEXCOORD1;
    	float2 TexCoord	: TEXCOORD2;
//    float3 LightPos	: TEXCOORD3; 
    	float4 LightPos	: TEXCOORD3; 
    	float3 Att     	: TEXCOORD4;
};

/***********************************************************/
/**          THE VERTEXSHADER        PROGRAM       *********/
/***********************************************************/

VS_OUTPUT VS_function(VS_INPUT input)
{
	VS_OUTPUT Out = (VS_OUTPUT)0;

	float4 worldPosition = mul(input.Pos, World);
    	Out.Pos = mul(worldPosition, ViewProj);

    	float4 normal = mul(input.Normal, WorldInvTransp);
    	Out.Normal = normal;
    	Out.TexCoord = input.TexCoord;

//    Out.LightPos = lightPosition.xyz - worldPosition;   
    	Out.LightPos = lightPosition - worldPosition;   
    	Out.LightPos = normalize(Out.LightPos);           

    	Out.Att = Out.LightPos * lightRange;

    return Out;
}

/***********************************************************/
/**          THE PIXELSHADER        PROGRAM        *********/
/***********************************************************/

float4 PS_function(VS_OUTPUT input): COLOR0
{
	float4 textureColor = tex2D(textureSampler, input.TexCoord);

//   	float lightIntensity = saturate(dot(input.Normal, input.LightPos));    
 
   	float distt = distance(input.LightPos, input.Pos);
    	float lightIntensity = 1 - saturate(distt / lightRange);    
    	
	float4 color = diffuseColor * lightIntensity;          
    	float4 amb = AmbientColor * AmbientIntensity * MatAmb;
    	float4 attenuation = mul(input.Att, input.Att);

    	return saturate((color + amb) * textureColor) * MatDiff * (1-attenuation); 
}

/***********************************************************/
/**          OPAUQE SHADER, REGULAR MESHES         *********/
/***********************************************************/

technique OpaqueShader
{
    pass P0              
    {
        AlphaBlendEnable    = FALSE;
                              
        VertexShader = compile vs_2_0 VS_function();
        PixelShader = compile ps_2_0 PS_function();
    }  
}

/***********************************************************/
/**   BLENDING SHADER, MESHES WITH BLENDED TEXTURES  *******/
/***********************************************************/

technique BlendingShader
{
    pass P0              
    {
        AlphaBlendEnable    = TRUE;
        SrcBlend            = SRCALPHA;
        DestBlend           = INVSRCALPHA;
        AlphaOp[0]          = SelectArg1;
        AlphaArg1[0]        = Texture;
                               
        VertexShader = compile vs_2_0 VS_function();
        PixelShader = compile ps_2_0 PS_function();
    }  
}

The commented lines of code are the ones which I used before (playing around with float3 / float4 to get them 'working together'.

I did manage to get a working point light with a 'range' of 0.0 to 1.0f, where 1.0f = completely dark, 0.1f being fully bright, and strangely having infinite distance.

Any suggestions?

Crealysm game & engine development: http://www.crealysm.com

Looking for a passionate, disciplined and structured producer? PM me

Update; I've cleaned up the fx file/ effect and removed the error.

I was trying to use the VS output 'POSITION' in the pixel shader, now fixed that.

I got a compiling effect now, but not giving any luminance/ light at all from the point light )-;

Any suggestions?


/***********************************************************/
/**  VARS NOT CONTROLLED BY ENGINE YET             *********/
/***********************************************************/

float4 	diffuseColor 	= { 0.8f, 0.8f, 0.8f, 0.0f };    	// NEW
float3 	lightPosition 	= { 0.0f, 2.0f, 0.0f };   		// NEW
float 	lightRange 		= 3.0f;    					// NEW

// modelfile, just for effectedit
string XFile = "paving.x";   // model

/***********************************************************/
/**       VARS CONTROLLED BY ENGINE                *********/
/***********************************************************/

float4x4		World         : WORLD;
float4x4    	WorldInvTransp: WORLDINVTRANSP;
shared float4x4 	ViewProj      : VIEWPROJECTION;

float4      	AmbientColor;
float       	AmbientIntensity;

float4      	MatAmb : MATERIALAMBIENT; 
float4      	MatDiff: MATERIALDIFFUSE; 
            
texture     	Tex0 < string name = "hungary009.jpg"; >;

/***********************************************************/
/**          SAMPLER STATES FOR TEXTURING          *********/
/***********************************************************/

sampler2D textureSampler = sampler_state
{
	Texture         	= (Tex0);
                                 
    	MinFilter       	= ANISOTROPIC;
   	MagFilter       	= LINEAR;
    	MipFilter       	= LINEAR;    
    	MaxAnisotropy	= 4;            
};

struct VS_INPUT
{
	float4    Pos     : POSITION0;
    	float4    Normal  : NORMAL0;
    	float2    TexCoord: TEXCOORD0;
};

struct VS_OUTPUT
{
	float4 Pos     	: POSITION0;
    	float3 Normal  	: TEXCOORD1;
    	float2 TexCoord	: TEXCOORD2;
	float3 LightPos	: TEXCOORD3; 
	float4 wPos		: TEXCOORD4;
};

/***********************************************************/
/**          THE VERTEXSHADER        PROGRAM       *********/
/***********************************************************/

VS_OUTPUT VS_function(VS_INPUT input)
{
	VS_OUTPUT Out = (VS_OUTPUT)0;

	float4 worldPosition = mul(input.Pos, World);
    	Out.Pos = mul(worldPosition, ViewProj);

    	float4 normal = mul(input.Normal, WorldInvTransp);
    	Out.Normal = normal;
    	Out.TexCoord = input.TexCoord;

	Out.LightPos = lightPosition.xyz - worldPosition;   
    	Out.LightPos = normalize(Out.LightPos);           

	Out.wPos = Out.Pos;

	return Out;
}

/***********************************************************/
/**          THE PIXELSHADER        PROGRAM        *********/
/***********************************************************/

float4 PS_function(VS_OUTPUT input): COLOR0
{
	float4 textureColor = tex2D(textureSampler, input.TexCoord);
    	float4 amb = AmbientColor * AmbientIntensity * MatAmb;

  	float distt = distance(input.LightPos, input.wPos);
    	float attenuation = 1 - saturate(distt / lightRange);    
    	
    	return saturate((amb * textureColor) * MatDiff * attenuation); 
}

/***********************************************************/
/**          OPAUQE SHADER, REGULAR MESHES         *********/
/***********************************************************/

technique OpaqueShader
{
    pass P0              
    {
        AlphaBlendEnable    = FALSE;
                              
        VertexShader = compile vs_2_0 VS_function();
        PixelShader = compile ps_2_0 PS_function();
    }  
}

/***********************************************************/
/**   BLENDING SHADER, MESHES WITH BLENDED TEXTURES  *******/
/***********************************************************/

technique BlendingShader
{
    pass P0              
    {
        AlphaBlendEnable    = TRUE;
        SrcBlend            = SRCALPHA;
        DestBlend           = INVSRCALPHA;
        AlphaOp[0]          = SelectArg1;
        AlphaArg1[0]        = Texture;
                               
        VertexShader = compile vs_2_0 VS_function();
        PixelShader = compile ps_2_0 PS_function();
    }  
}

Crealysm game & engine development: http://www.crealysm.com

Looking for a passionate, disciplined and structured producer? PM me

You're using the screenspace position for wPos, instead of the worldPosition. I assume all your lighting calculations are done in worldspace? wPos should be made equal to worldPosition (and you can make it a float3).

I also don't understand at all what you're doing with LightPos in your vertex shader. Why are you normalizing a position? Why are you subtracting worldPosition from lightPosition.xyz?

Thanks, I found that that was from an experiment to calculate attenuation in another way.

Cleaned it up and did what you explained.

Still darkness though, will play around to see what's wrong.

If you have any suggestions....

Here's the effect now:


/***********************************************************/
/**  VARS NOT CONTROLLED BY ENGINE YET             *********/
/***********************************************************/

float4 	diffuseColor 	= { 0.8f, 0.8f, 0.8f, 0.0f };    	// NEW
float3 	lightPosition 	= { 0.0f, 1.0f, 0.0f };   		// NEW
float 	lightRange 		= 1.0f;   					// NEW

// modelfile, just for effectedit
string XFile = "paving.x";   // model

/***********************************************************/
/**       VARS CONTROLLED BY ENGINE                *********/
/***********************************************************/

float4x4		World         : WORLD;
float4x4    	WorldInvTransp: WORLDINVTRANSP;
shared float4x4 	ViewProj      : VIEWPROJECTION;

float4      	AmbientColor;
float       	AmbientIntensity;

float4      	MatAmb : MATERIALAMBIENT; 
float4      	MatDiff: MATERIALDIFFUSE; 
            
texture     	Tex0 < string name = "hungary009.jpg"; >;

/***********************************************************/
/**          SAMPLER STATES FOR TEXTURING          *********/
/***********************************************************/

sampler2D textureSampler = sampler_state
{
	Texture         	= (Tex0);
                                 
    	MinFilter       	= ANISOTROPIC;
   	MagFilter       	= LINEAR;
    	MipFilter       	= LINEAR;    
    	MaxAnisotropy	= 4;            
};
				
struct VS_INPUT
{			
	float4 Pos     	: POSITION0;
   	float4 Normal  	: NORMAL0;
    	float2 TexCoord	: TEXCOORD0;
};			

struct VS_OUTPUT
{
	float4 Pos     	: POSITION0;
    	float3 Normal  	: TEXCOORD1;
    	float2 TexCoord	: TEXCOORD2;
	float3 wPos		: TEXCOORD4;
};
					
/***********************************************************/
/**          THE VERTEXSHADER        PROGRAM       *********/
/***********************************************************/

VS_OUTPUT VS_function(VS_INPUT input)
{
	VS_OUTPUT Out = (VS_OUTPUT)0;

	float4 worldPosition = mul(input.Pos, World);
    	Out.Pos = mul(worldPosition, ViewProj);

    	float4 normal = mul(input.Normal, WorldInvTransp);

    	Out.Normal = normal;
    	Out.TexCoord = input.TexCoord;
	Out.wPos = worldPosition;

	return Out;
}

/***********************************************************/
/**          THE PIXELSHADER        PROGRAM        *********/
/***********************************************************/

float4 PS_function(VS_OUTPUT input): COLOR0
{
	float4 textureColor = tex2D(textureSampler, input.TexCoord);
    	float4 amb = AmbientColor * AmbientIntensity * MatAmb;

  	float distt = distance(lightPosition, input.wPos);
    	float attenuation = 1 - saturate(distt / lightRange);    
    	
    	return saturate((amb * textureColor) * MatDiff) * attenuation; 
}

/***********************************************************/
/**          OPAUQE SHADER, REGULAR MESHES         *********/
/***********************************************************/

technique OpaqueShader
{
    pass P0              
    {
        AlphaBlendEnable    = FALSE;
                              
        VertexShader = compile vs_2_0 VS_function();
        PixelShader = compile ps_2_0 PS_function();
    }  
}

/***********************************************************/
/**   BLENDING SHADER, MESHES WITH BLENDED TEXTURES  *******/
/***********************************************************/

technique BlendingShader
{
    pass P0              
    {
        AlphaBlendEnable    = TRUE;
        SrcBlend            = SRCALPHA;
        DestBlend           = INVSRCALPHA;
        AlphaOp[0]          = SelectArg1;
        AlphaArg1[0]        = Texture;
                               
        VertexShader = compile vs_2_0 VS_function();
        PixelShader = compile ps_2_0 PS_function();
    }  
}

Crealysm game & engine development: http://www.crealysm.com

Looking for a passionate, disciplined and structured producer? PM me

Here's the tutorial I tried to use before:

http://digitalerr0r.wordpress.com/2009/05/06/xna-shader-programming-tutorial-17-point-light-and-self-shadowing/

Crealysm game & engine development: http://www.crealysm.com

Looking for a passionate, disciplined and structured producer? PM me

This topic is closed to new replies.

Advertisement