A vertex of the ship does not have "its" coordinates: it has many. Relative to the center of the ship it is \((1, 0, 0)\); relative to the lighthouse, \((10.4, 3, 2.8)\); relative to the camera, yet another triple; and at the end of the road it will be a pixel on the screen. Drawing a scene consists of taking each vertex from one coordinate system to the next, and each step is a matrix. In this lesson we present the complete chain of coordinate spaces of the graphics pipeline and develop its first three links in depth: local space, world space and camera space. We will build the view matrix—the one that expresses the scene relative to whoever is looking at it—the look-at function that manufactures it from "where I am and where I am looking", and three kinds of camera that every game needs: orbit, first-person and follow.
The code assumes that the functions from the previous modules (affine_matrix, model_matrix, transform_point, transform_direction, transform_points, rigid_inverse, is_rigid, orthonormal_basis, spherical_to_cartesian, euler_to_matrix...), the mesh octahedron_mesh() from the previous lesson and the scene data are already defined: ship, lamp, camera, ship_orientation, ship_world and hull_model.
The chain of coordinate spaces
Every vertex of a mesh travels this path before becoming a point in the image:
graph LR
A["Local space<br/>(object)"] -- "model matrix" --> B["World space"]
B -- "view matrix" --> C["View space<br/>(camera)"]
C -- "projection matrix" --> D["Clip space"]
D -- "division by w" --> E["NDC"]
E -- "viewport transformation" --> F["Screen<br/>(pixels)"]
| Space | Origin | Measured in | What it is for |
|---|---|---|---|
| Local (object) | The center or pivot of the object | Model units | Defining the mesh only once, regardless of where it is placed |
| World | A fixed point of the scene (the base of the lighthouse) | Meters | Placing all the objects relative to one another; physics, game logic |
| View (camera) | The eye of the camera | Meters | Describing the scene as the camera sees it: right, up, ahead |
| Clip | — | Homogeneous coordinates \((x, y, z, w)\) | Deciding what falls inside the field of view |
| NDC (normalized device coordinates) | The center of the image | Unitless: a cube from \(-1\) to \(1\) | Making the result independent of the window size |
| Screen | A corner of the window | Pixels | Painting |
In this lesson we cover the first two stretches. The third, the projection, and the division by \(w\) are the subject of "Projections and Views"; clipping and the step to pixels belong to "From Clip Space to the Screen: Viewport, Rasterization and Z-buffer".
The first three spaces have something in common: we go from one to another with affine transformations, which preserve lines, parallelism and—if there is no scale—distances and angles. They are three descriptions of the same three-dimensional scene. From the projection onward things change: space is distorted to produce perspective.
From local space to the world: the model matrix
We already built this stretch in "Composition of Transformations": the model matrix \(M = T,R,S\) scales, orients and places the object. For the ship's hull, \(M_{\text{hull}} = T(8, 3, 6),N,S(4, 1, 2)\), which takes the local vertex \((1, 0, 0)\) of the octahedron to the wing tip, \((10.4, 3, 2.8)\).
With the passive reading from "Inverse Transformations and Change of Coordinate System", the same matrix is described like this: it converts local coordinates into world coordinates. Its first three columns are the object's axes, and the fourth is its origin, all of them as seen from the world. Each object in the scene has its own model matrix; if it is part of a hierarchy (the antenna, a child of the ship), its matrix is the product of the matrices of the whole chain of parents.
The camera is just another object
The camera is not special: it is an object in the scene, with its position, its orientation and, therefore, its world matrix. The only thing that sets it apart is a convention about what its local axes mean:
| Local axis of the camera | Meaning |
|---|---|
| \(+X\) | Toward the right of the image |
| \(+Y\) | Up in the image |
| \(-Z\) | Forward: the direction it is looking in |
| \(+Z\) | Backward, toward the viewer |
Why does the camera look toward \(-Z\) and not toward \(+Z\)? It is a consequence of wanting three things at once: that in the image \(X\) grows to the right, that \(Y\) grows upward (like the axes on paper) and that the system is right-handed. Under those conditions, \(Z = X \times Y\) comes out of the screen toward the viewer, and what the camera sees lies on the opposite side. There is no more mystery to it: left-handed systems (Direct3D's, for example) make the camera look toward \(+Z\).
Until now the camera of "Stellar Lighthouse" has been at \((0, 5, 20)\) without any rotation: its world matrix is \(T(0, 5, 20)\), its axes coincide with those of the world and it looks toward \(-Z\), in the direction of the lighthouse.
The view matrix: the inverse of the camera
The camera's world matrix, \(C\), converts camera coordinates into world coordinates. To draw we need the opposite: given a point in the world, to know where it is relative to the camera. That conversion is done by the inverse, and it has a name of its own:
\[ V = C^{-1} \qquad\qquad \mathbf{p}{\text{view}} = V,\mathbf{p}{\text{world}} \]
\(V\) is the view matrix. Let us recall the two readings, active and passive, that we gave in Module 2:
- Passive. Nobody moves; \(V\) merely translates world coordinates into camera coordinates.
- Active. \(V\) moves the entire world so that the camera ends up at the origin, looking toward \(-Z\). "Moving the camera 2 m to the right" and "moving the world 2 m to the left" produce the same image.
Since a camera neither scales nor distorts, \(C = [R \mid \mathbf{t}]\) is a rigid transformation, and its inverse is the cheap, exact one we already know:
\[ V = \begin{pmatrix} R^T & -R^T\mathbf{t} \ \mathbf{0}^T & 1 \end{pmatrix} \]
import numpy as np
def view_matrix_from_world(camera_world):
"""View matrix from the (rigid) world matrix of the camera."""
return rigid_inverse(camera_world)
initial_view = view_matrix_from_world(translation_matrix(0.0, 5.0, 20.0))
print(initial_view)
print(transform_point(initial_view, ship), transform_point(initial_view, lamp))The initial view is \(T(0, -5, -20)\): the world shifts the opposite way to the camera. The ship ends up at \((8, -2, -14)\), the result we obtained in Module 2: 8 m to the right, 2 m below the line of sight and 14 m ahead. View coordinates are that easy to read: \(x\) = right, \(y\) = up, \(-z\) = depth. The lighthouse lamp is exactly on the vertical axis of the image, 7 m above the center and 20 m away.
The camera basis: building look-at
Giving the orientation of a camera by means of a rotation matrix is not very practical. The natural thing is to say "I am here and I am looking there". The look-at function builds the view matrix from three pieces of data:
- the eye \(\mathbf{e}\): the position of the camera;
- the target \(\mathbf{o}\): the point it is looking at;
- an approximate up vector \(\mathbf{a}\): almost always \((0, 1, 0)\), so that the horizon stays horizontal.
Step 1: the camera's three axes
We have to manufacture an orthonormal basis: right, up and forward. It is the same problem we solved with orthonormal_basis in "Dot Product and Cross Product", and with the same tools.
Forward. The viewing direction goes from the eye to the target, normalized:
\[ \hat{\mathbf{f}} = \frac{\mathbf{o} - \mathbf{e}}{\lVert \mathbf{o} - \mathbf{e} \rVert} \]
Right. It must be perpendicular to the viewing direction and also to the vertical (so that the camera is not tilted sideways). A vector perpendicular to two others is their cross product:
\[ \hat{\mathbf{d}} = \frac{\hat{\mathbf{f}} \times \mathbf{a}}{\lVert \hat{\mathbf{f}} \times \mathbf{a} \rVert} \]
The order matters. With the right-hand rule: if you are looking north and the thumb must point to your right (east), the fingers have to curl from "forward" toward "up". The reverse order would give the left. We have to normalize because \(\hat{\mathbf{f}}\) and \(\mathbf{a}\) are not, in general, perpendicular, and their cross product has a length of less than 1.
True up. The vector \(\mathbf{a}\) was only a hint: if the camera looks down, its "up" is tilted forward. The true one is the vector perpendicular to the other two:
\[ \hat{\mathbf{u}} = \hat{\mathbf{d}} \times \hat{\mathbf{f}} \]
It is already a unit vector, being the cross product of two perpendicular unit vectors.
Step 2: from the axes to the matrix
The camera's local axes, seen from the world, are \(+X = \hat{\mathbf{d}}\), \(+Y = \hat{\mathbf{u}}\) and \(+Z = -\hat{\mathbf{f}}\) (remember: it looks toward \(-Z\)). Its world matrix has those axes as columns and the eye as its origin:
\[ C = \begin{pmatrix} \hat{\mathbf{d}} & \hat{\mathbf{u}} & -\hat{\mathbf{f}} & \mathbf{e} \ 0 & 0 & 0 & 1 \end{pmatrix} \]
The view matrix is its rigid inverse: the rotation block is transposed—the axes become the rows—and the translation is \(-R^T\mathbf{e}\), whose components are dot products of each axis with the eye:
\[ V = \begin{pmatrix} d_x & d_y & d_z & -\hat{\mathbf{d}} \cdot \mathbf{e} \\ u_x & u_y & u_z & -\hat{\mathbf{u}} \cdot \mathbf{e} \\ -f_x & -f_y & -f_z & \hat{\mathbf{f}} \cdot \mathbf{e} \\ 0 & 0 & 0 & 1 \end{pmatrix} \]
The matrix is easier to understand when applied to a point \(\mathbf{p}\). The result is:
\[ V,\mathbf{p} = \big(\hat{\mathbf{d}} \cdot (\mathbf{p} - \mathbf{e}),\ \ \hat{\mathbf{u}} \cdot (\mathbf{p} - \mathbf{e}),\ \ -\hat{\mathbf{f}} \cdot (\mathbf{p} - \mathbf{e})\big) \]
In other words: we take the displacement from the eye to the point and project it onto each axis of the camera. How far it lies to the right, how far up and how far ahead (with the sign changed). Three dot products; that is all a view matrix does.
def look_at_matrix(eye, target, up=(0.0, 1.0, 0.0)):
"""4x4 view matrix of a camera located at `eye` that looks toward `target`."""
eye = np.asarray(eye, dtype=float)
forward = normalize(np.asarray(target, dtype=float) - eye)
right = normalize(cross_product(forward, up))
true_up = cross_product(right, forward)
view = np.eye(4)
view[0, :3] = right # the ROWS are the camera's axes
view[1, :3] = true_up
view[2, :3] = -forward
view[:3, 3] = -view[:3, :3] @ eye # -R^T e
return view
def camera_position(view):
"""Position of the eye in the world, recovered from a view matrix."""
return -view[:3, :3].T @ view[:3, 3]camera_position goes the other way: since the translation of the view is \(\mathbf{t}_V = -R^T\mathbf{e}\), the eye is \(\mathbf{e} = -R,\mathbf{t}_V\). We will need it when, for lighting, we have to know where the observer is.
Example by hand: the camera looks at the ship
The camera is still at \(\mathbf{e} = (0, 5, 20)\), but now it turns to frame the ship, \(\mathbf{o} = (8, 3, 6)\).
Forward. \(\mathbf{o} - \mathbf{e} = (8, -2, -14)\), of norm \(\sqrt{64 + 4 + 196} = \sqrt{264} \approx 16.248\):
\[ \hat{\mathbf{f}} \approx (0.4924,\ -0.1231,\ -0.8616) \]
Right. It can be computed with the unnormalized vector, since we normalize afterward:
\[ (8, -2, -14) \times (0, 1, 0) = \big((-2) \cdot 0 - (-14) \cdot 1,\ \ (-14) \cdot 0 - 8 \cdot 0,\ \ 8 \cdot 1 - (-2) \cdot 0\big) = (14, 0, 8) \]
Its norm is \(\sqrt{260} \approx 16.125\), and \(\hat{\mathbf{d}} \approx (0.8682,\ 0,\ 0.4961)\). The \(y\) component is zero: the camera's right is horizontal, which is exactly what the "up" vector guarantees.
Up. \(\hat{\mathbf{u}} = \hat{\mathbf{d}} \times \hat{\mathbf{f}}\):
\[ \big(0 \cdot (-0.8616) - 0.4961 \cdot (-0.1231),\ \ 0.4961 \cdot 0.4924 - 0.8682 \cdot (-0.8616),\ \ 0.8682 \cdot (-0.1231) - 0\big) \approx (0.0611,\ 0.9924,\ -0.1069) \]
Almost vertical, slightly tilted: the camera is looking a little downward.
Translation. \(-\hat{\mathbf{d}} \cdot \mathbf{e} = -(0.4961 \cdot 20) = -9.923\); \(-\hat{\mathbf{u}} \cdot \mathbf{e} = -(0.9924 \cdot 5 - 0.1069 \cdot 20) = -2.824\); \(\hat{\mathbf{f}} \cdot \mathbf{e} = -0.1231 \cdot 5 - 0.8616 \cdot 20 = -17.848\).
\[ V \approx \begin{pmatrix} 0.8682 & 0 & 0.4961 & -9.923 \\ 0.0611 & 0.9924 & -0.1069 & -2.824 \\ -0.4924 & 0.1231 & 0.8616 & -17.848 \\ 0 & 0 & 0 & 1 \end{pmatrix} \]
Check. The target must end up straight ahead of the camera, at \((0, 0, -\text{distance})\). For the third coordinate: \(-0.4924 \cdot 8 + 0.1231 \cdot 3 + 0.8616 \cdot 6 - 17.848 = -3.939 + 0.369 + 5.170 - 17.848 = -16.248\) ✓.
view = look_at_matrix(camera, ship)
print(np.round(view, 4) + 0.0)
print(np.round(transform_point(view, ship), 4) + 0.0) # the target
print(np.round(transform_point(view, lamp), 4)) # the lighthouse lamp
print(is_rigid(view), np.round(camera_position(view), 6) + 0.0)
# The same camera, built as an object and then inverted
camera_world = affine_matrix(orthonormal_basis(camera - ship), camera)
print(np.allclose(view_matrix_from_world(camera_world), view))[[ 0.8682 0. 0.4961 -9.9228] [ 0.0611 0.9924 -0.1069 -2.8245] [ -0.4924 0.1231 0.8616 -17.8483] [ 0. 0. 0. 1. ]] [ 0. 0. -16.2481] [ -9.9228 9.0842 -16.3712] True [ 0. 5. 20.] True
- The ship ends up at \((0, 0, -16.25)\): centered in the image, 16.25 m away.
- The lighthouse lamp ends up 9.9 m to the left of and 9.1 m above the center of the image, at a depth of 16.4 m.
- The matrix is rigid, and the position of the eye can be recovered from it.
The last two lines come full circle with Module 3. orthonormal_basis(forward) returned a matrix with columns right, up and forward for an object whose "forward" is its \(+Z\). Since the camera's \(+Z\) points backward, we pass it the vector from the target to the eye, \(\mathbf{e} - \mathbf{o}\). The result is the camera's world matrix, and its inverse coincides with the matrix from look_at_matrix. Look-at is not a new formula: it is orthonormal_basis plus rigid_inverse.
The degenerate case: looking straight up or down
The construction fails in one case: when the viewing direction is parallel to the up vector. Then \(\hat{\mathbf{f}} \times \mathbf{a} = \mathbf{0}\) and there is no "right" to normalize. Geometrically it makes sense: if you look straight down at your feet, the hint "the vertical goes up in the image" says nothing, because the vertical has turned into a point. Any rotation about the line of sight is equally valid.
It is the same phenomenon as the gimbal lock of "Euler Angles and Gimbal Lock", seen from another angle. Close to the degenerate case, moreover, the cross product is very small and the camera swings abruptly with minimal changes.
There are two usual solutions:
- Avoid it: prevent the camera from reaching the vertical (limit the elevation to ±89°).
- Change the hint: for an overhead view, choose a horizontal direction as "up". With \(\mathbf{a} = (0, 0, -1)\), the world's \(-Z\) axis points up in the image, like north on a map.
try:
look_at_matrix([0.0, 40.0, 0.0], [0.0, 0.0, 0.0])
except ValueError as error:
print("Error:", error)
overhead = look_at_matrix([0.0, 40.0, 0.0], [0.0, 0.0, 0.0], up=(0.0, 0.0, -1.0))
print(np.round(overhead, 4) + 0.0)
print(transform_point(overhead, ship))Error: cannot normalize the zero vector [[ 1. 0. 0. 0.] [ 0. 0. -1. 0.] [ 0. 1. 0. -40.] [ 0. 0. 0. 1.]] [ 8. -6. -37.]
Our normalize warns of the problem instead of returning a matrix full of nan. The overhead camera, 40 m above the lighthouse, sees the ship at \((8, -6, -37)\): 8 m to the right, 6 m "down" in the image (its world \(z = 6\)) and at a depth of 37 m (\(40 - 3\)). It is the top-down view we have been using since Module 1, turned into a camera.
Orbit camera
An orbit camera revolves around a target, always looking at it, at a fixed distance. It is the camera of 3D editors and of object inspection screens. Its parameters are those of the spherical coordinates from "Coordinates and Planes": a radius, an azimuth (rotation about the Y axis, measured from \(+Z\) toward \(+X\)) and an elevation above the horizontal plane.
The recipe combines two pieces we already have:
- Position of the eye: \(\mathbf{e} = \mathbf{o} + \text{spherical}(r, \text{azimuth}, \text{elevation})\).
- Orientation: look-at from \(\mathbf{e}\) toward \(\mathbf{o}\).
def orbit_camera(target, radius, azimuth, elevation):
"""View matrix of a camera that orbits around `target` and looks at it."""
target = np.asarray(target, dtype=float)
eye = target + spherical_to_cartesian(radius, azimuth, elevation)
return look_at_matrix(eye, target)
orbital = orbit_camera(ship, 15.0, np.radians(30.0), np.radians(20.0))
print(np.round(camera_position(orbital), 3))
print(np.round(transform_point(orbital, ship), 4) + 0.0)
for degrees in (0, 90, 180, 270):
v = orbit_camera(ship, 15.0, np.radians(degrees), np.radians(20.0))
print(degrees, np.round(camera_position(v), 3) + 0.0,
np.round(transform_point(v, lamp), 3) + 0.0)[15.048 8.13 18.207] [ 0. 0. -15.] 0 [ 8. 8.13 20.095] [ -8. 10.509 -17.56 ] 90 [22.095 8.13 6. ] [ 6. 11.193 -19.439] 180 [ 8. 8.13 -8.095] [ 8. 6.405 -6.284] 270 [-6.095 8.13 6. ] [-6. 5.721 -4.404]
The first position, \((15.05, 8.13, 18.21)\), is the one we computed in Module 3; now, in addition, the camera looks at the ship, which always stays at \((0, 0, -15)\). The last four lines go once around: the ship does not move from the center, while the lighthouse lamp parades across the background, from left (\(x = -8\)) to right (\(x = 6, 8\)) and back to the left, and from a depth of 17.6 m to just 4.4 m when the camera passes between the ship and the lighthouse.
To drive it with the mouse, it is enough to add the horizontal movement to the azimuth and the vertical movement to the elevation, and to use the wheel for the radius. The elevation must be limited (for example, to ±89°): at ±90° the camera would look straight up or down, the degenerate case of the previous section.
First-person camera
In a first-person camera there is no target: the player decides directly where to look. The camera is described as the object it is, with a position and two of the angles we defined in "Euler Angles and Gimbal Lock": yaw (turning the head from side to side, about Y) and pitch (raising or lowering it, about its X axis). The roll is left at zero so that the horizon does not tilt.
\[ C = T(\mathbf{e});R_y(\text{yaw});R_x(\text{pitch}) \qquad\qquad V = C^{-1} \]
The viewing direction is the image of \((0, 0, -1)\) under that rotation:
\[ \hat{\mathbf{f}} = \big({-\sin\psi,\cos\theta},\ \ \sin\theta,\ \ {-\cos\psi,\cos\theta}\big) \]
The signs have to be kept in mind, because the camera looks toward \(-Z\) and the ship pointed its nose toward \(+Z\):
| Angle | Positive sign on the ship (nose \(+Z\)) | Positive sign on the camera (looks toward \(-Z\)) |
|---|---|---|
| Yaw \(\psi\) | The nose goes from \(+Z\) toward \(+X\) | The gaze goes from \(-Z\) toward \(-X\): it turns left |
| Pitch \(\theta\) | The nose goes down | The gaze goes up |
The rotation is the same; what changes is which end of the Z axis we regard as "forward". Consequently, moving the mouse to the right must subtract yaw.
def first_person_view(position, yaw, pitch):
"""View matrix of a free camera: world = T(position) R_y(yaw) R_x(pitch)."""
limit = np.radians(89.0)
pitch = float(np.clip(pitch, -limit, limit))
world = affine_matrix(euler_to_matrix(yaw, pitch, 0.0), position)
return view_matrix_from_world(world)
def view_direction(view):
"""Direction (in the world) the camera is looking in: the third row, with its sign changed."""
return -view[2, :3]
print(np.allclose(first_person_view(camera, 0.0, 0.0), initial_view))
print(np.round(view_direction(first_person_view(camera, np.radians(90.0), 0.0)), 4) + 0.0)
print(np.round(view_direction(first_person_view(camera, np.radians(-30.0), np.radians(10.0))), 4))
# Which angles are needed to look at the ship?
f = direction_to(camera, ship)
yaw, pitch = np.arctan2(-f[0], -f[2]), np.arcsin(f[1])
print(round(np.degrees(yaw), 2), round(np.degrees(pitch), 2))
print(np.allclose(first_person_view(camera, yaw, pitch), view))With zero angles we recover the initial view; with 90° of yaw the camera looks toward \(-X\); with \(-30°\) of yaw and \(10°\) of pitch it looks to the right and upward. The last lines solve the formula for \(\hat{\mathbf{f}}\) for the angles: to look at the ship we have to turn 29.74° to the right and lower our gaze by 7.07°, and the resulting matrix is identical to the look-at one. They are two ways of parameterizing the same thing: look-at is convenient when the target is known; yaw and pitch, when the player turns freely.
The ±89° limit on the pitch prevents the camera from flipping over and keeps it away from the lock. To move "where I am looking", a multiple of view_direction is added to the position; for a sideways move, a multiple of the first row of the view, which is the "right" axis.
Third-person follow camera
The camera of "Stellar Lighthouse" follows the ship from behind. The idea is to treat it as a child of the ship in the scene graph: its position is given in the ship's local coordinates and converted to the world with the ship's matrix. When the ship moves or turns, the camera goes along with it with no further calculation.
The ship's nose is its local \(+Z\), so "behind and a little above" is, for example, the local point \((0, 2, -8)\). So that the ship does not hide what lies ahead of it, the camera does not aim at its center but at a point farther forward, such as the local \((0, 0, 4)\). And as the "up" vector we use the ship's own, so that the camera banks with it in the turns.
- Eye: \((8, 3, 6) + 2,\mathbf{n}_2 - 8,\mathbf{n}_3 = (8, 3, 6) + (0, 2, 0) - (6.4, 0, 4.8) = (1.6, 5, 1.2)\).
- Aim point: \((8, 3, 6) + 4,\mathbf{n}_3 = (11.2, 3, 8.4)\).
def follow_camera(object_world, eye_local, aim_point_local=(0.0, 0.0, 0.0)):
"""View of a camera anchored to an object: eye and aim point in local coordinates."""
eye = transform_point(object_world, eye_local)
target = transform_point(object_world, aim_point_local)
up = transform_direction(object_world, [0.0, 1.0, 0.0])
return look_at_matrix(eye, target, up)
follow = follow_camera(ship_world, [0.0, 2.0, -8.0], [0.0, 0.0, 4.0])
print(np.round(camera_position(follow), 4))
for name, p in (("ship", ship), ("nose", [9.6, 3.0, 7.2]),
("right wing", [10.4, 3.0, 2.8]), ("lamp", lamp)):
print(name, np.round(transform_point(follow, p), 3) + 0.0)[1.6 5. 1.2] ship [ 0. -0.658 -8.22 ] nose [ 0. -0.329 -10.193] right wing [-4. -0.658 -8.22 ] lamp [0. 6.576 3.124]
- The ship appears horizontally centered, somewhat below the center of the image and 8.2 m away; the nose, 2 m farther.
- The lighthouse lamp has a positive \(z\): it is behind the camera and will not be seen. The ship is moving away from the lighthouse, as we knew.
- The wing tip we have called "right" (the ship's local \(+X\)) appears 4 m to the left. It is not a mistake: in a right-handed system with Y up, someone looking toward \(+Z\) has the \(+X\) axis on their left; we already warned in Module 4 that "right" was an inherited name. The camera, which looks toward \(-Z\), does have its \(+X\) on the right.
A rigidly anchored camera feels abrupt: it instantly reproduces every jolt of the ship. Games smooth it out by making the camera chase its ideal position instead of jumping to it: lerp or move_toward for the position and quaternion_slerp or rotate_toward for the orientation, the tools from "Interpolating Rotations: Lerp, Nlerp and Slerp".
The model-view matrix
A local vertex reaches view space with two multiplications: \(\mathbf{p}{\text{view}} = V,(M,\mathbf{p}{\text{local}})\). Since the matrix product is associative, they can be merged into a single matrix, the model-view matrix:
\[ MV = V,M \qquad\qquad \mathbf{p}{\text{view}} = MV,\mathbf{p}{\text{local}} \]
It is the matrix between_systems(model, camera_world) from Module 2, \(C^{-1} M\), under another name. The advantages are the usual ones: it is computed once per object and frame, and after that each vertex costs a single multiplication, without going through the world. There is one view matrix for the whole scene, and one model-view matrix per object.
print(initial_view @ ship_world)
octahedron = octahedron_mesh()
print(transform_points(initial_view @ hull_model, octahedron["vertices"]))
print(np.round(transform_points(view @ hull_model, octahedron["vertices"]), 3))[[ 0.6 0. 0.8 8. ] [ 0. 1. 0. -2. ] [ -0.8 0. 0.6 -14. ] [ 0. 0. 0. 1. ]] [[ 10.4 -2. -17.2] [ 5.6 -2. -10.8] [ 8. -1. -14. ] [ 8. -3. -14. ] [ 9.6 -2. -12.8] [ 6.4 -2. -15.2]] [[ 0.496 0.489 -20.187] [ -0.496 -0.489 -12.309] [ 0. 0.992 -16.125] [ 0. -0.992 -16.371] [ 1.985 -0.031 -16.002] [ -1.985 0.031 -16.494]]
The first matrix is the one we called ship_to_camera in Module 2. The next two blocks are the six vertices of the hull in view space, for two cameras located at the same point:
- With the initial view (no rotation), the ship spans from \(x = 5.6\) to \(x = 10.4\): it is shifted toward the right of the image.
- With the look-at view, the vertices are spread symmetrically around the line of sight. And something interesting shows up: the wing tips (the first two rows) barely move away from the center, \(\pm 0.5\) m, but they lie at very different depths, 20.2 m and 12.3 m; the nose and the tail, by contrast, are \(\pm 2\) m apart at a similar depth. From here the ship is seen side-on, with one wing pointing almost directly at the camera, just as we deduced in an exercise in Module 2.
Those view coordinates are the raw material of the projection: in the next lesson, the depth \(-z\) of each vertex will decide how much it shrinks in the image.
Common Mistakes and Tips
- Using the camera's world matrix as the view matrix. The world matrix goes from the camera to the world; the view matrix is its inverse. If moving the camera to the right makes the scene go to the right as well, this is why.
- Placing the camera's axes in columns in the view matrix. In the world matrix they go in columns; in the view matrix, in rows (it is the transpose).
- Using \(-\mathbf{e}\) as the translation of the view. It is \(-R^T\mathbf{e}\): the eye projected onto the camera's axes. It only coincides with \(-\mathbf{e}\) if the camera is not rotated.
- Forgetting that the camera looks toward \(-Z\). What lies ahead has a negative view \(z\). A positive \(z\) means "behind the camera".
- Getting the order of the cross product wrong. \(\hat{\mathbf{f}} \times \mathbf{a}\) gives the right; \(\mathbf{a} \times \hat{\mathbf{f}}\), the left, and the image comes out mirrored.
- Not normalizing the right vector. \(\hat{\mathbf{f}} \times \mathbf{a}\) is a unit vector only if the camera looks horizontally. Without normalizing, the matrix stops being rigid and the image is distorted when looking up or down.
- Passing as "up" a vector parallel to the line of sight. This is the degenerate case. Limit the elevation or switch to a different up vector for overhead views.
- Confusing target with direction.
look_at_matrixexpects a point to look at. If what you have is a direction \(\mathbf{d}\), the target iseye + d. - Tip. To debug a camera, transform a known point: the target must give \((0, 0, -\text{distance})\), and
camera_positionmust return the eye.
Exercises
Exercise 1. A surveillance camera is installed on beacon Alpha, \((12, 7, 4)\), aimed at the ship, \((8, 3, 6)\).
a) Compute by hand the vectors \(\hat{\mathbf{f}}\), \(\hat{\mathbf{d}}\) and \(\hat{\mathbf{u}}\). b) Write the view matrix. c) Check that the ship ends up at \((0, 0, -6)\).
Exercise 2. To get a side view of the scene, a camera is placed at \((20, 5, 0)\) looking toward the point \((0, 5, 0)\) on the lighthouse tower.
a) Without doing any calculations, reason out what the right, up and forward axes of this camera are. b) Write its view matrix. c) Where does this camera see the ship and the lighthouse lamp?
Exercise 3. The ship carries a cockpit camera located at its local point \((0, 0.5, 1)\), which looks forward, toward the local point \((0, 0.5, 10)\). With follow_camera, obtain its view matrix and compute where it sees beacon Alpha, \((12, 7, 4)\), and the base of the lighthouse, \((0, 0, 0)\). Which of the two can appear in the image?
Solutions
Solution 1.
a) \(\mathbf{o} - \mathbf{e} = (-4, -4, 2)\), of norm 6: \(\hat{\mathbf{f}} = \left(-\tfrac{2}{3}, -\tfrac{2}{3}, \tfrac{1}{3}\right)\).
\((-4, -4, 2) \times (0, 1, 0) = \big((-4) \cdot 0 - 2 \cdot 1,\ \ 2 \cdot 0 - (-4) \cdot 0,\ \ (-4) \cdot 1 - 0\big) = (-2, 0, -4)\), of norm \(\sqrt{20}\): \(\hat{\mathbf{d}} = (-1, 0, -2)/\sqrt{5} \approx (-0.4472,\ 0,\ -0.8944)\).
\(\hat{\mathbf{u}} = \hat{\mathbf{d}} \times \hat{\mathbf{f}} = \dfrac{(-1, 0, -2) \times (-2, -2, 1)}{3\sqrt{5}} = \dfrac{(-4,\ 5,\ 2)}{3\sqrt{5}} \approx (-0.5963,\ 0.7454,\ 0.2981)\).
b) Translation: \(-\hat{\mathbf{d}} \cdot \mathbf{e} = \dfrac{12 + 8}{\sqrt{5}} = 8.944\); \(-\hat{\mathbf{u}} \cdot \mathbf{e} = -\dfrac{-48 + 35 + 8}{3\sqrt{5}} = 0.745\); \(\hat{\mathbf{f}} \cdot \mathbf{e} = \dfrac{-24 - 14 + 4}{3} = -11.333\).
\[ V \approx \begin{pmatrix} -0.4472 & 0 & -0.8944 & 8.944 \\ -0.5963 & 0.7454 & 0.2981 & 0.745 \\ 0.6667 & 0.6667 & -0.3333 & -11.333 \\ 0 & 0 & 0 & 1 \end{pmatrix} \]
c) Third row applied to \((8, 3, 6)\): \(\tfrac{2}{3}(8 + 3) - \tfrac{6}{3} - 11.333 = 7.333 - 2 - 11.333 = -6\) ✓. First row: \(\dfrac{-8 - 12 + 20}{\sqrt{5}} = 0\) ✓. Second: \(\dfrac{-32 + 15 + 12 + 5}{3\sqrt{5}} = 0\) ✓ (the \(+5\) term is the translation, \(0.745 \cdot 3\sqrt{5}\)).
Solution 2.
a) The camera looks from the point \((20, 5, 0)\) toward \((0, 5, 0)\): forward is \((-1, 0, 0)\). It looks horizontally, so up is \((0, 1, 0)\). The right is \(\hat{\mathbf{f}} \times \mathbf{a} = (-1, 0, 0) \times (0, 1, 0) = (0, 0, -1)\): someone looking toward \(-X\) has \(-Z\) on their right.
b) Rows: right, up and \(-\hat{\mathbf{f}} = (1, 0, 0)\). Translation: \(-\hat{\mathbf{d}} \cdot \mathbf{e} = 0\), \(-\hat{\mathbf{u}} \cdot \mathbf{e} = -5\), \(\hat{\mathbf{f}} \cdot \mathbf{e} = -20\).
\[ V = \begin{pmatrix} 0 & 0 & -1 & 0 \\ 0 & 1 & 0 & -5 \\ 1 & 0 & 0 & -20 \\ 0 & 0 & 0 & 1 \end{pmatrix} \]
c) Ship: \((-6,\ 3 - 5,\ 8 - 20) = (-6, -2, -12)\): 6 m to the left, 2 m below the center, 12 m away. Lamp: \((0,\ 12 - 5,\ 0 - 20) = (0, 7, -20)\): on the vertical axis of the image, 7 m above, 20 m away.
Solution 3.
alpha = look_at_matrix([12.0, 7.0, 4.0], ship)
print(np.round(alpha, 4) + 0.0)
print(np.round(transform_point(alpha, ship), 4) + 0.0)
side = look_at_matrix([20.0, 5.0, 0.0], [0.0, 5.0, 0.0])
print(transform_point(side, ship) + 0.0, transform_point(side, lamp) + 0.0)
cockpit = follow_camera(ship_world, [0.0, 0.5, 1.0], [0.0, 0.5, 10.0])
print(np.round(camera_position(cockpit), 4))
print(np.round(transform_point(cockpit, [12.0, 7.0, 4.0]), 4) + 0.0)
print(np.round(transform_point(cockpit, [0.0, 0.0, 0.0]), 4) + 0.0)[[ -0.4472 0. -0.8944 8.9443] [ -0.5963 0.7454 0.2981 0.7454] [ 0.6667 0.6667 -0.3333 -11.3333] [ 0. 0. 0. 1. ]] [ 0. 0. -6.] [ -6. -2. -12.] [ 0. 7. -20.] [8.8 3.5 6.6] [-4. 3.5 -1. ] [ 0. -3.5 11. ]
The first three outputs confirm Exercises 1 and 2. The cockpit camera is at \((8.8, 3.5, 6.6)\). It sees beacon Alpha at \((-4, 3.5, -1)\): its \(z\) is negative, so it is ahead, although only 1 m, and far off to one side (4 m to the left and 3.5 m up): whether or not it makes it into the image will depend on the width of the field of view, which we will define in the next lesson. The base of the lighthouse is at \((0, -3.5, 11)\): positive \(z\), behind the camera. It cannot appear.
Conclusion
Every vertex travels through a chain of coordinate spaces—local, world, view, clip, NDC and screen—and each stretch is a transformation. The model matrix goes from local space to the world. The camera is just another object, with its world matrix and the convention that it looks toward \(-Z\) with \(+X\) to the right and \(+Y\) up; its inverse is the view matrix, which expresses the world relative to the camera by projecting each point onto its three axes. The look-at function manufactures that matrix with two cross products from the eye, the target and an up vector, and it only fails when the line of sight is vertical. On top of it we have built an orbit camera with spherical coordinates, a first-person camera with yaw and pitch, and a follow camera anchored to the ship. mini3d gains look_at_matrix, view_matrix_from_world, camera_position, orbit_camera, first_person_view, view_direction and follow_camera.
The vertices are now in camera space, but they are still three-dimensional points, measured in meters. The decisive step is still missing: flattening them onto a plane to obtain an image, making what is far away look smaller. That is what we will study in the next lesson, "Projections and Views", where we will derive the orthographic and perspective projection matrices and discover what the fourth coordinate \(w\) was really for.
