WebGL Textures & Vertices

Beginner's Guide

Page Fifty Four

Upload Perspective Projection Matrix

The controller's constructor calls method getProgramVariables() which prepares shader variables, including the perspective projection matrix. The method getProgramVariables() follows three steps to upload a perspective projection matrix to the shader.

  1. Obtain the location of um4_pmatrix from the vertex shader with WebGL method getUniformLocation().
  2. Generate a 4 x 4 JavaScript matrix with values for perspective projection.
  3. Upload the JavaScript matrix to um4_pmatrix with WebGL method uniformMatrix4fv().

WebGL API getUniformLocation(WebGLProgram,String)

The WebGL API method getUniformLocation(WebGLProgram,String) returns the location of a uniform from a shader. The first parameter to getUniformLocation(WebGLProgram,String) is a WebGLProgram with linked shaders. The second parameter to getUniformLocation(WebGLProgram,String) is the name of the uniform within quotation marks. The following listing demonstrates how the method getProgramVariables() obtains the location of um4_pmatrix from the book's vertex shader. gl is the WebGLContext and program is a reference to the compiled and linked WebGLProgram.

var uMP = gl.getUniformLocation

Listing 47: WebGL API getUniformLocation(WebGLProgram,String)

The following JavaScript array functions as a perspective projection matrix. The matrix gives the illusion of one point perspective with approximately 450 field of view. Cast the JavaScript array to type Float32Array, for use within WebGL. A Float32Array means every entry represents a floating point number with 32 bits of precision.

var aMP = new Float32Array(

Listing 48: JavaScript Perspective Projection Matrix

WebGL API uniformMatrix4fv(WebGLUniformLocation, Boolean, Float32Array)

Use the WebGL API method uniformMatrix4fv(WebGLUniformLocation, Boolean, Float32Array) to upload a Float32Array of data to a shader's uniform. In other words copy our JavaScript array of numbers to the shader's uniform named um4_pmatrix. The Float32Array must represent a 4 x 4 matrix. The Boolean parameter must equal gl.FALSE.


Listing 49: WebGL API uniformMatrix4fv(WebGLUniformLocation, Boolean, Float32Array)

Perspective Projection Summary

This section briefly described how the book applies perspective projection and what perspective projection accomplishes. Perspective projection provides the illusion of depth and volume. Mesh elements in the distance appear smaller and closer together. Lines converge toward the center of projection.

Method getProgramVariables() prepares a JavaScript 4 x 4 matrix for perspective projection, then uploads the matrix to the vertex shader's uniform named um4_pmatrix. The vertex shader multiplies every vertex in a mesh by the matrix.

WebGL Beginner's Guide Introduction WebGL Beginner's Guide
Copyright © 2015 Seven Thunder Software. All Rights Reserved.