-
Notifications
You must be signed in to change notification settings - Fork 4
/
normals.js
123 lines (106 loc) · 2.8 KB
/
normals.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
var DEFAULT_NORMALS_EPSILON = 1e-6;
var DEFAULT_FACE_EPSILON = 1e-6;
//Estimate the vertex normals of a mesh
exports.vertexNormals = function(faces, positions, specifiedEpsilon) {
var N = positions.length;
var normals = new Array(N);
var epsilon = specifiedEpsilon === void(0) ? DEFAULT_NORMALS_EPSILON : specifiedEpsilon;
//Initialize normal array
for(var i=0; i<N; ++i) {
normals[i] = [0.0, 0.0, 0.0];
}
//Walk over all the faces and add per-vertex contribution to normal weights
for(var i=0; i<faces.length; ++i) {
var f = faces[i];
var p = 0;
var c = f[f.length-1];
var n = f[0];
for(var j=0; j<f.length; ++j) {
//Shift indices back
p = c;
c = n;
n = f[(j+1) % f.length];
var v0 = positions[p];
var v1 = positions[c];
var v2 = positions[n];
//Compute infineteismal arcs
var d01 = new Array(3);
var m01 = 0.0;
var d21 = new Array(3);
var m21 = 0.0;
for(var k=0; k<3; ++k) {
d01[k] = v0[k] - v1[k];
m01 += d01[k] * d01[k];
d21[k] = v2[k] - v1[k];
m21 += d21[k] * d21[k];
}
//Accumulate values in normal
if(m01 * m21 > epsilon) {
var norm = normals[c];
var w = 1.0 / Math.sqrt(m01 * m21);
for(var k=0; k<3; ++k) {
var u = (k+1)%3;
var v = (k+2)%3;
norm[k] += w * (d21[u] * d01[v] - d21[v] * d01[u]);
}
}
}
}
//Scale all normals to unit length
for(var i=0; i<N; ++i) {
var norm = normals[i];
var m = 0.0;
for(var k=0; k<3; ++k) {
m += norm[k] * norm[k];
}
if(m > epsilon) {
var w = 1.0 / Math.sqrt(m);
for(var k=0; k<3; ++k) {
norm[k] *= w;
}
} else {
for(var k=0; k<3; ++k) {
norm[k] = 0.0;
}
}
}
//Return the resulting set of patches
return normals;
}
//Compute face normals of a mesh
exports.faceNormals = function(faces, positions, specifiedEpsilon) {
var N = faces.length;
var normals = new Array(N);
var epsilon = specifiedEpsilon === void(0) ? DEFAULT_FACE_EPSILON : specifiedEpsilon;
for(var i=0; i<N; ++i) {
var f = faces[i];
var pos = new Array(3);
for(var j=0; j<3; ++j) {
pos[j] = positions[f[j]];
}
var d01 = new Array(3);
var d21 = new Array(3);
for(var j=0; j<3; ++j) {
d01[j] = pos[1][j] - pos[0][j];
d21[j] = pos[2][j] - pos[0][j];
}
var n = new Array(3);
var l = 0.0;
for(var j=0; j<3; ++j) {
var u = (j+1)%3;
var v = (j+2)%3;
n[j] = d01[u] * d21[v] - d01[v] * d21[u];
l += n[j] * n[j];
}
if(l > epsilon) {
l = 1.0 / Math.sqrt(l);
} else {
l = 0.0;
}
for(var j=0; j<3; ++j) {
n[j] *= l;
}
normals[i] = n;
}
return normals;
}