defunct
defunct

Reputation: 81

How perspective matrix works?

I started to read lesson 1 in learningwebgl blog, and I noticed this part:

var pMatrix = mat4.create();
mat4.perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0, pMatrix);

I roughly understand how matrices (translation/rotation/multiple) works, but I have no idea what mat4.perspective(...) means. What is it used for? What is the result, if I multiply a vector with this matrix?

Upvotes: 2

Views: 4661

Answers (2)

user1157123
user1157123

Reputation:

The perspective matrix is used to scale, and possibly translate or flip the coordinate system in preparation for the perspective divide. Since the the perspective projection operation involves a divide, it cannot be represented by a linear matrix transformation alone.

In a programmable graphics pipeline (see pixel shaders) you cannot see the divide operation - it is still one of the fixed-function parts. The programmer controls it by tweaking the variables involved in the operation. In the case of the perspective divide it is the projection matrix that gives you this control.

Upvotes: 6

Philipp
Philipp

Reputation: 69703

The projection matrix is used to convert world-coordinates to screen coordinates.

The positions in your three-dimensional virtual world are triplets of x, y and z coordinates. When you want to draw something (or rather tell OpenGL to draw something) it needs to calculation where these coordinates are on the users screen.

This calculation is implemented with matrix multiplication.

A vector consisting of x, y and z (and a fourth value of 1 which is necessary to allow the matrix to do some operations like scaling) is multiplied with a matrix to receive a new set of x, y and z coordinates (4th value is discarded) which represent where this point is on the users screen (the z-coordinate is required to determine which objects are in front of others).

The function mat4.perspective generates a projection matrix which generates a matrix which does exactly that. The arguments are:

  • The field-of-view in degree (45)
  • the aspect ratio of the field of view (the aspect ratio of the viewport)
  • the minimal distance from the viewer which is still drawn (0.1 world units)
  • the maximum distance from the viewer which is still drawn (100.0 world units)
  • the array in which the generated matrix is stored (pMatrix)

When a point is multiplied with this matrix, the result are the screen coordinates where this point has to be drawn.

Upvotes: -1

Related Questions