TExcelTAD
Home › Linear Algebra & Matrix Theory › 3D Graphics: Transform Pipelines

3D Graphics: Transform Pipelines

Every vertex drawn by a game engine or a 3D web page passes through a chain of 4×44 \times 4 matrices: model, view and projection. This lesson builds that pipeline from scratch in NumPy, so you can see exactly what the GPU's vertex shader does with projection * view * model * position.

Why 4×44 \times 4 matrices?

Rotation and scaling are linear maps of R3\mathbb{R}^3, so they are 3×33 \times 3 matrices (The Matrix of a Linear Transformation). Translation x↦x+t\mathbf{x} \mapsto \mathbf{x} + \mathbf{t} is not linear (it moves the origin), so it has no 3×33 \times 3 matrix. The trick is homogeneous coordinates: write a point as (x,y,z,1)(x, y, z, 1) and a direction as (x,y,z,0)(x, y, z, 0). Then a translation becomes a linear map of R4\mathbb{R}^4:

[100tx010ty001tz0001][xyz1]=[x+txy+tyz+tz1]\begin{bmatrix} 1 & 0 & 0 & t_x \\ 0 & 1 & 0 & t_y \\ 0 & 0 & 1 & t_z \\ 0 & 0 & 0 & 1 \end{bmatrix} \begin{bmatrix} x \\ y \\ z \\ 1 \end{bmatrix} = \begin{bmatrix} x + t_x \\ y + t_y \\ z + t_z \\ 1 \end{bmatrix}

Directions (w=0w = 0) ignore the translation column, which is what we want for normals and velocities. Now every transform, including translation and perspective, is one matrix, and a chain of them collapses into one product. See Homogeneous Coordinates for the game-programming view.

The pipeline

