# Need help with lighting math

This topic is 4312 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I am trying to emulate OpenGL hardware vertex lighting in C. This is my code:
//lightColor holds the RGB light color
lightColor = <RGB light color>;
//lightPos holds the light pos in eye space (translated & rotated)
lightPos = <xyz light position>;
//vertNorm holds the vertex normal in eye space (rotated)
vertNorm = <xyz vertex normal>;
NdotL = Dot (vertNorm, Normalize (lightPos));
if (NdotL < 0.0)
NdotL = 0.0;
// matAmbient, matDiffuse are ambient and diffuse material colors
vertColor = lightColor * (matDiffuse * NdotL + matAmbient);


Depending on where the viewer faces, there is no light, or the light at wrong positions. Looks like I am just too dang stupid to figure the bloody 3D math needed for this. Oh yeah, the application does its own translation and rotation, the OpenGL matrices are all set to identity. Where did I go wrong please? How does the correct code have to look like?

##### Share on other sites
You have the right idea. Remember that for diffuse lighting it's the angle between the vertex normal, and the vertex-to-light vector (normalized). You have one of those correct, but not the other.

##### Share on other sites
Would you do me a favor and write down the correct version? I still don't know what isn't correct here.

Should it be "NdotL = Dot (vertNorm, Normalize (lightPos - vertPos));" ?

##### Share on other sites
yes. We want to find the vector from the given vertex to the light position, then dot that with the normal at that vertex. Your newer calculation is doing just that :)

See, you're not too dumb to figure it out at all.

##### Share on other sites
Mind giving me a reflect() function for a vertex normal and a vector from that vertex?

##### Share on other sites
Thx for minding. :)

1. 1
Rutin
24
2. 2
3. 3
JoeJ
20
4. 4
5. 5

• 9
• 46
• 41
• 23
• 13
• ### Forum Statistics

• Total Topics
631749
• Total Posts
3002031
×