3D
You may need to read the article about transformation before this one.
Orthographic 3D
Using an orthographic projection matrix, primitives can be drawn in three dimensions without regard to perspective.
Polygon Culling
In the example above, the back of the rotating shape shows through to the front in some places. One way to fix this is with polygon culling, which is where only front- or back-facing triangles are rendered. By default, a polygon is considered front-facing if its vertices are defined in a counter-clockwise orientation relative to the camera. Polygon culling can be enabled with enable
. You can specify whether front- or back-facing polygons should be culled with cullFace
.
gl.enable(gl.CULL_FACE);
gl.cullFace(gl.BACK);
Enabling polygon culling will make any triangles that are defined in the wrong orientation invisible. The orientation of a triangle can be reversed by swapping the order of the last two vertices.
Depth Testing
In the example above, some polygons are showing through others that are in front of them. To fix this, enable depth testing, which tests the depth of fragments and only rasterizes them if they pass. The depth of fragments is computed from gl_Position.z
and is stored in the depth buffer.
Depth testing can be enabled with enable
.
gl.enable(gl.DEPTH_TEST);
Like the color buffer, the depth buffer should be cleared at the beginning of every frame. A value can be set for fragments to be cleared to with clearDepth
.
gl.clearDepth(1);
gl.clear(gl.DEPTH_BUFFER_BIT);
The color and depth buffers can be cleared at the same time with a bitwise or operator.
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
Perspective
Since WebGL automatically divides gl_Position.xyz
by gl_Position.w
, it can be used to apply perspective. A perspective projection is a projection that scales each vertex based on its distance from the camera.
Cameras
Rather than move a scene to fit in the view of the camera, it is more common to move the camera to view the scene. To do so, a matrix called a camera matrix can be made to represent the transformation of the camera. This can be inverted to make a view matrix, which represents the transformation that would move the scene into the view of the camera. A projection matrix can be multiplied by a view matrix to make a view projection matrix, which can be used to both apply perspective and move the scene into the view of the camera. The product of a view projection matrix and a world matrix is called a world view projection matrix.
gl_Position = u_view * u_proj * u_world * a_position;
The next article is about textures.