Monday, November 02, 2009

Cg Lighting Function

This a cool lighting function written in Nvidia Cg. It's pretty generalistic, its basically just a normal sum of the ambient + emissive + diffuse + specular. It can be the same for per pixel or vertex lighting.



struct Material
{
float4 Ka;
float4 Ke;
float4 Kd;
float4 Ks;
float shininess;
};

struct Light
{
float3 position;
float4 diffuseColor;
float4 specularColor;
};

float4 lighting(Material material,
Light light,
float4 globalAmbient,
float4 position,
float3 normal,
float3 eyePosition)
{
//Normalize the normal
normal = normalize(normal);

//Compute the ambient light
float4 ambient = globalAmbient * material.Ka;

//Compute the emissive term
float4 emissive = material.Ke;

//Compute the diffuse term
float3 lightVector = normalize(light.position - position);
float diffuseLight = max(dot(normal, lightVector), 0);
float4 diffuse = material.Kd * light.diffuseColor * diffuseLight;

//Compute the specular term
float3 viewVector = normalize(eyePosition - position);
float3 halfAngleVector = normalize(lightVector + viewVector);
float specularLight = pow(max(dot(normal, halfAngleVector), 0), material.shininess);
if(diffuseLight <= 0) specularLight = 0; float4 specular = material.Ks * light.specularColor * specularLight; return ambient + emissive + diffuse + specular; }




That´s it

I'm using Ogre for this trials, so i'm also supplying the Ogre .material and .program files, as well as some cg shaders using this function in a PerPixel, Vertex and FixedPipeline Contexts. Any doubts or critics go fuck yourself, do you think i'm your mother?


Material File

Also check some pics, it's the same model ( a low tessellated sphere ), with the same texture applied. You can quickly see the difference in both quality and the frame rate penalty.







No comments: