Lighting - Shader Langauge - Vector Magnitude

I am playing with Lesson 12 (Ambient And Point Lighting) from the WebGL Tutorials provided at:


I adapted the example to my own use but I noticed that the lighting does not drop off over distance. This is not a problem in a crowded scene where the light is likely to end up hitting something before traveling any significant distance but in a more open scene it is a problem. Think of a candle in a large room. The candle is bright and will illuminate objects near it but only a short distance away and objects are almost not illuminated at all. :frowning:

For the lesson it seems that the calculation to obtain the light on any particular fragment is done (on the shader) using:

vec3 lightDirection = normalize(uPointLightingLocation -;
vec3 transformedNormal = uNMatrix * aVertexNormal;
float directionalLightWeighting = max(dot(transformedNormal, lightDirection), 0.0);
vLightWeighting = uAmbientColor + uPointLightingColor * directionalLightWeighting; 

So it basically adds the ambient component plus the point light contribution which is based on the point light and its angle to the fragment. :stuck_out_tongue:

To me it seems that if I multiply the point light contribution by some fractional factor based on the distance between the point light and the fragment then I can make the light intensity drop off the further it is from the point light source. :wink:

The distance, if I understand things correctly, should be the magnitude of uPointLightingLocation - :?:

However, I am not sure what the shader language command for getting the magnitude of a vector is. :?

If anyone knows this, please let me know. It would be very helpful.

Looking at the WebGL Quick Reference Card … rd-1_0.pdf

You want length()

as in

float distanceToLight = length(uPointLightingLocation -


I’ll give that a try.

I have familiarity with Javascript but not with the shader language.

Doh! If I had looked just one line down the reference card I would have seen the distance function

float distanceToLight = distance(uPointLightingLocation,;

Hmmm…using length seemed to have worked just fine.

I have already adjusted my code and my theory worked great. Now the light source contribution drops off as the fragments are further away from the light source.


Yes, distance() is pretty much the length of the difference between the two, but distance does allow for some optimizations by the GPU, thus using it can sometimes be faster. Now it might not be the case with this method, but generally, it is a good idea to try to use as much of the built in methods as possible.