GAMES104 Modern Game Engine - The Mathematical Magic of Light and Materials in Rendering

Words: 2059

There are quite a few things I didn’t fully understand; I’ll need to go through them again later.

Introduction: The Essential Challenge of Rendering

This lecture explores the core of modern game engine rendering — the mathematical relationship between light, materials, and shaders (Shader). It is one of the most complex and intricate systems in a game engine.

The essence of rendering is simulating the propagation of photons: photons are emitted from light sources, and after reflection, absorption, and refraction they enter the human eye. To solve this process in real time under limited hardware compute, graphics researchers and engineers around the world have spent the past decades proposing countless ingenious “hacks” (engineering compromises), collectively building today’s real-time rendering technology stack.

The Rendering Equation

35 years ago, Kajiya proposed the famous Rendering Equation, now regarded as the most fundamental theoretical framework in graphics:

$$ L_o(x, \vec w) = L_e(x, \vec w) + \int_\Omega f_r(x, \vec w', \vec w) L_i(x, \vec w') (\vec w' \cdot \vec n) d\vec w' $$

Where:

  • $L_o(x, \vec w)$ is the outgoing light at position $ x $ and direction $\vec w$.
  • $L_e(x, \vec w)$ is the light emitted at the same position and direction.
  • $\int_\Omega … d\vec w’$ is the infinitesimal sum over the hemisphere of incident directions.
  • $f_r(x, \vec w’, \vec w)$ is the fraction of light reflected at that point from the incident direction to the outgoing direction.
  • $L_i(x, \vec w’)$ is the incident light at that point, at position and direction $ \vec w’ $.
  • $(\vec w’ \cdot \vec n)$ is the attenuation of incident light caused by the incident angle.

—— Rendering Equation - Wikipedia

Core contradiction: this equation describes perfect physical truth, yet it is extremely difficult to solve in real time. The work of game engine engineers over the past 30 years is essentially the search for various engineering approximate solutions to this equation.

The Three Major Challenges of Real-Time Rendering

Real-time rendering faces three core challenges:

Visibility To Light

That is, the shadow problem. Determining whether a point in the scene can be directly lit by a light source seems simple, but it is in fact one of the thorniest problems in graphics.

Complexity of Light

Real-world lighting comes from the spherical space (Sphere) in every direction, not from simple directional or point lights. How to handle area lights (Area Light), ambient light (Ambient Light), and the different frequency (high/low frequency) information of light is a huge challenge.

Even if we know the incoming lighting from every direction (a spherical function), computing its integral (convolution) with the material BRDF is still enormously expensive. In real time, we cannot densely sample and integrate over the sphere.

Global Illumination

In the real world, a surface that is lit becomes a new light source itself (Color Bleeding), and light bounces around the scene infinitely many times (Bouncing).

This leads to:

  • Infinitely many light sources in the scene
  • Challenge three (indirect light) aggravates challenge one (visibility) and challenge two (complexity of light)

The Basic Render Pipeline: Early Engineering Compromises

Faced with such complex mathematical theory, early graphics engineers resorted to extremely pragmatic “brute-force” tricks — and these simple hacks ended up laying the foundation of real-time rendering.

Simplified Lighting Models

Complex spherical lighting is decomposed into three categories:

  • Dominant Light: directional lights / point lights / spotlights
  • Ambient Light: a constant standing in for indirect light from all directions
  • Environment Map: a Cubemap (6 textures) capturing high-frequency reflection information of the surrounding environment

Blinn-Phong Material Model

A victory for the empiricists. It does not pursue strict physical correctness, but is based on observation:

  • Diffuse: light scatters uniformly, computed with $\cos\theta$
  • Specular: a power function controls the width of the reflection lobe (Lobe)

Flaw: energy non-conservative; in ray-traced scenes light energy explodes (brightness grows without bound).

Shadow Map Technology

The classic solution to the visibility problem, with the core idea of trading space for time:

  1. Render a depth map (Depth Map) from the light’s point of view
  2. When rendering from the camera’s point of view, project each pixel back into light space and compare depths
  3. If the depth is greater than the value stored in the Shadow Map, the point is in shadow

Key problems:

  • Self-occlusion: aliasing caused by insufficient precision, solved by adding a bias, but this produces “floating shadows” (Peter Panning)
  • Sampling rate mismatch: the difference in sampling rate between the light’s view and the camera’s view causes various artifacts

Global Illumination (GI) and Precomputation Techniques

AAA games pursue realism and must solve indirect lighting. The core idea is precomputation: store the results of offline computation and query them directly at runtime.

Spherical Harmonics (SH)

The lighting function defined on the sphere (a spherical signal) is compressed using the idea of Fourier series:

  • Represent the spherical function with a set of orthogonal basis functions (similar to $\sin/\cos$ functions)
  • Storing only the first $n$ orders of coefficients (e.g. 4 parameters for order 1, 9 parameters for order 2) is enough to reconstruct the approximate lighting direction

Advantages:

  • Extremely high compression ratio: 12 parameters (RGB×4) can express the ambient lighting at a point
  • Simplified convolution: the convolution (integral) of two functions on the sphere reduces to a dot product of SH coefficients
  • Supports Diffuse and Specular: choose different orders according to precision requirements

Lightmap

Bake the global illumination of static objects into 2D textures (Atlas):

  • Parameterization: unwrap 3D geometry into 2D UV space
  • Baking: perform offline ray-tracing computation on a Light Farm (render farm)
  • At runtime: sample the Lightmap directly for indirect light and add it to real-time lighting

Drawbacks:

  • Only supports static objects and static light sources
  • Baking takes a very long time (half an hour to an hour)
  • Consumes a lot of memory (tens to hundreds of MB)

Light Probe

Scatter sample points through space, each storing lighting information encoded as SH:

  • Automatic generation: modern engines automatically generate Probe distributions (along player paths, expanding over geometric surfaces)
  • Lighting for dynamic objects: dynamic objects are shaded by interpolating the lighting of surrounding Probes
  • Reflection Probe: dedicated to high-frequency reflections, storing high-resolution Cubemaps

Trade-offs vs. Lightmap:

  • Lightmap: high precision, rich detail (soft shadows, Color Bleeding), but static only
  • Light Probe: supports dynamic objects and runtime updates, but low precision and cannot express fine contact shadows

Physically Based Rendering (PBR)

Microfacet Theory

A rough surface is modeled as consisting of countless tiny mirrors (Microfacets):

  • Roughness: controls how dispersed the distribution of microfacet normals is
  • Metallic: distinguishes metals (reflect colored light) from non-metals (dominated by diffuse reflection)

The Cook-Torrance Reflection Model

The standard model for modern PBRSpecular; the BRDF is a product of three terms:

$$ f_r = \frac{D \cdot F \cdot G}{4(\omega_o \cdot n)(\omega_i \cdot n)} $$
  • D (Normal Distribution Function, NDF): the distribution of microfacet normals, most commonly the GGX (Trowbridge-Reitz) distribution

    • Characteristics: sharp peak (good high-frequency behavior), long trailing tail (good low-frequency behavior) — like a good speaker with “crisp highs and deep lows”
  • F (Fresnel Term): describes the increase in reflectance as the angle between the view direction and the surface approaches grazing angle (Grazing Angle)

    • Classic approximation: Schlick approximation $F = F_0 + (1-F_0)(1-\cos\theta)^5$
  • G (Geometry Term): the geometric occlusion term, computing self-shadowing between microfacets (Shadowing-Masking)

    • Smith model: computes occlusion for the incoming and outgoing directions separately based on the same Roughness distribution

Disney Principled BRDF

The PBR design principles proposed by Disney, which deeply influenced the design philosophy of game engines:

  1. Intuitive: parameters must match artists’ intuition (e.g. “metallic”, “roughness” rather than physical index of refraction)
  2. Minimal parameters: the fewer the better, usually kept to 2-3
  3. Normalized range: parameters should preferably lie in $[0,1]$
  4. Robustness: any combination of parameters should not produce invalid or bizarre results
  5. Creative flexibility: a small number of out-of-range values are allowed for special artistic effects

Mainstream PBR Workflows

  1. Specular-Glossiness (SG):

    • Parameters: Diffuse Map + Specular Map (RGB controls Fresnel color) + Glossiness Map
    • Pros: flexible, good for expressing colored metals (e.g. gold, copper)
    • Cons: easy to misconfigure, leading to energy non-conservation
  2. Metallic-Roughness (MR):

    • Parameters: Base Color + Metallic Map + Roughness Map
    • Mechanism: Metallic acts as a mask, interpolating between metal (using Base Color as Specular) and non-metal (Specular is gray)
    • Pros: hard to get wrong, intuitive, the industry mainstream
    • Cons: a white line artifact may appear at the transition between metal and non-metal

Image-Based Lighting (IBL)

A technique that combines environment lighting (Environment Map) with PBR materials, solving the integral problems of specular reflection and diffuse reflection from the environment.

Diffuse Irradiance Map

  • Precomputation: convolve the environment map with the Lambertian BRDF (a constant) to produce a low-frequency diffuse lookup map
  • At runtime: sample directly along the normal direction, no real-time integration needed

Specular Prefiltered Mipmap

  • Roughness layering: store prefiltered environment maps for different roughness values (0 to 1) in different mipmap levels of the Cubemap
    • Low roughness (smooth): high-frequency information, stored in high-precision mipmaps (low levels)
    • High roughness (rough): low-frequency information, stored in low-precision mipmaps (high levels)
  • BRDF LUT: use a 2D lookup texture to precompute the integral of the Fresnel and geometry terms, parameterized by Roughness and Cosine Theta

Essence: turning the integral computation of the rendering equation entirely into texture lookups, enabling efficient dynamic environment lighting.


Advanced Shadow Techniques

Cascade Shadow Maps (CSM)

Solves the problem of insufficient shadow resolution in large scenes:

  • Cascades: divide the view frustum into several cascades by distance from the camera (e.g. 0-10m, 10-30m, 30-100m)
  • Multiple Shadow Maps: generate a Shadow Map of different resolution for each cascade — high precision near, low precision far
  • ** blend between cascades**: smooth interpolation at cascade boundaries avoids hard edges

Cost: requires rendering the scene multiple times (usually 4), making it one of the most expensive modules in the render pipeline (typically 4-5 ms).

Soft Shadows

  • PCF (Percentage Closer Filtering): sample neighboring depths on the Shadow Map and blur with multiple samples to simulate the penumbra
  • PCSS (Percentage Closer Soft Shadows): dynamically adjust the sampling kernel size based on the distance from the object to the light (occluder distance), producing distance-dependent soft/hard shadows
  • VSSM (Variance Soft Shadow Map): uses Chebyshev’s inequality and a two-channel Shadow Map (storing depth and depth squared) to estimate the probability of visibility from variance, giving fast approximate soft shadows

Virtual Shadow Map

A new technique introduced by Unreal Engine 5, solving the low spatial utilization of CSM:

  • Virtual paging: virtualize a huge shadow texture space, allocating and generating Shadow Map tiles only for the actually visible regions
  • Dynamic allocation: dynamically decide which regions need high-resolution shadows based on the camera view, achieving consistent high-precision shadows across the whole scene

Real-Time Ray Tracing

Hardware acceleration (RTX/DRX) makes real-time ray tracing possible:

  • Current usage: mainly used for reflection and shadows, rather than full GI
  • Future direction: combined with denoising to achieve real-time global illumination (e.g. UE5’s Lumen, which combines SDF, Voxel, Screen Space GI and other techniques)

Uber Shader and Shader Variants

Modern engines face the problem of shader explosion:

  • Uber Shader: write one giant shader containing all features, with branches controlled by macros (Macro)
  • Shader Permutation (variants): at compile time, generate all possible shader combinations based on material properties, light types, platform, etc. (e.g. 165 templates can produce 70,000+ concrete shaders)
  • Cross-platform compilation: use intermediate formats such as SPIR-V and translate uniformly to each platform’s shader language — HLSL, GLSL, Metal, PSL, etc.

Conclusion

The history of real-time rendering technology is a history of engineering innovation that seeks a balance between physical truth and real-time performance:

  1. The foundational era: through the combination of Blinn-Phong + Shadow Map + Environment Map, minimal hacks achieved acceptable real-time rendering
  2. The GI era: through precomputation techniques such as Lightmap, Spherical Harmonics, and Light Probe, trading space for time to achieve static global illumination
  3. The PBR era: based on Microfacet theory and the Cook-Torrance model, a unified material standard (Metallic-Roughness) was established, achieving physically correct lighting response
  4. The IBL era: through prefiltered environment maps, complex integral computations became texture lookups, enabling efficient environment lighting
  5. Modern/future: hardware ray tracing and real-time GI techniques (Lumen, etc.) are breaking the constraints of precomputation, moving toward a fully dynamic, fully realistic goal

Key takeaway: game engine development is not about chasing mathematical perfection, but about creating believable and beautiful visuals under limited compute through reasonable assumptions, simplifications, and precomputation.

References

This post contains some AI-assisted content, reviewed and edited by the author before publishing.
This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...