Stage Matrix From → to
Model M=T⋅R⋅SM = T \cdot R \cdot S object (local) space → world space
View V=(camera’s world transform)−1V = (\text{camera's world transform})^{-1} world space → camera (eye) space
Projection PP eye space → clip space (x,y,z,w)(x, y, z, w)
Perspective divide divide by ww clip space → normalized device coordinates, each in [−1,1][-1, 1]
Viewport scale and shift NDC → pixel coordinates

A vertex is transformed as clip=P⋅V⋅M⋅v\text{clip} = P \cdot V \cdot M \cdot \mathbf{v}. Read right to left: the matrix nearest the vector acts first. The order inside MM matters too: T⋅R⋅ST \cdot R \cdot S scales, then rotates, then translates (TRS).

python · try it yourself
import numpy as np

def translate(tx, ty, tz):
    M = np.eye(4); M[:3, 3] = [tx, ty, tz]; return M

def rotate_y(deg):
    c, s = np.cos(np.radians(deg)), np.sin(np.radians(deg))
    return np.array([[c, 0, s, 0], [0, 1, 0, 0], [-s, 0, c, 0], [0, 0, 0, 1]])

def scale(sx, sy, sz):
    return np.diag([sx, sy, sz, 1.0])

M = translate(5, 0, 0) @ rotate_y(90) @ scale(2, 2, 2)
corner = np.array([1, 0, 0, 1.0])          # a point in model space
print("world position:", np.round(M @ corner, 4))
print("direction (w=0):", np.round(M @ np.array([1, 0, 0, 0.0]), 4))
wrong = scale(2, 2, 2) @ rotate_y(90) @ translate(5, 0, 0)
print("other order:   ", np.round(wrong @ corner, 4))
world position: [ 5.  0. -2.  1.]
direction (w=0): [ 0.  0. -2.  0.]
other order:    [  0.   0. -12.   1.]

The point (1,0,0)(1, 0, 0) is scaled to (2,0,0)(2, 0, 0), rotated 90° about yy to (0,0,−2)(0, 0, -2) and moved to (5,0,−2)(5, 0, -2). Multiplying in the wrong order translates first and then rotates and scales the translation too.

The view matrix

A camera at position e\mathbf{e} looking at a target has an orthonormal basis: right r\mathbf{r}, up u\mathbf{u} and backward b\mathbf{b} (OpenGL cameras look down their −z-z axis). Its world transform is C=[r u b e]C = [\mathbf{r}\ \mathbf{u}\ \mathbf{b}\ \mathbf{e}] (as columns, with a bottom row 0 0 0 1). The view matrix is C−1C^{-1}, and since the 3×33 \times 3 part is orthogonal, the inverse is cheap: transpose the rotation and apply −RTe-R^T\mathbf{e} as the translation. This is the classic lookAt (Look Rotation).

The projection matrix

A perspective projection with vertical field of view fov\text{fov}, aspect ratio aa and near/far planes n,fn, f (OpenGL convention) is

P=[g/a0000g0000f+nn−f2fnn−f00−10]g=1tan⁡(fov/2),n,f=near and far plane distancesP = \begin{bmatrix} g/a & 0 & 0 & 0 \\ 0 & g & 0 & 0 \\ 0 & 0 & \frac{f+n}{n-f} & \frac{2fn}{n-f} \\ 0 & 0 & -1 & 0 \end{bmatrix} \qquad g = \frac{1}{\tan(\text{fov}/2)}, \quad n, f = \text{near and far plane distances}

The last row copies −z-z into ww. After the perspective divide by ww, xx and yy are divided by the depth: far objects shrink. This is the same idea as Perspective Rendering, packed into a matrix so the GPU can treat it like any other transform. The third row maps depth so that z=−nearz = -\text{near} goes to −1-1 and z=−farz = -\text{far} to +1+1 in NDC.

python · try it yourself
import numpy as np

def look_at(eye, target, up=(0, 1, 0)):
    eye, target, up = map(np.asarray, (eye, target, up))
    b = eye - target; b = b / np.linalg.norm(b)            # backward
    r = np.cross(up, b); r = r / np.linalg.norm(r)          # right
    u = np.cross(b, r)                                      # true up
    V = np.eye(4); V[:3, :3] = np.vstack([r, u, b])          # R^T: rows are the basis
    V[:3, 3] = -V[:3, :3] @ eye
    return V

def perspective(fov_deg, aspect, near, far):
    f = 1 / np.tan(np.radians(fov_deg) / 2)
    return np.array([[f / aspect, 0, 0, 0], [0, f, 0, 0],
                     [0, 0, (far + near) / (near - far), 2 * far * near / (near - far)],
                     [0, 0, -1, 0]])

V = look_at(eye=(0, 2, 6), target=(0, 0, 0))
P = perspective(60, 16 / 9, 0.1, 100)
W, H = 1920, 1080
for name, p in [("origin", (0, 0, 0)), ("near corner", (1, 0, 1)), ("far corner", (1, 0, -1))]:
    clip = P @ V @ np.array([*p, 1.0])
    ndc = clip[:3] / clip[3]
    px = ((ndc[0] + 1) / 2 * W, (1 - ndc[1]) / 2 * H)       # flip y: pixel rows go down
    print(f"{name:11s} w={clip[3]:.3f}  ndc=({ndc[0]:+.3f}, {ndc[1]:+.3f}, {ndc[2]:+.4f})  "
          f"pixel=({px[0]:.0f}, {px[1]:.0f})")
origin      w=6.325  ndc=(+0.000, +0.000, +0.9703)  pixel=(960, 540)
near corner w=5.376  ndc=(+0.181, -0.102, +0.9648)  pixel=(1134, 595)
far corner  w=7.273  ndc=(+0.134, +0.075, +0.9745)  pixel=(1089, 499)

The camera looks at the origin, so it lands in the middle of the screen. The two corners are both at x=1x = 1, but the one closer to the camera (smaller ww) is drawn further from the centre. Notice how close the NDC depths are to 1: depth precision is concentrated near the near plane, which is why a tiny near value causes z-fighting.

Note: Conventions differ. Direct3D, Vulkan and WebGPU map depth to [0,1][0, 1] instead of [−1,1][-1, 1], Vulkan flips yy, and some engines use row vectors (v⋅M\mathbf{v} \cdot M, so the order is reversed and the matrices are transposed). The linear algebra is identical; only the bookkeeping changes.

Normals need the inverse transpose

A surface normal n\mathbf{n} must stay perpendicular to tangent vectors t\mathbf{t}. If tangents transform by the 3×33 \times 3 part AA of MM, then normals must transform by (A−1)T(A^{-1})^T, because (A−1)Tn⋅At=nTA−1At=n⋅t=0(A^{-1})^T\mathbf{n} \cdot A\mathbf{t} = \mathbf{n}^TA^{-1}A\mathbf{t} = \mathbf{n} \cdot \mathbf{t} = 0. For rotations (A−1)T=A(A^{-1})^T = A, but non-uniform scaling breaks normals if you skip this.

python · try it yourself
import numpy as np

A = np.diag([3.0, 1.0, 1.0])                 # stretch x by 3
t = np.array([1.0, -1.0, 0.0])               # tangent of the plane x + y = 0
n = np.array([1.0, 1.0, 0.0])                # its normal
print("naive  A n   . A t =", float((A @ n) @ (A @ t)))
N = np.linalg.inv(A).T
print("correct N n  . A t =", float((N @ n) @ (A @ t)))
naive  A n   . A t = 8.0
correct N n  . A t = 0.0

In software

  • Vertex shaders compute gl_Position = proj * view * model * vec4(pos, 1.0); engines precompute P⋅VP \cdot V once per frame and MM once per object.
  • Scene graphs multiply parent and child model matrices (Hierarchy); Spaces and Screen Space cover the conversions engines expose.
  • Picking runs the pipeline backwards with (P⋅V)−1(P \cdot V)^{-1} to turn a mouse click into a ray (Screen to World).
  • CSS transform: matrix3d(...) and Three.js Matrix4 are these same 4×44 \times 4 matrices (column-major in memory).

Exercises

Exercise 1: Translate a direction

What does translate⁡(4,5,6)\operatorname{translate}(4, 5, 6) do to the point (1,1,1)(1, 1, 1) and to the direction (1,1,1)(1, 1, 1)?

Answer

The point becomes (5,6,7)(5, 6, 7); the direction stays (1,1,1)(1, 1, 1).

Solution

Points have w=1w = 1 and pick up the translation column; directions have w=0w = 0 and do not.

Exercise 2: Order of operations

Compute translate⁡(0,3,0)⋅scale⁡(2,2,2)\operatorname{translate}(0, 3, 0) \cdot \operatorname{scale}(2, 2, 2) and scale⁡(2,2,2)⋅translate⁡(0,3,0)\operatorname{scale}(2, 2, 2) \cdot \operatorname{translate}(0, 3, 0) applied to the origin.

Answer

(0,3,0)(0, 3, 0) and (0,6,0)(0, 6, 0).

Solution

In the first product the scale acts first (the origin stays put) and then the translation moves it to (0,3,0)(0, 3, 0). In the second the origin is translated to (0,3,0)(0, 3, 0) and then scaled to (0,6,0)(0, 6, 0).

Exercise 3: The perspective divide

A point has clip coordinates (2,−1,3,4)(2, -1, 3, 4). What are its NDC coordinates, and is it inside the view volume?

Answer

(0.5,−0.25,0.75)(0.5, -0.25, 0.75): inside, since all three lie in [−1,1][-1, 1].

Solution

Divide x,y,zx, y, z by w=4w = 4.

Exercise 4: View matrix inverse (code)

Check that look_at(eye=(3, 4, 5), target=(0, 0, 0)) maps the eye to the origin and the target onto the negative zz axis, at distance ∣eye∣\lvert \text{eye} \rvert.

Answer

Eye↦(0,0,0)\text{Eye} \mapsto (0, 0, 0); target↦(0,0,−50)≈(0,0,−7.0711)\text{target} \mapsto (0, 0, -\sqrt{50}) \approx (0, 0, -7.0711).

Solution

The camera looks down its −z-z axis, and the distance from eye to target is 9+16+25=50\sqrt{9 + 16 + 25} = \sqrt{50}.

python · try it yourself
import numpy as np
def look_at(eye, target, up=(0, 1, 0)):
    eye, target, up = map(np.asarray, (eye, target, up))
    b = (eye - target) / np.linalg.norm(eye - target)
    r = np.cross(up, b); r = r / np.linalg.norm(r); u = np.cross(b, r)
    V = np.eye(4); V[:3, :3] = np.vstack([r, u, b]); V[:3, 3] = -V[:3, :3] @ eye
    return V
V = look_at((3, 4, 5), (0, 0, 0))
print(np.round(V @ [3, 4, 5, 1], 4) + 0, np.round(V @ [0, 0, 0, 1], 4) + 0)
[0. 0. 0. 1.] [ 0.      0.     -7.0711  1.    ]

Test yourself

Why do 3D engines use 4×44 \times 4 matrices for 3D points?

  1. GPUs cannot multiply 3×33 \times 3 matrices
  2. So that translation (and perspective) become matrix multiplications
  3. To store colour in the fourth component
  4. To make matrices invertible

In clip=P⋅V⋅M⋅v\text{clip} = P \cdot V \cdot M \cdot \mathbf{v}, which transform is applied to v\mathbf{v} first?

  1. PP
  2. VV
  3. MM
  4. They commute

How should normals be transformed when the model matrix has a non-uniform scale?

  1. By the model matrix
  2. By the inverse transpose of its 3×33 \times 3 part
  3. By the projection matrix
  4. They should not be transformed