TExcelTAD
Home › Calculus in Depth › Calculus for Graphics and Games

Calculus for Graphics and Games

A rendered frame is the answer to an integral, every lit surface needs a normal vector that comes from partial derivatives, and every smooth camera path or racing line is a spline whose derivative is a velocity. This lesson works through those three ideas: the rendering integral and its Monte Carlo estimate, normals from partial derivatives of height maps and parametric surfaces, and Catmull-Rom splines with arc-length reparametrisation for constant-speed motion.

Background: Surface Integrals, Tangent Planes and Linear Approximations, Parametric Surfaces and Their Areas and Arc Length and Curvature. For the game-side vocabulary see Math for Games and Easing curves.

The rendering integral

The light leaving a surface point xx toward the viewer is the emitted light plus all incoming light reflected toward the viewer:

Lo(x,ωo)=Le(x,ωo)+∫Ωfr(x,ωi,ωo)⋅Li(x,ωi)⋅cos⁡θi dωiL_o(x, \omega_o) = L_e(x, \omega_o) + \int_\Omega f_r(x, \omega_i, \omega_o) \cdot L_i(x, \omega_i) \cdot \cos\theta_i \, d\omega_i

Ω\Omega is the hemisphere of directions above the surface, frf_r the material's reflectance (BRDF), θi\theta_i the angle between ωi\omega_i and the normal, and dω=sin⁡θ dθ dφd\omega = \sin\theta \, d\theta \, d\varphi the solid-angle element. The cos⁡θ\cos\theta factor is the same projection that turns flux into a surface integral: light arriving at a slant spreads over more area.

LiL_i itself depends on light leaving other surfaces, so the integral is recursive and has no closed form. Path tracers estimate it by Monte Carlo: draw directions ωk\omega_k with density pdf⁡(ω)\operatorname{pdf}(\omega) and average f(ωk)/pdf⁡(ωk)f(\omega_k)/\operatorname{pdf}(\omega_k). The estimate is unbiased, and its error shrinks like 1/N1/\sqrt{N} regardless of dimension. Importance sampling chooses a pdf shaped like the integrand to lower the variance: cosine-weighted sampling (pdf⁡=cos⁡θ/π\operatorname{pdf} = \cos\theta/\pi) cancels the cos⁡θ\cos\theta factor exactly.

Test it on irradiance E=∫ΩLicos⁡θ dωE = \int_\Omega L_i \cos\theta \, d\omega under a sky that is brighter overhead, Li=cos⁡θL_i = \cos\theta. The exact value is ∫02π∫0π/2cos⁡2θsin⁡θ dθ dφ=2π/3\int_0^{2\pi}\int_0^{\pi/2} \cos^2\theta \sin\theta \, d\theta \, d\varphi = 2\pi/3.

python · try it yourself
import numpy as np

rng = np.random.default_rng(42)
exact = 2 * np.pi / 3
for N in [16, 256, 4096, 65536]:
    # uniform hemisphere: cos(theta) is uniform on [0, 1], pdf = 1 / (2 pi)
    c = rng.random(N)
    uniform = np.mean(c * c * 2 * np.pi)
    # cosine-weighted: cos(theta) = sqrt(xi), pdf = cos(theta) / pi
    c = np.sqrt(rng.random(N))
    cosine = np.mean(c * np.pi)            # (L * cos) / pdf = cos * pi
    print(f"N = {N:6d}   uniform err = {abs(uniform - exact):.5f}   cosine-weighted err = {abs(cosine - exact):.5f}")
N =     16   uniform err = 0.54787   cosine-weighted err = 0.14007
N =    256   uniform err = 0.20839   cosine-weighted err = 0.04200
N =   4096   uniform err = 0.01358   cosine-weighted err = 0.00857
N =  65536   uniform err = 0.00774   cosine-weighted err = 0.00066

Both estimators converge to 2π/3≈2.09442\pi/3 \approx 2.0944, but the importance-sampled one has a smaller variance (π2/18≈0.55\pi^2/18 \approx 0.55 against 16π2/45≈3.5116\pi^2/45 \approx 3.51 for uniform sampling, about one sixth), so it reaches the same noise level with fewer samples, fewer rays per pixel.

Normals from partial derivatives

Lighting needs the unit normal nn at each point. Two common cases:

Surface Tangents Normal (before normalising)
Height field z=h(x,y)z = h(x, y) (terrain, bump maps) ⟨1,0,hx⟩\langle 1, 0, h_x \rangle, ⟨0,1,hy⟩\langle 0, 1, h_y \rangle ⟨−hx,−hy,1⟩\langle -h_x, -h_y, 1 \rangle
Parametric r(u,v)r(u, v) (spheres, tori, NURBS) rur_u, rvr_v ru×rvr_u \times r_v

The height-field formula is the cross product of the two tangents, the same vector as the normal of the tangent plane. Shaders compute hxh_x and hyh_y from a height texture with central differences, and normal maps store the result. The program compares the exact normal of a wavy terrain with the finite-difference one a shader would use.

