Until now our meshes have come from hand-written lists or from very simple formulas, and they all have flat faces. But the world we want to represent is curved: the dome that protects the lighthouse lamp, the rounded spine of a ship, the relief of an asteroid. A designer does not model those shapes by placing thousands of triangles one by one: they describe them with mathematics—a function, an equation or a handful of control points—and let the computer generate the triangles with whatever density is needed. In this lesson we study the three classic ways of describing a surface (explicit, parametric and implicit), how the exact normal is obtained in each of them, and Bézier curves and surfaces, the basis of almost all computer modeling, together with their successors, B-splines and NURBS.

The code assumes that the functions from the previous lessons (normalize, norm, cross_product, spherical_to_cartesian, transform_point, transform_points, rigid_inverse, create_mesh, face_areas, vertex_normals, euler_characteristic, is_closed...) and the scene data are already defined: ship, lamp, camera, ship_orientation and ship_world.

Three ways of describing a surface

Take a sphere of radius \(r\) centered at the origin. It can be described in three ways:

Form Idea The sphere
Explicit One coordinate as a function of the other two \(y = \sqrt{r^2 - x^2 - z^2}\) (only the upper half!)
Parametric The three coordinates as a function of two parameters \((u, v)\) \(S(u, v) = r,(\cos v \sin u,\ \sin v,\ \cos v \cos u)\)
Implicit The points that satisfy an equation \(x^2 + y^2 + z^2 - r^2 = 0\)

Each one is good at answering a different question. The parametric form knows how to generate points on the surface: you choose \(u\) and \(v\) and you get a point. The implicit form knows how to check points: given any point, it says whether it is on the surface, inside or outside. The explicit form is a particular, limited case of both.

We had already come across this duality in Module 3: a line had the parametric equation \(\mathbf{p}_0 + t,\mathbf{v}\) and a plane had the implicit equation \(\mathbf{n} \cdot \mathbf{p} + d = 0\). And all the ray intersections consisted of the same thing: substituting the parametric form of the ray into the implicit form of the object.

Explicit surfaces: the heightmap

In an explicit surface the height above each point of the ground is given directly. In mathematics books it is written \(z = f(x, y)\); with our convention of Y pointing up it is:

\[ y = h(x, z) \]

In graphics this function is called a heightmap, and it is the usual way of representing terrain. Often \(h\) is not a formula but a grayscale image: each pixel stores the height of one point of a grid.

Let us take as an example a hill on the asteroid, near the base of the lighthouse:

\[ h(x, z) = 4 - \frac{x^2 + 2z^2}{8} \]

Its top, 4 m high, is at the origin, and it descends faster in the Z direction than in the X direction.

The normal

Imagine that we move a little over the terrain in the X direction: we advance 1 and climb \(\partial h/\partial x\) (the slope in that direction). The vector \(\mathbf{t}_x = (1,\ \partial h/\partial x,\ 0)\) is tangent to the surface. The same in Z: \(\mathbf{t}_z = (0,\ \partial h/\partial z,\ 1)\). The normal is perpendicular to both, and it is given by their cross product (in the order that points upward):

\[ \mathbf{n} = \mathbf{t}_z \times \mathbf{t}_x = \left(-\frac{\partial h}{\partial x},\ 1,\ -\frac{\partial h}{\partial z}\right) \]

It has a very direct reading: on flat ground it is \((0, 1, 0)\), and the more the terrain climbs toward \(+X\), the more the normal leans toward \(-X\), downhill.

Example. At the point \((x, z) = (2, 1)\): \(h = 4 - \tfrac{4 + 2}{8} = 3.25\). The partial derivatives are \(\partial h/\partial x = -x/4 = -0.5\) and \(\partial h/\partial z = -z/2 = -0.5\). The normal is \((0.5, 1, 0.5)\), which normalized (norm \(\sqrt{1.5}\)) gives \((0.408, 0.816, 0.408)\).

When \(h\) does not have a formula that can be differentiated by hand (or is an image), the derivatives are approximated with central differences: the function is evaluated a little before and a little after, and the difference is divided by the separation.

import numpy as np
np.set_printoptions(suppress=True)

def hill_height(x, z):
    """Hill on the asteroid: heightmap y = h(x, z)."""
    return 4.0 - (x * x + 2.0 * z * z) / 8.0

def explicit_normal(h, x, z, step=1e-5):
    """Unit normal (pointing up) of the surface y = h(x, z)."""
    dh_dx = (h(x + step, z) - h(x - step, z)) / (2.0 * step)
    dh_dz = (h(x, z + step) - h(x, z - step)) / (2.0 * step)
    return normalize([-dh_dx, 1.0, -dh_dz])

print(hill_height(2.0, 1.0), np.round(explicit_normal(hill_height, 2.0, 1.0), 4))
3.25 [0.4082 0.8165 0.4082]

The limitation. A function gives a single value of \(y\) for each \((x, z)\). An explicit surface cannot have caves, overhangs or vertical walls, and it cannot close up on itself: of a sphere it describes only one hemisphere. It is good for terrain and little else.

Parametric surfaces

A parametric surface is a function that turns two numbers into a point in space:

\[ S(u, v) = \big(x(u, v),\ y(u, v),\ z(u, v)\big) \]

It is the natural generalization of the parametric line \(\mathbf{p}(t)\): one parameter traces a curve; two, a surface. It helps to imagine \((u, v)\) as the coordinates of a square rubber sheet, which the function bends and stretches into shape. We will always normalize the parameters to the interval \([0, 1]\).

