X

HLSL Normal Mapping

  • October 4, 2013
  • By admin
  • Comments Off on HLSL Normal Mapping
  • in

Direct X High Level Shading Language

Normal Mapping

 

Vertax Shader

 

struct VS_INPUT

{

float4 mPosition : POSITION;

float3 mNormal : NORMAL;

float3 mTangent : TANGENT;

float3 mBinormal : BINORMAL;

float2 mUV : TEXCOORD0;

};

 

struct VS_OUTPUT

{

float4 mPosition : POSITION;

float2 mUV : TEXCOORD0;

float3 mLightDir : TEXCOORD1;

float3 mViewDir : TEXCOORD2;

float3 T : TEXCOORD3;

float3 B : TEXCOORD4;

float3 N : TEXCOORD5;

};

 

float4x4 gWorldMatrix;

float4x4 gWorldViewProjectionMatrix;

 

float4 gWorldLightPosition;

float4 gWorldCameraPosition;

 

VS_OUTPUT vs_main (VS_INPUT Input)

{

VS_OUTPUT Output;

Output.mPosition = mul(Input.mPosition, gWorldViewProjectionMatrix);

Output.mUV = Input.mUV;

float4 worldPosition = mul(Input.mPosition, gWorldMatrix);

float3 lightDir = worldPosition.xyz - gWorldLightPosition.xyz;

Output.mLightDir = normalize(lightDir);

float3 viewDir = worldPosition.xyz - gWorldCameraPosition.xyz;

Output.mViewDir = normalize(viewDir);

float3 worldNormal = mul(Input.mNormal, (float3x3)gWorldMatrix);

Output.N = normalize(worldNormal);

float3 worldTangent = mul(Input.mTangent, (float3x3)gWorldMatrix);

Output.T = normalize(worldTangent);

float3 worldBinormal = mul(Input.mBinormal, (float3x3)gWorldMatrix);

Output.B = normalize(worldBinormal);

return Output;

}

 

Pixel Shader

 

struct PS_INPUT

{

float2 mUV : TEXCOORD0;

float3 mLightDir : TEXCOORD1;

float3 mViewDir : TEXCOORD2;

float3 T : TEXCOORD3;

float3 B : TEXCOORD4;

float3 N : TEXCOORD5;

};

 

sampler2D DiffuseSampler;

sampler2D SpecularSampler;

sampler2D NormalSampler;

float3 gLightColor;

 

float4 ps_main (PS_INPUT Input) : COLOR

{

float3 tangentNormal = tex2D(NormalSampler, Input.mUV).xyz;

tangentNormal = normalize(tangentNormal * 2 - 1);

float3x3 TBN = float3x3(normalize(Input.T), normalize(Input.B), normalize(Input.N));

TBN = transpose(TBN);

float3 worldNormal = mul(TBN, tangentNormal);

float4 albedo = tex2D(DiffuseSampler, Input.mUV);

float3 lightDir = normalize(Input.mLightDir);

float3 diffuse = saturate(dot(worldNormal, -lightDir));

diffuse = gLightColor * albedo.rgb * diffuse;

float3 specular = 0;

if (diffuse.x > 0)

{

float3 reflection = reflect(lightDir, worldNormal);

float3 viewDir = normalize(Input.mViewDir);

specular = saturate(dot(reflection, -viewDir));

specular = pow(specular, 20.0f);

float4 specularIntensity = tex2D(SpecularSampler, Input.mUV);

specular *= specularIntensity.rgb * gLightColor;

}

float3 ambient = float3(0.1f, 0.1f, 0.1f) * albedo;

return float4(ambient + diffuse + specular, 1);

}

Contact Me

Using the contact form to send me email at below

Keep in touch with me

You can use the following information to contact me if anything need to communicate.

Name: Luke Lee (yongmin)