1. 程式人生 > >用Shader實現標準光照模型

用Shader實現標準光照模型

DXSDK裡光照模型的講解依然停留在DX9的固定管線時代; DX10及DX11的文件裡只是API文件,居然一點基於Shader的光照模型講解文章都未見,失望.

無奈, 開啟NV官網,找到這樣一篇文章, 基於Cg語言的Shader標準光照模型講解, Bingo!

瞭解標準光照基礎知識後,就不會面對MAX的材質系統, Maya的Node Based Material System感到陌生.

這裡貼下這組光照模型的Cg程式碼

float4x4 matViewProjection;
float3 GlobalAmbient;
float3 LightColor;
float3 LightPosition;
float4 EyePosition;
float3 Ke;
float3 Ka;
float3 Kd;
float3 Ks;
float Shininess;
void vs_main( 
   in float4 InPosition : POSITION,
   in float3 InNormal : NORMAL,
   out float4 OutPosition : POSITION,
   out float4 OutColor : COLOR0
 )
{
   OutPosition = mul( InPosition, matViewProjection );
   float3 P = InPosition.xyz;
   float3 N = InNormal;
   // Compute the emissive term
   float3 Emissive = Ke;
    // Compute the ambient term
   float3 Ambient = Ka * GlobalAmbient;
   // Compute the diffuse term
   float3 L = normalize( LightPosition - P );
   float DiffuseLight = max( dot( N, L ), 0 );
   float3 Diffuse = Kd * LightColor * DiffuseLight;
   // Compute the specular term
   float3 V = normalize( EyePosition - P );
   float3 H = normalize( L + V );
   float SpecularLight = pow( max( dot( N, H ), 0 ), Shininess );
   if ( DiffuseLight <= 0 )  SpecularLight = 0;
   float3 Specular = Ks * LightColor * SpecularLight;
   OutColor.xyz = Emissive +  Ambient + Diffuse + Specular;
   OutColor.w = 1;   
}
float4 ps_main( float4 OutColor : COLOR0 ) : COLOR0
{   
   return( OutColor );
}