Surface \(S(u, v)\) Parameters
Plane (parallelogram) \(\mathbf{p}_0 + u,\mathbf{a} + v,\mathbf{b}\) Progress along each side
Sphere \(r,(\cos\varepsilon \sin\varphi,\ \sin\varepsilon,\ \cos\varepsilon \cos\varphi)\) Azimuth \(\varphi = 2\pi u\); elevation \(\varepsilon\) from \(-\tfrac{\pi}{2}\) to \(\tfrac{\pi}{2}\)
Cylinder \((r \sin\varphi,\ H,v,\ r \cos\varphi)\) Angle \(\varphi = 2\pi u\); height
Torus \(\big((R + r\cos\theta)\sin\varphi,\ r \sin\theta,\ (R + r\cos\theta)\cos\varphi\big)\) Angle \(\varphi\) around the axis; angle \(\theta\) around the tube

Several remarks:

  • The plane is the parametric equation from "Equations of Planes and Lines".
  • The sphere is nothing more than spherical_to_cartesian from "Coordinates and Planes" with the radius fixed: spherical coordinates are a parameterization of the sphere. The cylinder, likewise, is the cylindrical coordinates with the radius fixed.
  • An explicit surface is a particular case: \(S(u, v) = (u,\ h(u, v),\ v)\).
  • The parameterization is not unique: the same sphere can be traversed in many ways.

The lighthouse dome is a hemisphere of radius 1.5 m resting on top of the tower, centered at the lamp, \((0, 12, 0)\). It is half a sphere: the elevation only goes from 0 to 90°.

dome_center = np.array([0.0, 12.0, 0.0])

def dome(u, v):
    """Hemisphere of radius 1.5 over the lamp: u runs over the azimuth and v over the elevation."""
    return dome_center + spherical_to_cartesian(1.5, 2.0 * np.pi * u, 0.5 * np.pi * v)

print(np.round(dome(0.0, 0.0), 4), np.round(dome(0.125, 0.5), 4), np.round(dome(0.7, 1.0), 4) + 0.0)
[ 0.  12.   1.5] [ 0.75   13.0607  0.75  ] [ 0.  13.5  0. ]

The point \((u, v) = (0, 0)\) is on the rim of the dome, on the \(+Z\) axis; \((0.125, 0.5)\) corresponds to 45° of azimuth and 45° of elevation; and with \(v = 1\) we get the pole, \((0, 13.5, 0)\), whatever \(u\) is: one whole side of the rubber sheet has shrunk to a point.

Tangents and normal of a parametric surface

If \(v\) is fixed and \(u\) is allowed to vary, the point \(S(u, v)\) travels along a curve on the surface (on the dome, a parallel). Its velocity is the partial derivative with respect to \(u\), a vector tangent to the surface. The same goes for fixing \(u\) (a meridian):

\[ S_u = \frac{\partial S}{\partial u} \qquad\qquad S_v = \frac{\partial S}{\partial v} \]

These two vectors span the tangent plane at the point. The normal is perpendicular to both:

\[ \hat{\mathbf{n}} = \frac{S_u \times S_v}{\lVert S_u \times S_v \rVert} \]

It is the same construction as the normal of a triangle, \((B - A) \times (C - A)\), with the edges replaced by derivatives. And, as there, the order decides which side it points to: if the normal comes out pointing inward, the roles of \(u\) and \(v\) are swapped. The norm \(\lVert S_u \times S_v \rVert\) means something too: it is the factor by which the surface stretches the area of the parameter sheet.

Example. On the sphere, with \(\varphi\) the azimuth and \(\varepsilon\) the elevation:

\[ S_\varphi = r,(\cos\varepsilon\cos\varphi,\ 0,\ -\cos\varepsilon \sin\varphi) \qquad S_\varepsilon = r,(-\sin\varepsilon \sin\varphi,\ \cos\varepsilon,\ -\sin\varepsilon\cos\varphi) \]

At the simplest point, \(\varphi = \varepsilon = 0\), they are \(S_\varphi = (r, 0, 0)\)—toward the east—and \(S_\varepsilon = (0, r, 0)\)—toward the north—and their cross product is \((0, 0, r^2)\): it points toward \(+Z\), which is where the point is, \((0, 0, r)\). The normal of a sphere is radial and outward, as we knew.

At the pole, on the other hand, \(\cos\varepsilon = 0\) and \(S_\varphi\) vanishes: the cross product is zero and the formula gives no normal. It is a singularity of the parameterization, not of the surface (the sphere is perfectly smooth at the pole). We already know it: it is the pole of spherical coordinates and the degenerate case of look-at.

For an arbitrary surface we compute the derivatives, once again, with central differences:

def parametric_normal(function, u, v, step=1e-5):
    """Unit normal S_u x S_v, with the partial derivatives by central differences."""
    s_u = (function(u + step, v) - function(u - step, v)) / (2.0 * step)
    s_v = (function(u, v + step) - function(u, v - step)) / (2.0 * step)
    return normalize(cross_product(s_u, s_v))

p = dome(0.125, 0.5)
print(np.round(parametric_normal(dome, 0.125, 0.5), 4), np.round((p - dome_center) / 1.5, 4))
[0.5    0.7071 0.5   ] [0.5    0.7071 0.5   ]

The numerical normal coincides with the exact one, which on a sphere is the vector from the center to the point divided by the radius.

Tessellating: from the formula to the mesh

A graphics card does not draw formulas, but triangles. Tessellating a parametric surface means sampling it on a grid of values of \((u, v)\) and joining neighboring samples:

  1. The parameter square is divided into \(n_u \times n_v\) cells: \((n_u + 1)(n_v + 1)\) vertices.
  2. Each vertex is \(S(i/n_u,\ j/n_v)\).
  3. Each cell is split into two triangles, ordered so that their normal coincides with \(S_u \times S_v\).
def tessellate_parametric(function, n_u, n_v):
    """Mesh of the surface function(u, v), with u and v in [0, 1], in n_u x n_v quadrilaterals."""
    vertices = [function(i / n_u, j / n_v) for i in range(n_u + 1) for j in range(n_v + 1)]
    faces = []
    for i in range(n_u):
        for j in range(n_v):
            a = i * (n_v + 1) + j           # vertex (i, j)
            b = a + (n_v + 1)               # vertex (i + 1, j)
            faces += [[a, b, b + 1], [a, b + 1, a + 1]]
    return create_mesh(vertices, faces)

for n in (4, 8, 16, 32):
    mesh = tessellate_parametric(dome, 2 * n, n)
    print(n, len(mesh["vertices"]), len(mesh["faces"]), round(face_areas(mesh).sum(), 4))
print(round(2.0 * np.pi * 1.5 ** 2, 4))

mesh = tessellate_parametric(dome, 16, 4)
print(euler_characteristic(mesh), is_closed(mesh), int(np.sum(face_areas(mesh) < 1e-12)))
4 45 64 13.1698
8 153 256 13.8894
16 561 1024 14.0748
32 2145 4096 14.1216
14.1372
1 False 16

As the grid is refined, the area of the mesh converges to the exact area of the hemisphere, \(2\pi r^2 = 14.137\) m². That is the great advantage of having the formula: the resolution is chosen afterward, and it can be different depending on how close the camera is (this is the idea of level of detail).

The last line compares this mesh with the sphere_mesh from "Representing 3D Objects", which was a more careful tessellation of the same formula:

  • The dome is an open surface (it has a boundary, the equator): it is not closed, and its Euler characteristic is not 2.
  • The grid duplicates the vertices of the seam: the column \(u = 0\) and the column \(u = 1\) are the same points in space with different indices. In sphere_mesh we stitched them together with j % meridians.
  • At the pole there are 17 coincident vertices and 16 degenerate triangles, of zero area. In sphere_mesh the pole was a single vertex with a fan of triangles.

Duplicating the seam is not always a flaw: as we will see in "Texture Coordinates and Mapping", it is just what is needed to wrap an image around the object.

Implicit surfaces

An implicit surface is the set of points at which a function of three variables vanishes:

\[ F(x, y, z) = 0 \]

The function \(F\) assigns a number to every point in space, not just to those on the surface, and with the usual convention its sign classifies space into three regions:

\(F(\mathbf{p})\) The point is
Negative Inside
Zero On the surface
Positive Outside

For the sphere, \(F = x^2 + y^2 + z^2 - r^2\): the squared distance to the center, compared with the squared radius. Knowing whether a point is inside an object—an awkward question for a mesh—costs one evaluation here.

Quadrics

The simplest implicit surfaces, after the plane, are the quadrics: those in which \(F\) is a polynomial of degree 2.

Quadric Equation (centered, axis-aligned)
Sphere \(x^2 + y^2 + z^2 - r^2 = 0\)
Ellipsoid \(\dfrac{x^2}{a^2} + \dfrac{y^2}{b^2} + \dfrac{z^2}{c^2} - 1 = 0\)
Cylinder (Y axis) \(x^2 + z^2 - r^2 = 0\)
Cone (Y axis) \(x^2 + z^2 - k^2 y^2 = 0\)
Paraboloid \(x^2 + z^2 - y = 0\)

A ray substituted into any of them gives a quadratic equation in \(t\), as with the sphere in "Intersections: Rays, Spheres, Triangles and Boxes". The ellipsoid is a scaled sphere: the one with semi-axes \((4, 1, 2)\) is the "rounded" version of the ship's hull in its local space. The octahedral hull itself also has an implicit equation, although it is not a quadric: \(\tfrac{\lvert x \rvert}{4} + \lvert y \rvert + \tfrac{\lvert z \rvert}{2} - 1 = 0\).

The normal is the gradient

The gradient of \(F\) is the vector of its partial derivatives:

\[ \nabla F = \left(\frac{\partial F}{\partial x},\ \frac{\partial F}{\partial y},\ \frac{\partial F}{\partial z}\right) \]

It points in the direction in which \(F\) grows fastest. On the surface, \(F\) is always 0: moving along it does not change \(F\), so the direction of greatest change has to be perpendicular to it. Therefore:

\[ \hat{\mathbf{n}} = \frac{\nabla F}{\lVert \nabla F \rVert} \]

and, since \(F\) grows outward, the normal points outward. For the sphere, \(\nabla F = (2x, 2y, 2z)\): radial. For a plane, \(F = \mathbf{n} \cdot \mathbf{p} + d\), the gradient is \(\mathbf{n}\), the vector we have been calling the normal since Module 3.

Example. On the hull ellipsoid, \(F = \tfrac{x^2}{16} + y^2 + \tfrac{z^2}{4} - 1\), the local point \((2, 0.5, \sqrt{2})\) is on the surface: \(\tfrac{4}{16} + 0.25 + \tfrac{2}{4} - 1 = 0\). The gradient is \(\left(\tfrac{x}{8},\ 2y,\ \tfrac{z}{2}\right) = (0.25,\ 1,\ 0.707)\), of norm \(\sqrt{0.0625 + 1 + 0.5} = 1.25\). The normal is \((0.2,\ 0.8,\ 0.566)\). Note that it is not radial: on an ellipsoid, the normal does not point in the direction from the center to the point.

def implicit_normal(f, p, step=1e-5):
    """Unit normal of the surface f(p) = 0 at the point p: the normalized gradient."""
    p = np.asarray(p, dtype=float)
    gradient = np.zeros(3)
    for axis in range(3):
        delta = np.zeros(3)
        delta[axis] = step
        gradient[axis] = (f(p + delta) - f(p - delta)) / (2.0 * step)
    return normalize(gradient)

def hull_ellipsoid(p):
    x, y, z = p
    return x * x / 16.0 + y * y + z * z / 4.0 - 1.0

def hull_octahedron(p):
    x, y, z = p
    return abs(x) / 4.0 + abs(y) + abs(z) / 2.0 - 1.0

for name, p in (("antenna", [1.0, 2.0, 0.0]), ("interior", [2.0, 0.5, 1.0]),
                ("surface", [2.0, 0.5, np.sqrt(2.0)])):
    print(name, round(hull_ellipsoid(p), 4), round(hull_octahedron(p), 4))
print(np.round(implicit_normal(hull_ellipsoid, [2.0, 0.5, np.sqrt(2.0)]), 4))

hit_local = transform_point(rigid_inverse(ship_world), np.array([26.0, 10.0, 13.0]) / 3.0)
print(np.round(hit_local, 4), round(hull_octahedron(hit_local), 6) + 0.0)
print(np.round(ship_orientation @ implicit_normal(hull_octahedron, hit_local), 4))
antenna 3.0625 1.25
interior -0.25 0.5
surface 0.0 0.7071
[0.2    0.8    0.5657]
[ 1.7333  0.3333 -0.4667] 0.0
[-0.2182  0.8729 -0.4364]
  • The antenna, at the local point \((1, 2, 0)\), is outside both hulls. The point \((2, 0.5, 1)\) is inside the ellipsoid but outside the octahedron, which is more angular and fits inside it.
  • The last two lines take to local space the point where the lighthouse beam hit the hull: the octahedron's function confirms that it is on the surface, and its gradient, returned to the world with the ship's orientation, gives \((-0.218, 0.873, -0.436)\). It is exactly the normal of that face that we obtained in "Representing 3D Objects" with a cross product. Two paths, the same vector.

Drawing an implicit surface

The weak point of implicit surfaces is the opposite of that of parametric ones: checking points is trivial, but generating them is not. There are two ways: casting rays and looking for where \(F\) changes sign, or converting the surface into a mesh. The classic algorithm for the latter is marching cubes: \(F\) is evaluated at the nodes of a 3D grid and, in each cube in which some vertices are inside and others outside, triangles are placed that separate the ones from the others. It is the bridge between voxels and meshes; we will not implement it here.

Signed distance fields

Among all the functions \(F\) that describe the same surface there is one that is especially useful: the one that returns the distance from the point to the surface, negative on the inside. It is called a signed distance field (SDF). For a sphere with center \(\mathbf{c}\) and radius \(r\):

\[ d(\mathbf{p}) = \lVert \mathbf{p} - \mathbf{c} \rVert - r \]

And the signed distance to a plane is the point_plane_distance from "Distances and Geometric Projections". Three properties make SDFs very convenient:

  • They are combined with min and max. The union of two shapes is the minimum of their distances; the intersection, the maximum.
  • The normal is still the gradient, and it also has norm 1.
  • They say how far you can advance without colliding. If the distance to the nearest surface is \(d\), a ray can take a step of length \(d\) in complete safety. Repeating this until \(d \approx 0\) is sphere tracing.
def sphere_sdf(p, center, radius):
    """Signed distance from p to a sphere: negative inside."""
    return norm(np.asarray(p, dtype=float) - np.asarray(center, dtype=float)) - radius

def asteroids_sdf(p):
    """Union of the rogue asteroid and the lighthouse asteroid."""
    return min(sphere_sdf(p, [2.0, 8.0, 5.0], 5.0), sphere_sdf(p, [0.0, -10.0, 0.0], 10.0))

print(round(asteroids_sdf(ship), 4), round(asteroids_sdf(camera), 4),
      round(asteroids_sdf([2.0, 8.0, 2.0]), 4))
print(np.round(implicit_normal(asteroids_sdf, ship), 4))

# Sphere tracing: the lighthouse beam aimed at the strip
direction, t, steps = np.array([1.0, -8.0, 4.0]) / 9.0, 0.0, 0
while asteroids_sdf(lamp + t * direction) > 1e-4:
    t += asteroids_sdf(lamp + t * direction)
    steps += 1
print(steps, round(t, 3))
2.874 10.4272 -2.0
[ 0.762 -0.635  0.127]
6 2.0

The ship is 2.87 m from the nearest rock (the rogue asteroid) and the camera 10.43 m away; the point \((2, 8, 2)\) is 2 m inside. The gradient at the ship's position is the direction in which it has to move to get away from danger as fast as possible: precious information for automatic navigation. And sphere tracing finds in 6 steps that the beam touches the rogue asteroid 2 m from the lamp, the same result as ray_sphere in Module 3, without solving any equation.

Bézier curves

Closed-form formulas are fine for spheres and cylinders, but not for the outline of a ship. Free-form modeling is based on another idea: the designer places a few control points and the curve lets itself be "attracted" by them. The most important ones are Bézier curves. We start with curves because surfaces will be built from them.

De Casteljau's algorithm

The simplest Bézier curve has two control points, and it is the segment that joins them: \(B(t) = (1 - t),P_0 + t,P_1\). It is linear interpolation, our lerp.

With three points, \(P_0\), \(P_1\) and \(P_2\), we interpolate twice: first between each pair of neighbors, and then between the two results, always with the same \(t\). With four points, three times. This is De Casteljau's algorithm: repeating "lerp between neighbors" until a single point is left.

Example. The ship's approach route to the strip is a cubic Bézier (four control points):

  • \(P_0 = (8, 3, 6)\): the ship.
  • \(P_1 = (12, 3, 9)\): 5 m ahead of the nose (\(P_0 + 5,\mathbf{n}_3\)).
  • \(P_2 = (9, 2, 5)\): 2 steps before touchdown, along the descent direction \((1, -1, -1)\).
  • \(P_3 = (11, 0, 3)\): the point of contact with the strip.

For \(t = 0.5\), each interpolation is a midpoint:

Level Points
Control \((8, 3, 6)\quad (12, 3, 9)\quad (9, 2, 5)\quad (11, 0, 3)\)
1 \((10, 3, 7.5)\quad (10.5, 2.5, 7)\quad (10, 1, 4)\)
2 \((10.25, 2.75, 7.25)\quad (10.25, 1.75, 5.5)\)
3 \((10.25,\ 2.25,\ 6.375)\)

The point of the curve at \(t = 0.5\) is \((10.25, 2.25, 6.375)\).