python · try it yourself
import numpy as np

h = lambda x, y: 0.5 * np.sin(2*x) * np.cos(y)
hx = lambda x, y: np.cos(2*x) * np.cos(y)              # partial derivatives by hand
hy = lambda x, y: -0.5 * np.sin(2*x) * np.sin(y)

def unit(v):
    return v / np.linalg.norm(v)

x, y = 0.3, 1.1
exact = unit(np.array([-hx(x, y), -hy(x, y), 1.0]))
for texel in [0.1, 0.01, 0.001]:
    dx = (h(x + texel, y) - h(x - texel, y)) / (2 * texel)
    dy = (h(x, y + texel) - h(x, y - texel)) / (2 * texel)
    approx = unit(np.array([-dx, -dy, 1.0]))
    angle = np.degrees(np.arccos(min(1.0, float(exact @ approx))))
    print(f"texel {texel:<6} normal {np.round(approx, 5)}  error {angle:.6f} degrees")
print("exact normal", np.round(exact, 5))
texel 0.1    normal [-0.33928  0.22917  0.91234]  error 0.122420 degrees
texel 0.01   normal [-0.34124  0.22935  0.91157]  error 0.001226 degrees
texel 0.001  normal [-0.34126  0.22935  0.91156]  error 0.000012 degrees
exact normal [-0.34126  0.22935  0.91156]

Splines and constant-speed motion

A Catmull-Rom spline passes through a list of points P0,P1,P2,…P_0, P_1, P_2, \ldots; the segment between P1P_1 and P2P_2 is the cubic

p(t)=12[2P1+(P2−P0)t+(2P0−5P1+4P2−P3)t2+(−P0+3P1−3P2+P3)t3],0≤t≤1p′(0)=P2−P02,p′(1)=P3−P12\begin{aligned} p(t) &= \tfrac{1}{2}\left[2P_1 + (P_2 - P_0)t + (2P_0 - 5P_1 + 4P_2 - P_3)t^2 + (-P_0 + 3P_1 - 3P_2 + P_3)t^3\right], \qquad 0 \le t \le 1 \\ p'(0) &= \frac{P_2 - P_0}{2}, \qquad p'(1) = \frac{P_3 - P_1}{2} \end{aligned}

Neighbouring segments share their end tangents, so the path is C1C^1: position and velocity are continuous, with no kinks. But moving tt at a constant rate does not give constant speed, since ∣p′(t)∣\lvert p'(t) \rvert varies. The fix is arc-length reparametrisation: compute s(t)=∫0t∣p′(τ)∣ dτs(t) = \int_0^t \lvert p'(\tau) \rvert \, d\tau, then invert it to find the tt that lies a given distance along the curve.

python · try it yourself
import numpy as np

P = np.array([[0, 0], [1, 2], [4, 3], [6, 0]], dtype=float)
def p(t):
    P0, P1, P2, P3 = P
    return 0.5 * (2*P1 + (P2 - P0)*t + (2*P0 - 5*P1 + 4*P2 - P3)*t**2 + (-P0 + 3*P1 - 3*P2 + P3)*t**3)
def dp(t):
    P0, P1, P2, P3 = P
    return 0.5 * ((P2 - P0) + 2*(2*P0 - 5*P1 + 4*P2 - P3)*t + 3*(-P0 + 3*P1 - 3*P2 + P3)*t**2)

t = np.linspace(0, 1, 2001)
speed = np.linalg.norm([dp(ti) for ti in t], axis=1)
s = np.concatenate([[0], np.cumsum((speed[1:] + speed[:-1]) / 2 * np.diff(t))])   # trapezoid
print("endpoints:", p(0.0), p(1.0), "  tangents:", dp(0.0), dp(1.0))
print(f"segment length = {s[-1]:.4f},  speed ranges {speed.min():.3f} .. {speed.max():.3f}")
for frac in [0.25, 0.5, 0.75]:
    t_frac = np.interp(frac * s[-1], s, t)                  # invert s(t)
    print(f"{frac:.0%} of the length: t = {t_frac:.4f}  (naive t = {frac})  point {np.round(p(t_frac), 3)}")
endpoints: [1. 2.] [4. 3.]   tangents: [2.  1.5] [ 2.5 -1. ]
segment length = 3.2646,  speed ranges 2.500 .. 3.656
25% of the length: t = 0.2672  (naive t = 0.25)  point [1.684 2.444]
50% of the length: t = 0.4937  (naive t = 0.5)  point [2.416 2.804]
75% of the length: t = 0.7259  (naive t = 0.75)  point [3.195 3.042]

In software

  • Path tracing and real-time GI. Blender's Cycles, film renderers and real-time ray tracing estimate the rendering integral by Monte Carlo with importance sampling, then denoise the result.
  • Normal and bump mapping. Height maps become normal maps by finite differences; procedural terrain and SDF raymarchers get normals from the gradient of the height or distance function.
  • Splines. Camera rails, racing lines, animation curves (Bézier in UI and CSS, Catmull-Rom in games) and font outlines; arc-length tables give constant-speed movement along them.

