Sign in to follow this  
Waaayoff

Would someone look at my EXTREMELY simple lighting shader?

Recommended Posts

Waaayoff    952
I pieced this (extremely simple) lighting shader together from online articles, it can only do ambient, diffuse and specular lighting. I was wondering if someone could look at the code and tell me if it could be better.


[code]float4x4 WorldViewProj;
float4x4 World;

float4 MatDiffuse;
float3 MatAmbient;
float3 MatSpecular;
float MatPower;

#define MAX_LIGHTS 3

float3 AmbientLight;
float4 DiffuseLight[MAX_LIGHTS];
float3 SpecularLight[MAX_LIGHTS];
float3 LightDirection[MAX_LIGHTS];
float3 CamPosition;
int nLights;

struct VS_IN
{
float4 Position : POSITION;
float3 Normal : NORMAL;
};

struct VS_OUT
{
float4 Position : POSITION;
float3 Light[MAX_LIGHTS] : TEXCOORD0;
float3 Normal : TEXCOORD3;
float3 CamView : TEXCOORD4;
};

struct PS_OUT
{
float4 Colour : COLOR;
};

VS_OUT VShader(VS_IN input)
{
VS_OUT output = (VS_OUT)0;

output.Position = mul(input.Position, WorldViewProj);
output.Normal = mul(float4(input.Normal, 0.0f), World).xyz;
output.CamView = CamPosition - mul(input.Position, World);

return output;
}

PS_OUT PShader(VS_OUT input)
{
PS_OUT output = (PS_OUT)0;

float3 Normal = normalize(input.Normal);

float3 TotalDiffuse = float3(0,0,0);
float3 TotalSpecular = float3(0,0,0);

for (int i = 0; i < nLights; i++)
{
input.Light[i] = normalize(LightDirection[i]);
float3 Half = normalize(input.Light[i] + normalize(input.CamView));
TotalSpecular += (MatSpecular * SpecularLight[i]) * pow(saturate(dot(Normal, Half)), MatPower);
TotalDiffuse += (MatDiffuse * DiffuseLight[i]).rgb * saturate(dot(input.Light[i], Normal));
}

output.Colour.rgb = (MatAmbient * AmbientLight) + TotalDiffuse + TotalSpecular;
output.Colour.a = MatDiffuse.a;

return output;
}

technique FirstTechnique
{
pass FirstPass
{
Lighting = false;
CullMode = None;

VertexShader = compile vs_2_0 VShader();
PixelShader = compile ps_2_0 PShader();
}
}[/code]

And here's an image with the result (only 1 light)

FPS Fail btw. Lousy laptop.

[img]http://img820.imageshack.us/img820/939/unledrt.jpg[/img]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this