Bernstein polynomials

Expanding the chained interpolations gives a direct formula. For the cubic:

\[ B(t) = (1 - t)^3,P_0 + 3,(1 - t)^2,t,P_1 + 3,(1 - t),t^2,P_2 + t^3,P_3 \]

The coefficients are the Bernstein polynomials, which for degree \(n\) are:

\[ B_i^n(t) = \binom{n}{i},t^i,(1 - t)^{n - i} \qquad\qquad B(t) = \sum_{i=0}^{n} B_i^n(t),P_i \]

They are the terms of the expansion of \(\big((1 - t) + t\big)^n\), which equals 1. That is why they are all non-negative on \([0, 1]\) and add up to 1: the curve is, at every instant, a weighted average of its control points, just as barycentric coordinates are a weighted average of the vertices of a triangle. At \(t = 0.5\) the weights of the cubic are \(\tfrac{1}{8}, \tfrac{3}{8}, \tfrac{3}{8}, \tfrac{1}{8}\), and indeed \(\tfrac{1}{8},\big(P_0 + 3P_1 + 3P_2 + P_3\big) = (10.25, 2.25, 6.375)\).

Properties

  • It passes through the endpoints: \(B(0) = P_0\) and \(B(1) = P_n\). Through the intermediate points, in general, it does not pass: they only pull on it.
  • Tangents at the endpoints: the curve leaves \(P_0\) in the direction of \(P_1\) and arrives at \(P_n\) from the direction of \(P_{n-1}\). For the cubic, \(B'(0) = 3,(P_1 - P_0)\) and \(B'(1) = 3,(P_3 - P_2)\). The interior points are "handles" that set the direction and the strength of departure and arrival.
  • Convex hull: being an average with positive weights, the curve never leaves the convex polygon formed by its control points. The AABB of the control points is therefore a valid bounding volume of the curve.
  • Affine invariance: transforming the curve is equivalent to transforming its control points. To move, rotate or scale the route it is enough to apply the matrix to four points.
  • Derivative: the derivative of a Bézier of degree \(n\) is another Bézier of degree \(n - 1\), whose control points are \(n,(P_{i+1} - P_i)\).
def bezier(control_points, t):
    """Point of the Bezier curve at parameter t (De Casteljau's algorithm)."""
    points = np.asarray(control_points, dtype=float)
    while len(points) > 1:
        points = (1.0 - t) * points[:-1] + t * points[1:]     # lerp between neighbors
    return points[0]

def bezier_tangent(control_points, t):
    """Derivative of the Bezier curve at t: n times the Bezier of the differences."""
    points = np.asarray(control_points, dtype=float)
    return (len(points) - 1) * bezier(points[1:] - points[:-1], t)

route = np.array([[8.0, 3.0, 6.0], [12.0, 3.0, 9.0], [9.0, 2.0, 5.0], [11.0, 0.0, 3.0]])
for t in (0.0, 0.5, 1.0):
    print(t, np.round(bezier(route, t), 4), np.round(bezier_tangent(route, t), 4))

samples = np.array([bezier(route, t) for t in np.linspace(0.0, 1.0, 101)])
print(round(float(np.sum(np.linalg.norm(np.diff(samples, axis=0), axis=1))), 3))
print(route.min(axis=0), route.max(axis=0), samples.min(axis=0).round(3), samples.max(axis=0).round(3))
0.0 [8. 3. 6.] [12.  0.  9.]
0.5 [10.25   2.25   6.375] [ 0.   -3.   -5.25]
1.0 [11.  0.  3.] [ 6. -6. -6.]
7.495
[8. 0. 3.] [12.  3.  9.] [8. 0. 3.] [11.     3.     7.079]

In bezier, points[:-1] is all the points except the last and points[1:] all except the first: the line in the loop interpolates each point with its neighbor and leaves one point fewer. The function works for any degree.

The route leaves the ship with velocity \((12, 0, 9) = 15,\mathbf{n}_3\), exactly in the direction of the nose, and arrives at the strip with velocity \((6, -6, -6)\), the descent direction \((1, -1, -1)\) that we used in Module 3. Halfway along it no longer advances in X and it is descending. The curve is about 7.5 m long (adding up 100 small segments) and, as the convex hull promises, it does not leave the box of its control points: it reaches \(x = 11\) and \(z = 7.08\), but not the \(x = 12\), \(z = 9\) of the handle \(P_1\).

Bézier surfaces

To go from curve to surface, the same idea is applied in two directions. A bicubic Bézier patch is defined with a grid of \(4 \times 4 = 16\) control points \(P_{ij}\):

\[ S(u, v) = \sum_{i=0}^{3}\sum_{j=0}^{3} B_i^3(u),B_j^3(v),P_{ij} \]

Each weight is the product of a Bernstein polynomial in \(u\) and another in \(v\); that is why it is called a tensor product surface. The practical way of evaluating it explains it better than the formula:

  1. Each row of the grid is a Bézier curve. All four are evaluated at \(v\): four points.
  2. Those four points are the control points of a new curve, which is evaluated at \(u\).

A Bézier curve whose control points move, in turn, along Bézier curves. The patch inherits the properties of the curves: it passes through the four corners of the grid, its four edges are the Bézier curves of the outer rows and columns, it stays inside the convex hull of its 16 points and it is transformed by transforming its control points. The four interior points are not touched: they make the surface bulge.

It is a parametric surface like the others: its normal is \(S_u \times S_v\), and it is tessellated with tessellate_parametric.

Example: the ship's spine. The team wants to replace the sharp upper edge of the hull with a curved fairing. In the ship's local coordinates, the control grid covers the rectangle \(x \in [-3, 3]\), \(z \in [-1.5, 1.5]\): the twelve points on the border are at height 0 and the four interior ones are raised to \(y = 1.2\). The parameter \(u\) runs along the longitudinal axis (Z) and \(v\) along the transverse one (X), in that order so that \(S_u \times S_v\) points upward.

