measure how much a triangle face a light

时间:2015-07-28 15:55:04

标签: javascript math matrix geometry

I have 3 vertices forming a triangle:

var a = [0, 0, 0];
var b = [1, 0, 0];
var c = [1, 1, 0];

and a light:

var d = [0, 1, 1];

enter image description here

How can I compute if the triangle face the light or not, and how much?

1 个答案:

答案 0 :(得分:2)

I guess you want to calculate the intensity of the point over the whole triangle. Conceptually the code could look like this:

var vector1 = Vector(c, a); // a vector from a -> c
var vector2 = Vector(b, a); // a vector from a -> c
var normal = cross(vector1, vector2);

// normalize the vector, i.e length of the normal vector is 1
normal = normalize(normal);

var vectorToLightSource = Vector(lightSourceVector, a); // Any point could be taken. The result would vary some.
vectorToLightSource = normalize(vectorToLightSource);

// This will be a value between -1 and 1, but light can't be negative
var intensity = dotProduct(normal, vectorToLightSource); 
intensity = intensity > 0 ? intensity : 0;

Now you could take the color of the triangle to be color = lightSourceColor*intensity.

The code above is very pseudo; functions like cross,normalize etc needs to be constructed. For this I recommend using a geometry library, or if you like linear algebra you could construct them yourself :)

For reference:

cross: https://en.wikipedia.org/wiki/Cross_product

dotProduct: https://en.wikipedia.org/wiki/Dot_product

normalize: https://en.wikipedia.org/wiki/Unit_vector