Game Development Reference
In-Depth Information
for(var j=0;j<indices.length;j=j+3)//Since we are using triads
of indices to represent one primitive
{
//v1-v0
var vector1=vec3.create();
vec3.subtract(vector1,vertexVectors[indices[j+1]],
vertexVectors[indices[j]]);
//v2-v1
var vector2=vec3.create();
vec3.subtract(vector2,vertexVectors[indices[j+2]],
vertexVectors[indices[j+1]]);
var normal=vec3.create();
//cross-product of two vectors
vec3.cross(normal, vector1, vector2);
//Since the normal caculated from three vertices is the same for
all the three vertices(same face/surface), the contribution
from each normal to the corresponding vertex is the same
vec3.add(normalVectors[indices[j]],
normalVectors[indices[j]],normal);
vec3.add(normalVectors[indices[j+1]],
normalVectors[indices[j+1]],normal);
vec3.add(normalVectors[indices[j+2]],
normalVectors[indices[j+2]],normal);
}
for(var j=0;j<normalVectors.length;j=j+1){
vec3.normalize(normalVectors[j],normalVectors[j]);
normals.push(normalVectors[j][0]);
normals.push(normalVectors[j][1]);
normals.push(normalVectors[j][2]);
}
return normals;
}
In the preceding code, the
calculateVertexNormals
function takes the
vertices
and
indices
arrays. The triads of elements of the vertex array define a single vertex;
hence, we create a
vec3
object of each triad. Each triad of the
indices
array defines
vertices of a triangle; hence, when we iterate over the array, we get all the vertices
of the triangle from the
vertexVectors
array. From these vertices, we calculate
the normal for that particular vertex. As all three vertices belong to the same face/
surface/triangle, the normal of each vertex is the same. Therefore, we calculate only
one normal and add it to all the normals of the three vertices. The last loop iterates
over the
normalVector
array, normalizes it, and then unpacks the
vec3
object to
generate the normal array. We only need the direction of the normal and not its
magnitude, since normals are unit vectors.