Exercises

Exercise 1: A terrain normal

Find the unit normal of the height field h(x,y)=x2+2yh(x, y) = x^2 + 2y at (1,0)(1, 0).

Answer

n=(−2,−2,1)/3=(−0.6667,−0.6667,0.3333)n = (-2, -2, 1)/3 = (-0.6667, -0.6667, 0.3333).

Solution
hx=2x=2,hy=2⟨−hx,−hy,1⟩=⟨−2,−2,1⟩,length 4+4+1=3\begin{aligned} &h_x = 2x = 2, \qquad h_y = 2 \\ &\langle -h_x, -h_y, 1 \rangle = \langle -2, -2, 1 \rangle, \qquad \text{length } \sqrt{4 + 4 + 1} = 3 \end{aligned}

Exercise 2: Irradiance from a uniform sky

A sky has the same radiance LL in every direction. Show that the irradiance on a horizontal surface is E=πLE = \pi L.

Answer

E=πLE = \pi L.

Solution
E=∫02π∫0π/2L⋅cos⁡θ⋅sin⁡θ dθ dφ=2π⋅L⋅[sin⁡2θ2]0π/2=2π⋅L⋅12=πLE = \int_0^{2\pi} \int_0^{\pi/2} L \cdot \cos\theta \cdot \sin\theta \, d\theta \, d\varphi = 2\pi \cdot L \cdot \left[\frac{\sin^2\theta}{2}\right]_0^{\pi/2} = 2\pi \cdot L \cdot \frac{1}{2} = \pi L

This π\pi is why a perfectly diffuse (Lambertian) BRDF is albedo/π\text{albedo}/\pi: it makes reflected radiance equal albedo×L\text{albedo} \times L.

Exercise 3: A Catmull-Rom tangent

The points P0=(0,0)P_0 = (0, 0), P1=(1,2)P_1 = (1, 2), P2=(3,3)P_2 = (3, 3) are consecutive on a Catmull-Rom spline. What is the velocity of the curve as it passes P1P_1?

Answer

(1.5,1.5)(1.5, 1.5).

Solution

The tangent at P1P_1 is (P2−P0)/2=((3,3)−(0,0))/2=(1.5,1.5)(P_2 - P_0)/2 = ((3, 3) - (0, 0))/2 = (1.5, 1.5), for both the segment arriving at P1P_1 and the one leaving it, which is what makes the spline C1C^1.

Exercise 4: Monte Carlo on the hemisphere (code)

Estimate ∫Ωcos⁡3θ dω\int_\Omega \cos^3\theta \, d\omega with 100,000 uniform hemisphere samples (seed 3) and compare it with the exact value.

Answer

Exact: π/2≈1.5708\pi/2 \approx 1.5708; the estimate is 1.571, off by 0.0002.

Solution
∫02π∫0π/2cos⁡3θsin⁡θ dθ dφ=2π⋅[−cos⁡4θ4]0π/2=2π⋅14=π2\int_0^{2\pi} \int_0^{\pi/2} \cos^3\theta \sin\theta \, d\theta \, d\varphi = 2\pi \cdot \left[-\frac{\cos^4\theta}{4}\right]_0^{\pi/2} = 2\pi \cdot \frac{1}{4} = \frac{\pi}{2}

With uniform hemisphere sampling cos⁡θ\cos\theta is uniform on [0,1][0, 1] and the pdf is 1/(2π)1/(2\pi), so the estimator is the mean of 2π⋅u32\pi \cdot u^3.

python · try it yourself
import numpy as np
rng = np.random.default_rng(3)
u = rng.random(100_000)
est = float(np.mean(2 * np.pi * u**3))
print(round(est, 4), round(np.pi / 2, 4), round(abs(est - np.pi / 2), 4))
1.571 1.5708 0.0002

Test yourself

Why does cosine-weighted sampling reduce noise when estimating the rendering integral?

  1. It uses fewer samples
  2. Its pdf is proportional to the cos⁡θ\cos\theta factor of the integrand, so the ratio f/pdf⁡f/\operatorname{pdf} varies less
  3. It makes the integral exact for every scene
  4. It removes the BRDF

What is the (unnormalised) normal of the height field z=h(x,y)z = h(x, y)?

  1. ⟨hx,hy,1⟩\langle h_x, h_y, 1 \rangle
  2. ⟨−hx,−hy,1⟩\langle -h_x, -h_y, 1 \rangle
  3. ⟨hx,hy,0⟩\langle h_x, h_y, 0 \rangle
  4. ⟨1,1,h⟩\langle 1, 1, h \rangle

Moving the spline parameter tt at a constant rate gives a varying speed. What fixes that?

  1. Normalising the control points
  2. Reparametrising by arc length s(t)=∫∣p′∣ dts(t) = \int \lvert p' \rvert \, dt
  3. Using a higher-degree spline
  4. Clamping tt