-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathphong.js
83 lines (67 loc) · 2.03 KB
/
phong.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Phong illumination calculations for a given visible point on an object
class Phong {
constructor(scene, obj, intersect) {
this.scene = scene;
this.obj = obj;
this.intersect = intersect;
this._normal = obj.getSurfaceNormal(intersect);
}
ambientTerm() { // -> Color
return cScale(this.scene.iA, this.obj.material.ambient);
}
diffuseTerm() { // -> Color
if (this.dotNormalLight < 0) {
return new Color(0, 0, 0);
}
return cScaleS(
cScale(this.obj.material.diffuse, this.light.diffuse),
this.dotNormalLight
);
}
specularTerm() { // -> Color
if (this.dotNormalLight < 0) {
return new Color(0, 0, 0);
}
const reflectance = vSub(vScale(this._normal, 2 * this.dotNormalLight), this.lUnit);
// View unit
const view = vSub(this.scene.camera, this.intersect);
const viewUnit = vScale(view, 1 / vLength(view));
const dotViewReflect = vDotProduct(viewUnit, reflectance);
return cScaleS(
cScale(this.obj.material.specular, this.light.specular),
Math.pow(dotViewReflect, this.obj.material.shininess)
);
}
isInShadow() { // -> Boolean
const shadowRay = new Ray( // intersection --> light
this.intersect,
vSub(this.light.location, this.intersect)
);
for (let i = 0; i < this.scene.objects.length; i++) {
const shadowT = this.scene.objects[i].intersectRay(shadowRay);
if (0.00001 < shadowT && shadowT < 1) {
// In shadow, don't add diffuse / specular
return true;
}
}
return false;
}
// Dot product of surface normal with normalized light vector
get dotNormalLight() { // -> dbl
return vDotProduct(this.lUnit, this._normal);
}
// Normalized light vector
get lUnit() { // Vector
const l = vSub(this.light.location, this.intersect);
return vScale(l, 1 / vLength(l));
}
set light(light) {
this._light = light;
}
get light() {
if (!this._light) {
throw new Error("Phong instance has no light source set.");
}
return this._light;
}
}