At the center, \(u = v = 0.5\), only the four interior points count (the others have height 0), each with weight \(\tfrac{3}{8} \cdot \tfrac{3}{8}\):

\[ y = 4 \cdot \frac{9}{64} \cdot 1.2 = 0.675 \]

The spine rises 0.675 m, a little over half the height of its control points: the surface approaches them, but does not reach them.

def bezier_patch(control, u, v):
    """Point of the Bezier patch: control is a grid (rows in u, columns in v) of points."""
    control = np.asarray(control, dtype=float)
    curve = [bezier(row, v) for row in control]        # one curve per row, evaluated at v
    return bezier(curve, u)

xs, zs = [-3.0, -1.0, 1.0, 3.0], [-1.5, -0.5, 0.5, 1.5]
control_local = np.array([[[x, 1.2 if (i in (1, 2) and j in (1, 2)) else 0.0, z]
                           for j, x in enumerate(xs)] for i, z in enumerate(zs)])

def spine_local(u, v):
    return bezier_patch(control_local, u, v)

for u, v in ((0.5, 0.5), (0.5, 0.25), (0.25, 0.5)):
    print((u, v), np.round(spine_local(u, v), 4), np.round(parametric_normal(spine_local, u, v), 4) + 0.0)
print(spine_local(0.0, 0.0), spine_local(1.0, 1.0))

# The same patch in the world: just transform the 16 control points
control_world = transform_points(ship_world, control_local.reshape(-1, 3)).reshape(4, 4, 3)

def spine(u, v):
    return bezier_patch(control_world, u, v)

print(np.round(spine(0.5, 0.25), 4), np.round(parametric_normal(spine, 0.5, 0.25), 4))
spine_mesh = tessellate_parametric(spine, 8, 8)
print(len(spine_mesh["vertices"]), len(spine_mesh["faces"]), round(face_areas(spine_mesh).sum(), 3))
print(np.round(spine_mesh["vertices"][4 * 9 + 2], 4), np.round(vertex_normals(spine_mesh)[4 * 9 + 2], 4))
(0.5, 0.5) [0.    0.675 0.   ] [0. 1. 0.]
(0.5, 0.25) [-1.5     0.5062  0.    ] [-0.2195  0.9756  0.    ]
(0.25, 0.5) [ 0.      0.5062 -0.75  ] [ 0.      0.9119 -0.4104]
[-3.   0.  -1.5] [3.  0.  1.5]
[7.1    3.5062 7.2   ] [-0.1317  0.9756  0.1756]
81 128 19.489
[7.1    3.5062 7.2   ] [-0.1218  0.9765  0.1776]
  • At the center, the normal is vertical; toward one side (\(v = 0.25\)) it leans toward \(-X\), and toward the stern (\(u = 0.25\)), toward \(-Z\) and more steeply, because the patch is shorter in that direction.
  • The patch passes through the corners of the grid.
  • To take it to the world we do not transform the surface, but its 16 control points with the ship's matrix (affine invariance). The point \((0.5, 0.25)\) goes to \((7.1, 3.51, 7.2)\) and its normal is the local one rotated by \(N\).
  • The 8 × 8 tessellation gives 81 vertices and 128 triangles. The last line compares, at that same point, the vertex normal we would compute by averaging faces, \((-0.122, 0.977, 0.178)\), with the exact one of the surface, \((-0.132, 0.976, 0.176)\). They are similar, but they do not coincide: when the formula is available, the right thing to do is to store the analytic normal at each vertex.

Beyond Bézier: B-splines and NURBS

Bézier curves have three limitations that show up as soon as the shape gets complicated:

  • Global control. Moving one control point changes the whole curve, because all the Bernstein polynomials are nonzero over the whole interval.
  • The degree grows with the points. A curve with 20 control points would be of degree 19: expensive to evaluate and prone to oscillating. In practice cubic pieces are chained together, and then you have to make sure by hand that the joins are smooth.
  • They cannot represent a circle. A polynomial cannot trace an arc of a circle exactly, only approximate it.

B-splines

A B-spline solves the first two. It is a curve made up of polynomial pieces of low degree (normally 3), defined by a single list of control points, in which:

  • each control point influences only a few neighboring pieces (local control);
  • the joins between pieces are automatically smooth;
  • the number of control points is independent of the degree.

The new ingredient is the knot vector: an increasing list of parameter values that says where one piece ends and the next begins and, with it, how long the influence of each control point "lasts". If the knots are equally spaced, the B-spline is uniform; if not, non-uniform. A Bézier curve is the particular case of a B-spline with a single piece.

NURBS

NURBS (Non-Uniform Rational B-Splines) solve the third limitation by adding a weight \(w_i\) to each control point. The greater the weight, the more that point attracts the curve. The formula stops being a polynomial and becomes a quotient of polynomials (hence "rational"). For a rational Bézier piece:

\[ C(t) = \frac{\sum_i B_i^n(t),w_i,P_i}{\sum_i B_i^n(t),w_i} \]

This formula should look familiar. It is an ordinary Bézier curve in homogeneous coordinates: each control point is lifted to four dimensions as \((w_i P_i,\ w_i)\), the curve is evaluated there and we divide by \(w\) at the end. The same mechanism as the perspective projection and perspective-correct interpolation. And it is no coincidence: a circle is the perspective projection of a parabola, and a parabola is indeed a polynomial of degree 2. That is why rational curves represent conics (circles, ellipses, hyperbolas) exactly, and NURBS surfaces represent exact spheres, cylinders and cones. It is the reason why they are the standard in industrial design.

Example. The ship orbits the lighthouse 10 m from the axis and 3 m up. A quarter of that orbit, from \((0, 3, 10)\) to \((10, 3, 0)\), is obtained with a rational Bézier of degree 2 whose control points are the two endpoints and the corner \((10, 3, 10)\), where the tangents meet, with weights \(1\), \(\tfrac{\sqrt{2}}{2}\) and \(1\). (The central weight is the cosine of half the angle of the arc: \(\cos 45°\).)

