12 13 14 15 16

# glMatrix

83

We'll start to deal with 3D objects very soon. At that point you'll need some JavaScript library to work with vectors and matrices. You'll need it to set up camera, to transform objects, etc. There are several libraries offered over the internet. In this lesson we will learn how to set up and use `glMatrix` library.

## glMatrix installation

2. Unzip the archive;
3. Put `/dist/gl-matrix-min.js` near your HTML page;
4. Include the script into your page:
``<script src="gl-matrix-min.js"></script>``

## glMatrix usage

At the beginning we'll need just two operations of `glMatrix`: creating a perspective projection matrix and creating a view matrix. Everythings of `glMatrix` live inside `glMatrix` namespace, so first thing I suggest to do after including of the `glMatrix` script is to deconstruct `glMatrix` object. Just to make thing clean so you could write `mat4` instead of `glMatrix.mat4`:

``````<script type="text/javascript">
const {mat2, mat3, mat4, vec2, vec3, vec4} = glMatrix;
</script>``````

Now let's create a perspective projection and view matrices:

``````<script type="text/javascript">
const {mat2, mat3, mat4, vec2, vec3, vec4} = glMatrix;

const project = mat4.create();
mat4.perspective(project, Math.PI / 2, 16 / 9, 1 / 256, 256);

const view = mat4.create();
mat4.lookAt(view, vec3.fromValues(0, 0, 0), vec3.fromValues(0, 1, 0), vec3.fromValues(0, 0, 1));

console.log(project, view);
</script>``````

If everything works right, you should see in the developer's console something like this:

``````Float32Array(16) [0.4630272090435028, 0, 0, 0, 0, 0.6173696517944336,
0, 0, 0, 0, -1.0001220703125, -1, 0, 0, -0.015625953674316406, 0]

Float32Array(16) [1, 0, 0, 0, 0, 0, -1, 0, -0, 1, 0, 0, -0, -0, -0, 1]``````

As you can see, `mat4` is just an extended instance of `Float32Array`. Which means that you can pass it “as is” into the GLSL program. First, set up uniforms in the vertex program:

``````#version 300 es
precision highp float;

uniform mat4 project;
uniform mat4 view;

in vec3 position;

void main(void)
{
gl_Position = project * view * vec4(position, 1.0);
}``````

And then pass their values from JavaScript:

``````gl.useProgram(program);

const project = mat4.create();
mat4.perspective(project, 90, 16 / 9, 1 / 256, 256);
const projectUniform = gl.getUniformLocation(program, "project");
gl.uniformMatrix4fv(projectUniform, false, project);

const view = mat4.create();
mat4.lookAt(view, vec3.fromValues(0, 0, 0), vec3.fromValues(0, 1, 0), vec3.fromValues(0, 0, 1));
const viewUniform = gl.getUniformLocation(program, "view");
gl.uniformMatrix4fv(viewUniform, false, view);``````

Now you're all set up. We'll talk about matrices and how do they work in future lesson when we finally begin to render 3D objects.

Lesson 14

Lesson 16