HTML and CSS Reference
In-Depth Information
red = color >> 16,
green = color >> 8 & 0xff,
blue = color & 0xff,
lightFactor = this.getLightFactor();
red *= lightFactor;
green *= lightFactor;
blue *= lightFactor;
return utils.parseColor(red << 16 | green << 8 | blue);
};
This method first splits the triangle's base color into red, green, and blue components (see Chapter 4). The
command utils.parseColor(this.color, true) converts the color from a string format to a number.
There is a call to getLightFactor , which we'll look at next, but for now, it returns a number from 0.0 to
1.0. This is the amount to alter the color of that particular triangle, 1.0 being full brightness, and 0.0 being
black.
Each of the component colors is then multiplied by that light factor, and they are joined back into a single
color value—using utils.parseColor to convert it back to a string—and is returned as the adjusted
color. This is the color of the triangle, based on its lighting.
Now, how do you come up with this lightFactor method? Let's look:
Triangle.prototype.getLightFactor = function () {
var ab = {
x: this.pointA.x - this.pointB.x,
y: this.pointA.y - this.pointB.y,
z: this.pointA.z - this.pointB.z
};
var bc = {
x: this.pointB.x - this.pointC.x,
y: this.pointB.y - this.pointC.y,
z: this.pointB.z - this.pointC.z
};
var norm = {
x: (ab.y * bc.z) - (ab.z * bc.y),
y:-((ab.x * bc.z) - (ab.z * bc.x)),
z: (ab.x * bc.y) - (ab.y * bc.x)
};
var dotProd = norm.x * this.light.x +
norm.y * this.light.y +
norm.z * this.light.z;
var normMag = Math.sqrt(norm.x * norm.x +
norm.y * norm.y +
norm.z * norm.z);
var lightMag = Math.sqrt(this.light.x * this.light.x +
this.light.y * this.light.y +
this.light.z * this.light.z);
return (Math.acos(dotProd / (normMag * lightMag)) / Math.PI) * this.light.brightness;
};
Now that is quite a function to take in. To fully understand all that's going on here, you need a
good grasp of advanced vector math, but we'll walk through the basics of it.
Search WWH ::




Custom Search