def rational_bezier(control_points, weights, t):
    """Rational Bezier curve: De Casteljau in homogeneous coordinates and division by w."""
    points = np.asarray(control_points, dtype=float)
    weights = np.asarray(weights, dtype=float)
    homogeneous = np.hstack([points * weights[:, None], weights[:, None]])    # (w p, w)
    result = bezier(homogeneous, t)
    return result[:-1] / result[-1]

arc = np.array([[0.0, 3.0, 10.0], [10.0, 3.0, 10.0], [10.0, 3.0, 0.0]])
weights = [1.0, np.sqrt(2.0) / 2.0, 1.0]
for t in (0.0, 0.25, 0.5, 1.0):
    a, b = bezier(arc, t), rational_bezier(arc, weights, t)
    print(t, np.round(a, 4), round(float(np.hypot(a[0], a[2])), 4),
          np.round(b, 4), round(float(np.hypot(b[0], b[2])), 4))
0.0 [ 0.  3. 10.] 10.0 [ 0.  3. 10.] 10.0
0.25 [4.375 3.    9.375] 10.3456 [3.6809 3.     9.2979] 10.0
0.5 [7.5 3.  7.5] 10.6066 [7.0711 3.     7.0711] 10.0
1.0 [10.  3.  0.] 10.0 [10.  3.  0.] 10.0

weights[:, None] turns the list of weights into a column in order to multiply each point by its own. The ordinary Bézier (a parabola) strays as far as 10.61 m from the axis; the rational one stays at exactly 10 m at all its points: it is an arc of a circle. One nuance: the curve is exact in its shape, but it is not traversed at constant speed; \(t = 0.25\) corresponds to 21.6° of arc, not to 22.5°.

NURBS surfaces are built like Bézier patches, by tensor product, with a grid of weighted control points and a knot vector in each direction.

Subdivision surfaces

NURBS surfaces are rectangular grids, and covering a branching shape with them (a character, a hand) requires stitching many patches together. Subdivision surfaces avoid the problem by starting from any polygon mesh, called the control mesh, and refining it repeatedly: each step divides each face into several and repositions the vertices by averaging their neighbors. In the limit a smooth surface is obtained. The best-known schemes are Catmull–Clark (for quadrilaterals; in the regular regions it coincides with a bicubic B-spline) and Loop (for triangles). They are the standard in character animation and film.

Side-by-side comparison

Representation Defined with Generating points Telling whether a point is inside Normal Strong point Typical use
Explicit \(y = h(x, z)\) A function or an image Immediate Immediate (compare heights) \((-h_x, 1, -h_z)\) Simplicity Terrain
Parametric \(S(u, v)\) A formula Immediate Hard \(S_u \times S_v\) Easy to tessellate and to texture Primitives
Implicit \(F = 0\) An equation Hard Immediate \(\nabla F\) Inside/outside, combinations Collisions, SDF, effects
Bézier Grid of control points Immediate Hard \(S_u \times S_v\) Intuitive control Typography, patches, trajectories
NURBS Points, weights and knots Immediate Hard \(S_u \times S_v\) Local control, exact conics Industrial design (CAD)
Subdivision Control mesh By refinement Hard From the limit mesh Arbitrary topology Characters, film

Common Mistakes and Tips

  • Believing that a Bézier curve passes through all its control points. It only passes through the first and the last.
  • Evaluating outside \([0, 1]\). The formula returns a point, but it stops being an average: the convex hull and the geometric meaning are lost.
  • Getting the order of \(S_u \times S_v\) wrong. The normal comes out pointing inward, and with it the winding of the triangles from tessellate_parametric. It is fixed by swapping the parameters.
  • Asking for the normal at a singularity. At the pole of a parametric sphere one partial derivative vanishes and the cross product is zero. Use the known normal there (the axis) or a parameterization without poles.
  • Choosing the finite-difference step badly. Too large and it approximates the derivative poorly; too small and it amplifies rounding errors. Values from \(10^{-4}\) to \(10^{-6}\) work well for scenes measured in meters; if the exact derivative exists, use it.
  • Assuming that the normal of an ellipsoid is radial. It is only so on the sphere. In general the gradient has to be computed.
  • Treating any \(F\) as a distance. \(x^2 + y^2 + z^2 - r^2\) gives the right sign, but its value is not the distance to the sphere. Sphere tracing needs a genuine SDF.
  • Confusing the parameter with the distance traveled. On a Bézier, equal steps of \(t\) are not equal steps of length: moving an object with uniform \(t\) makes it speed up and slow down.
  • Tip. To move, rotate or scale a curve or a patch, transform its control points, not the points already evaluated.

Exercises

Exercise 1. The ship's takeoff maneuver from the strip is a quadratic Bézier curve with control points \(P_0 = (11, 0, 3)\), \(P_1 = (11, 6, 3)\) and \(P_2 = (8, 3, 6)\).

a) Compute with De Casteljau's algorithm the point of the curve at \(t = 0.5\). b) Check it with the Bernstein polynomials of degree 2. c) In which direction does the ship take off and in which direction does it arrive at the final point?

Exercise 2. The ship's energy shield is, in its local coordinates, the ellipsoid \(\tfrac{x^2}{16} + y^2 + \tfrac{z^2}{4} = 1\).

a) Are the main nozzle, with local coordinates \((0, -1, -2)\), and the point \((2, 0.5, 1)\) inside the shield? b) Check that the point \((0, 0.6, 1.6)\) is on the shield and compute its normal by hand.

Exercise 3. The lighthouse tower is a cylinder of radius 1 m and height 12 m.

a) Write its parameterization \(S(u, v)\) so that the normal \(S_u \times S_v\) points outward, and check it with parametric_normal at \((u, v) = (0.25, 0.5)\). b) Tessellate the lateral surface with 6, 12, 24 and 48 divisions around and a single one along the height, and compare the area with the exact one. Why is one vertical division enough?

