Game Development Reference
In-Depth Information
We have moved the function
getIndicesFromFaces(faces)
from the
parseJSON.
js
file to the
Geometry.js
file and renamed it to
indicesFromFaces
, since it
populates the class variable
indices
. It now processes the class variable
faces
of the
Geometry
class to update its class variable
indices
as shown in the following code:
indicesFromFaces:function (){
for(var i=0;i<this.faces.length;++i){
this.indices.push(this.faces[i].a);
this.indices.push(this.faces[i].b);
this.indices.push(this.faces[i].c);
}
},
We also moved the
calculateVertexNormals
function from the
utils.js
file to
the
geometry.js
file. This function is described in depth in the
Understanding surface
normals for lighting calculations
section of
Chapter 2
,
Colors and Shading Languages
. The
only difference in the following code is that it processes class variables
vertices
and
indices
instead of the function parameters:
calculateVertexNormals:function(){
var vertexVectors=[];
var normalVectors=[];
var j;
for(var i=0;i<this.vertices.length;i=i+3){
var vector=vec3.fromValues(this.vertices[i],
this.vertices[i+1],this.vertices[i+2]);
var normal=vec3.create();//Intialiazed normal array
normalVectors.push(normal);
vertexVectors.push(vector);
}
for(j=0;j<this.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[this.indices[j+1]],
vertexVectors[this.indices[j]]);
//v2-v1
var vector2=vec3.create();
vec3.subtract(vector2,vertexVectors[this.indices[j+2]],
vertexVectors[this.indices[j+1]]);
var normal=vec3.create();
//cross product of two vector
vec3.cross(normal, vector1, vector2);