Game Development Reference
In-Depth Information
Here,
[234]
denotes 2 x 2 arrays, 3 x 3 arrays, and 4 x 4 arrays. The
transpose
parameter will automatically transpose the matrix while passing its values to the
shader, and in the function names (
uniformMatrix3fv
,
uniformMatrix3iv
), the
f
or
i
denotes that we are passing a float or an integer:
function drawScene() {
gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
mat4.perspective(pMatrix,40, gl.viewportWidth /
gl.viewportHeight, 0.1, 1000.0);
mat4.identity(mvMatrix);
mat4.translate(mvMatrix,mvMatrix, [0.0, 0.0,-3.0]);
//mat4.scale(mvMatrix,mvMatrix,[10,10,10]);
mat4.rotateY(mvMatrix,mvMatrix,rotateY);
mat4.rotateX(mvMatrix,mvMatrix,rotateZ);
gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer);
gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute,
vertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, vertexNormalBuffer);
gl.vertexAttribPointer(shaderProgram.vertexNormalAttribute,
vertexNormalBuffer.itemSize, gl.FLOAT, false, 0, 0);
setMatrixUniforms();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.drawElements(gl.TRIANGLES, indices.length,
gl.UNSIGNED_SHORT,0);
}
Let's go over the
drawScene
function once again. First, we create a perspective matrix
with
40
as the
field of view
(
FOV
),
gl.viewportWidth
or
gl.viewportHeight
as the aspect ratio,
0.1
as the near plane, and
1000.0
as the far plane. We will
discuss these parameters in the
Understanding perspective transformations
section in
Chapter 5
,
Camera and User Interaction
. We initialize the ModelView matrix as the
identity matrix. We translate and rotate
mvMatrix
with variable angles controlled
by key presses. We associate the shader variable
vertexPositionAttribute
with
vertexPositionBuffer
and
vertexNormalAttribute
with
vertexNormalBuffer
,
and then invoke the
drawElements
functions after specifying the
indexBuffer
variable as the active
gl.ELEMENT_ARRAY_BUFFER
constant. The OBJ file has 3
n
indices,
n
being the number of triangles to be drawn; hence, we use
gl.TRIANGLES
as the mode in the
drawElements
function call.