Solutions

Solution 1.

a) Level 1: \(\tfrac{1}{2}(P_0 + P_1) = (11, 3, 3)\) and \(\tfrac{1}{2}(P_1 + P_2) = (9.5, 4.5, 4.5)\). Level 2: their midpoint, \((10.25,\ 3.75,\ 3.75)\).

b) The polynomials of degree 2 are \((1 - t)^2\), \(2,(1 - t),t\) and \(t^2\); at \(t = 0.5\) they equal \(\tfrac{1}{4}, \tfrac{1}{2}, \tfrac{1}{4}\). Then \(\tfrac{1}{4}(11, 0, 3) + \tfrac{1}{2}(11, 6, 3) + \tfrac{1}{4}(8, 3, 6) = (2.75 + 5.5 + 2,\ 0 + 3 + 0.75,\ 0.75 + 1.5 + 1.5) = (10.25, 3.75, 3.75)\) ✓.

c) \(B'(0) = 2,(P_1 - P_0) = (0, 12, 0)\): it takes off vertically. \(B'(1) = 2,(P_2 - P_1) = (-6, -6, 6)\): it arrives descending, in the direction \((-1, -1, 1)\). The height of the curve is \(y(t) = 12,t - 9,t^2\), which reaches its maximum, 4 m, at \(t = 2/3\), and then drops toward the 3 m of the final position: the control point \(P_1\), at 6 m, pulls it upward without the curve reaching it.

Solution 2.

a) Nozzle: \(F = 0 + 1 + \tfrac{4}{4} - 1 = 1 > 0\): outside the shield. Point \((2, 0.5, 1)\): \(F = 0.25 + 0.25 + 0.25 - 1 = -0.25 < 0\): inside.

b) \(F = 0 + 0.36 + \tfrac{2.56}{4} - 1 = 0.36 + 0.64 - 1 = 0\) ✓. Gradient: \(\left(\tfrac{x}{8},\ 2y,\ \tfrac{z}{2}\right) = (0,\ 1.2,\ 0.8)\), of norm \(\sqrt{1.44 + 0.64} = 1.442\). Normal: \((0,\ 0.832,\ 0.555)\). The radial vector would be \((0, 0.6, 1.6)/1.709 = (0, 0.351, 0.936)\): very different. The shield is flattened in Y, and its normal leans toward that axis.

Solution 3.

a) With the angle in \(u\) and the height in \(v\): \(S(u, v) = (\sin 2\pi u,\ 12,v,\ \cos 2\pi u)\). Then \(S_u\) is horizontal and tangent to the circle, \(S_v = (0, 12, 0)\) is vertical, and \(S_u \times S_v\) is radial and outward. (With the parameters swapped it would point toward the axis.)

b)

takeoff = np.array([[11.0, 0.0, 3.0], [11.0, 6.0, 3.0], [8.0, 3.0, 6.0]])
print(bezier(takeoff, 0.5), bezier_tangent(takeoff, 0.0), bezier_tangent(takeoff, 1.0))
print(hull_ellipsoid([0.0, -1.0, -2.0]), hull_ellipsoid([2.0, 0.5, 1.0]),
      np.round(implicit_normal(hull_ellipsoid, [0.0, 0.6, 1.6]), 4) + 0.0)

def tower(u, v):
    return np.array([np.sin(2.0 * np.pi * u), 12.0 * v, np.cos(2.0 * np.pi * u)])

print(np.round(tower(0.25, 0.5), 4) + 0.0, np.round(parametric_normal(tower, 0.25, 0.5), 4) + 0.0)
for n in (6, 12, 24, 48):
    print(n, round(face_areas(tessellate_parametric(tower, n, 1)).sum(), 3))
print(round(2.0 * np.pi * 1.0 * 12.0, 3))
[10.25  3.75  3.75] [ 0. 12.  0.] [-6. -6.  6.]
1.0 -0.25 [0.     0.8321 0.5547]
[1. 6. 0.] [1. 0. 0.]
6 72.0
12 74.54
24 75.183
48 75.344
75.398

At the point \((1, 6, 0)\) of the tower the normal is \((1, 0, 0)\): radial and outward. The area converges to \(2\pi r H = 75.40\) m²; with 6 sides the mesh is a hexagonal prism of 72 m². One vertical division is enough because in that direction the cylinder is straight: the vertical segments of the mesh coincide exactly with the surface, and subdividing them improves nothing. Triangles only need to be spent where there is curvature.

Conclusion

A surface can be described by giving a height above each point of the ground (explicit), a function that turns two parameters into a point (parametric) or an equation that its points satisfy (implicit). The parametric form generates points easily, is converted into a mesh by sampling a grid of parameters and has \(S_u \times S_v\) as its normal; the implicit form classifies any point as interior or exterior, has the gradient as its normal and, when it measures distances, becomes a signed distance field that makes it possible to combine shapes and trace rays without equations. For free-form shapes, Bézier curves average a set of control points with the Bernstein polynomials—or, what amounts to the same thing, chain linear interpolations with De Casteljau's algorithm—and Bézier patches apply the idea in two directions. B-splines add local control and NURBS add weights that—via homogeneous coordinates—make it possible to represent exact conics; subdivision surfaces free us from the rectangular grid. mini3d gains explicit_normal, tessellate_parametric, parametric_normal, implicit_normal, sphere_sdf, bezier, bezier_tangent, bezier_patch and rational_bezier.

In every representation the same protagonist has appeared again and again: the normal. It is no coincidence. The normal says which way the surface is facing at each point, and that is precisely what decides how much light it receives. In the next lesson, "Lighting and Shading", we will use normals—face normals, vertex normals or exact ones—to compute at last the color of each point of the ship under the lighthouse lamp.

© Copyright 2026. All rights reserved