Algorithm Search⌘K

Data structureadvanced

Irradiance volume

Also called light probe grid.

A 3D grid of light probes that store the incoming irradiance by direction, interpolated to light moving objects with baked global illumination.

Time
Θ(n) bakeΘ(1) sample · set_probe
Space
Θ(n) total
Where
n = the number of probes in the grid
Properties
not concurrentnot externalnot persistent
Origin
Gene Greger, Peter Shirley, Philip M. Hubbard, Donald P. Greenberg, 1998

An irradiance volume stores the diffuse lighting of a scene at the points of a regular 3D grid. Each grid point, called a probe, holds the irradiance that arrives there as a function of the surface normal, usually as nine spherical harmonic coefficients per color channel, the same encoding as an irradiance environment map. To light a point of a moving object, the renderer finds the grid cell around it, blends the coefficients of the 8 corner probes with trilinear weights, and evaluates the blend at the normal. The probes are baked offline by a global illumination renderer, or updated at run time by ray tracing. A query costs the same for any grid size. The weakness is that the blend ignores walls: a probe on the far side of a thin wall still contributes, so light leaks into dark rooms.

In plain words

Before the game runs, place many small light meters in a 3D lattice through the level. Each meter records how bright the light is from every direction around it, in a compact form of a few numbers. When a character walks through the level, look at the eight meters around it, mix their records by how close the character is to each, and read the mix in the direction its surface faces. The character then gets the bounced light of the room, the colors of nearby walls and the darkness of corners, without any ray tracing at run time. Meters on the other side of a wall do not know about the wall, which is the main source of errors.

The abstract type

An irradiance volume is a map from a point pp in a box of space and a unit normal nn to an irradiance E(p,n)E(p, n), with these operations:

  • set_probe(i, j, k, c): store the coefficients cc of the irradiance at probe (i,j,k)(i, j, k).
  • bake(f): call set_probe with f(position)f(\text{position}) for every probe, for example the projection of the radiance that a renderer computes there.
  • sample(p, n): the interpolated irradiance at pp for the normal nn.
  • sample_coeffs(p): the interpolated coefficients at pp, for shaders that evaluate many normals at one point.

The defined result of sample is the trilinear interpolation of the probe irradiance functions, with points outside the box clamped to the box. How close that is to the true irradiance depends on the scene and on the spacing, not on the data structure.

Representation

The grid has X×Y×ZX \times Y \times Z probes, at least 2 along each axis, with an origin oo and a spacing hh; probe (i,j,k)(i, j, k) is at o+h(i,j,k)o + h(i, j, k). Each probe holds nine numbers ElmE_{lm} per color channel: the spherical harmonic coefficients of the radiance, already multiplied by the clamped cosine factors π\pi, 2π/32\pi/3 and π/4\pi/4 of bands 0, 1 and 2, so that E(n)=∑lmElmYlm(n)E(n) = \sum_{lm} E_{lm} Y_{lm}(n). The invariant is that the array has XYZX Y Z entries of nine numbers each, and that entry (i,j,k)(i, j, k) belongs to the probe at that position. On the GPU, the coefficients usually go into a few 3D textures, so that the hardware does the trilinear blend in one fetch per texture.

Operations

  1. SAMPLE(V, p, n)
  2. 1g ← clamp((p - o) / h, 0, (X, Y, Z) - 1) ▷ per axis, in probe units
  3. 2i ← min(⌊g⌋, (X, Y, Z) - 2); f ← g - i ▷ per axis: the cell and the place in it
  4. 3c ← nine zeros
  5. 4for each corner (a, b, d) in {0, 1}^3
  6. 5w ← (f_x or 1 - f_x) · (f_y or 1 - f_y) · (f_z or 1 - f_z) ▷ f if the bit is 1
  7. 6c ← c + w · V.probe[i_x + a][i_y + b][i_z + d]
  8. 7return Σ_m c_m Y_m(n)

Sample. Line L1 converts the point to grid units and clamps it to the box. Line L2 finds the lowest corner of the cell; the minimum keeps a point on the last plane inside the last cell. Lines L4 to L6 blend the 8 corner probes with the trilinear weights, which are nonnegative and add up to 1. Line L7 evaluates the blended coefficients at the normal, nine multiplications per channel. Cost: O(1)O(1).

Set probe and bake. set_probe writes nine numbers per channel. bake calls it once per probe, Θ(n)\Theta(n) calls for nn probes; the cost of the renderer that computes each probe is separate and dominates in practice.

Example

A 2×2×22 \times 2 \times 2 grid with origin (0,0,0)(0, 0, 0) and spacing 2 m. The four probes at x=0x = 0 see a uniform sky of radiance 1, so their irradiance is π\pi for every normal. The four probes at x=2x = 2 see only a point light of unit power straight above, so their irradiance is 17/1617/16 for the normal +z+z, 3/323/32 for +x+x and 1/161/16 for −z-z (the nine coefficient values of the irradiance environment map page). Sample at p=(0.5,1,1)p = (0.5, 1, 1):

step line work result
1 L1 g=(0.25,0.5,0.5)g = (0.25, 0.5, 0.5) inside the box
2 L2 i=(0,0,0)i = (0, 0, 0), f=(0.25,0.5,0.5)f = (0.25, 0.5, 0.5) the only cell
3 L4, L5 the 4 corners with a=0a = 0 get 0.75⋅0.5⋅0.5=0.18750.75 \cdot 0.5 \cdot 0.5 = 0.1875, the 4 with a=1a = 1 get 0.06250.0625 weights add up to 1
4 L6 c=0.75 csky+0.25 clightc = 0.75\, c_{\text{sky}} + 0.25\, c_{\text{light}} nine numbers
5 L7, n=+zn = +z 0.75π+0.25⋅17/160.75 \pi + 0.25 \cdot 17/16 2.6218
6 L7, n=−zn = -z 0.75π+0.25⋅1/160.75 \pi + 0.25 \cdot 1/16 2.3718
7 L7, n=+xn = +x 0.75π+0.25⋅3/320.75 \pi + 0.25 \cdot 3/32 2.3796

The result is linear in the probe data, so the sky and the light could be baked into separate volumes and added. Now put a wall at x=1x = 1 and keep the probes: a point at x=0.8x = 0.8, on the sky side of the wall, still gets 40%40\% of the light probes, because line L5 does not know about the wall. That is the light leak, shown in the tests as a measurement of the failure.

Correctness

The invariant is that the probe array has XYZX Y Z entries of nine numbers, and only set_probe changes an entry. The proof shows that line L2 always gives a valid cell with fractions in [0,1][0, 1], that lines L3 to L6 equal the sum over all probes of their coefficients times a product of three hat functions, that the weights are nonnegative and add up to 1, that the sample at a probe is that probe, that fields of coefficients that are affine in position are reproduced exactly, and that the result is linear in the probe data. All of these are proved properties. The tests check each of them, and compare random sequences of stores and samples with a dict model and a brute force sum over all probes.

Whether the sample equals the true irradiance is a different question. The true irradiance field is smooth in open space but can change sharply at shadow edges and across occluders, and a grid with spacing hh cannot represent changes on a scale smaller than hh. That error is a property of the scene, and the usual fix is a finer grid or visibility data, not a change to the blend.

Proof: Correctness of the irradiance volume samplefull

Setting. The volume has X×Y×ZX \times Y \times Z probes with X,Y,Z≥2X, Y, Z \ge 2, an origin oo and a spacing h>0h > 0. Probe (i,j,k)(i, j, k) sits at o+h(i,j,k)o + h (i, j, k) and holds a vector cijk∈R9c_{ijk} \in \mathbb{R}^9 of irradiance coefficients. For a point pp, let ga=clamp⁡((pa−oa)/h,0,Da−1)g_a = \operatorname{clamp}((p_a - o_a)/h, 0, D_a - 1) for each axis aa, where D=(X,Y,Z)D = (X, Y, Z). Define the hat function Λ(u)=max⁡(0,1−∣u∣)\Lambda(u) = \max(0, 1 - |u|) and the reference blend

B(p)=∑i,j,kΛ(gx−i) Λ(gy−j) Λ(gz−k) cijk,B(p) = \sum_{i, j, k} \Lambda(g_x - i)\, \Lambda(g_y - j)\, \Lambda(g_z - k)\, c_{ijk},

the sum over every probe. The claims are in exact arithmetic.

Claim 1 (the cell). Line L2 gives ia∈{0,…,Da−2}i_a \in \{0, \dots, D_a - 2\} and fa=ga−ia∈[0,1]f_a = g_a - i_a \in [0, 1] for each axis.

Proof. Line L1 and the clamp give ga∈[0,Da−1]g_a \in [0, D_a - 1]. If ga<Da−1g_a < D_a - 1, then ia=⌊ga⌋≤Da−2i_a = \lfloor g_a \rfloor \le D_a - 2 and 0≤fa<10 \le f_a < 1. If ga=Da−1g_a = D_a - 1, the minimum gives ia=Da−2i_a = D_a - 2 and fa=1f_a = 1. In both cases ia≥0i_a \ge 0. □\square

Claim 2 (the blend is the reference blend). Lines L3 to L6 return B(p)B(p).

Proof. For one axis, Λ(ga−m)\Lambda(g_a - m) is nonzero only for ∣ga−m∣<1|g_a - m| < 1. By Claim 1, ga∈[ia,ia+1]g_a \in [i_a, i_a + 1], so only m=iam = i_a and m=ia+1m = i_a + 1 can give a nonzero value, with Λ(ga−ia)=1−fa\Lambda(g_a - i_a) = 1 - f_a and Λ(ga−ia−1)=1−(1−fa)=fa\Lambda(g_a - i_a - 1) = 1 - (1 - f_a) = f_a. So the triple sum in B(p)B(p) reduces to the 8 corners (ix+a,iy+b,iz+c)(i_x + a, i_y + b, i_z + c) with a,b,c∈{0,1}a, b, c \in \{0, 1\}, and each corner has the weight wabc=∏w_{abc} = \prod of ff or 1−f1 - f per axis. Line L5 computes exactly these weights and line L6 adds wabc cw_{abc}\, c of each corner to the output, which line L3 starts at 0. □\square

Claim 3 (partition of unity). The 8 weights are nonnegative and add up to 1, so if every probe holds the same vector cc, the sample is cc at every point, inside or outside the grid.

Proof. Each factor is in [0,1][0, 1] by Claim 1, so each product is too. The sum is ∏a((1−fa)+fa)=1\prod_a \big((1 - f_a) + f_a\big) = 1. □\square

Claim 4 (interpolation and exactness). At a probe position the sample equals that probe. If cijk=α+βxxi+βyyj+βzzkc_{ijk} = \alpha + \beta_x x_i + \beta_y y_j + \beta_z z_k for fixed vectors α,βa\alpha, \beta_a and the probe positions (xi,yj,zk)(x_i, y_j, z_k), then the sample at any pp inside the grid box is α+β⋅p\alpha + \beta \cdot p.

Proof. At a probe position, gag_a is an integer mam_a, so Λ(ga−m)=1\Lambda(g_a - m) = 1 for m=mam = m_a and 0 for every other integer mm, and B(p)=cmxmymzB(p) = c_{m_x m_y m_z}. For the affine case, inside the box ga=(pa−oa)/hg_a = (p_a - o_a)/h with no clamping. By Claim 3 the constant α\alpha is kept. For the term βxxi\beta_x x_i, sum out jj and kk with Claim 3, which leaves ∑iΛ(gx−i) βx(ox+hi)=βx(ox+h((1−fx)ix+fx(ix+1)))=βx(ox+hgx)=βxpx\sum_i \Lambda(g_x - i)\, \beta_x (o_x + h i) = \beta_x \big(o_x + h((1 - f_x) i_x + f_x (i_x + 1))\big) = \beta_x (o_x + h g_x) = \beta_x p_x. The other two axes are the same. □\square

Claim 5 (the irradiance). Line L7 returns ∑ijkwijk(p) Eijk(n)\sum_{ijk} w_{ijk}(p)\, E_{ijk}(n), where Eijk(n)=∑mcijk,mYm(n)E_{ijk}(n) = \sum_m c_{ijk, m} Y_m(n) is the irradiance that probe (i,j,k)(i, j, k) gives for the normal nn, and the map from the probe data to the result is linear.

Proof. The evaluation c↦∑mcmYm(n)c \mapsto \sum_m c_m Y_m(n) is linear, so it commutes with the weighted sum of Claim 2. Each weight depends only on pp, not on the data, so the whole map from the probe vectors to the result is linear. □\square

So the sample is the trilinear interpolation of the probe irradiance functions, which is what the page defines. It makes no claim that this equals the true irradiance at pp: that needs the irradiance field to be close to trilinear between probes, and it fails across occluders (the light leak of the page), which is a property of the field, not of the code.

Cost. Lines L1 and L2 do a constant number of operations per axis, lines L4 to L6 visit 8 corners with 9 coefficients each, and line L7 evaluates nine basis functions, so sample is O(1)O(1), independent of the number of probes. set_probe writes 9 numbers, and the memory is 9XYZ9 X Y Z numbers per color channel. ■\blacksquare

Complexity

The model is the real RAM, with n=XYZn = XYZ probes and nine coefficients per channel.

operation time note
sample Θ(1)\Theta(1) 8 probes, 72 multiply-adds per channel, 9 more for the evaluation
sample_coeffs Θ(1)\Theta(1) the same without line L7
set_probe Θ(1)\Theta(1) 9 writes per channel
bake Θ(n)\Theta(n) calls to the probe renderer, which cost far more than the writes
space Θ(n)\Theta(n) 27n27 n numbers for three color channels

For scale, a grid of 32×16×32=1638432 \times 16 \times 32 = 16384 probes with 27 half precision numbers each needs 884736884736 bytes, under 1 MB. A light map of the same level would need texels on every surface, and still could not light objects that move.

Variants

  • Other probe encodings. Two bands of spherical harmonics (four numbers per channel) for a smaller grid, an ambient cube of six colors along the axes, or a small octahedral map per probe for sharper directional detail.
  • Visibility-aware blending. Store with each probe some statistics of the distance to nearby surfaces, and lower the weight of probes that the shaded point cannot see. Majercik and coauthors do this in DDGI and update the probes each frame with ray tracing.
  • Adaptive grids. An octree or a two-level grid puts more probes where the lighting changes fast, at the cost of a search per query and of seams between levels.
  • Irregular probes. Probes placed by hand or by a tool, with a tetrahedral mesh between them and barycentric weights; the query first finds the tetrahedron that contains the point.
  • Radiance probes. Store radiance instead of irradiance, as cube maps, for glossy reflections. These are usually fewer and placed by hand, and they need parallax correction.
  • Moving the sample point. Offset the point along the normal, or toward the viewer, by a part of the spacing before line L1, which reduces leaks and self-shadowing (a heuristic).

When to use it

Use an irradiance volume for the diffuse light on dynamic objects in a scene whose lighting is baked or slowly changing, and as the diffuse term of whole levels when the geometry or the time of day changes too much for light maps. It is cheap to query and to store, and it needs no unique texture layout. Avoid it alone where sharp contact shadows or thin walls matter, unless the probes carry visibility data; combine it with ambient occlusion for small scale darkening. For static surfaces with fine detail, light maps give sharper results.

Pitfalls

  • Light leaks. Line L5 gives weight to probes behind a wall. Thin walls, floors between stories and probes inside geometry give bright spots in dark rooms. Keep probes out of solid geometry, use visibility data, or make walls thicker than the spacing.
  • Probes inside geometry. A probe baked inside a wall sees only back faces and stores black or garbage. It then darkens everything around it through line L6. Detect such probes during the bake and move or disable them.
  • Clamping at the box. Line L1 clamps points outside the box to its faces, so an object that leaves the volume keeps the light of the boundary. Give the volume a margin or blend to a fallback.
  • Ringing. Strong, small lights give spherical harmonic coefficients whose evaluation in line L7 can go negative for normals away from the light. Window the coefficients, or clamp the result at zero, and test with the brightest light of the scene.
  • Cell index at the far edge. Without the minimum in line L2, a point exactly on the last plane reads one probe past the end of the array.
  • Blending in the wrong space. Blend linear radiometric values. Blending after tone mapping or gamma encoding does not give the interpolated irradiance.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

irradiance_volume.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/irradiance-volume/. The authors are listed in prov/CE3Y53.jsonl.

"""An irradiance volume: a regular 3D grid of probes that store irradiance.

Each probe holds the nine spherical harmonic coefficients E_lm of the
irradiance at its position (the coefficients are already convolved with the
clamped cosine, so E(n) = sum of E_lm Y_lm(n)). A query at a point p and a
unit normal n blends the coefficients of the 8 probes of the cell around p
with trilinear weights and evaluates the blend at n. Points outside the grid
are clamped to its boundary. Visibility is ignored, which is why light can
leak through thin walls.

Precondition: at least 2 probes along each axis, spacing > 0. Cost: O(1) per
query (8 probes of 9 coefficients) and Theta(X Y Z) memory for X Y Z probes.
"""

import math

Vec = tuple[float, float, float]

Y0 = 0.5 / math.sqrt(math.pi)
Y1 = math.sqrt(3.0 / (4.0 * math.pi))
Y2 = 0.5 * math.sqrt(15.0 / math.pi)
Y20 = 0.25 * math.sqrt(5.0 / math.pi)
Y22 = 0.25 * math.sqrt(15.0 / math.pi)
A_HAT = (math.pi, 2.0 * math.pi / 3.0, math.pi / 4.0)
BAND = (0, 1, 1, 1, 2, 2, 2, 2, 2)


def sh9(d: Vec) -> list[float]:
    """The nine real spherical harmonics at d, z as the polar axis."""
    x, y, z = d
    return [Y0, Y1 * y, Y1 * z, Y1 * x, Y2 * x * y, Y2 * y * z,
            Y20 * (3.0 * z * z - 1.0), Y2 * x * z, Y22 * (x * x - y * y)]


def irradiance_coeffs(radiance_coeffs: list[float]) -> list[float]:
    """Convolve nine radiance coefficients L_lm with the clamped cosine: E_lm = A_hat_l L_lm."""
    return [A_HAT[BAND[k]] * radiance_coeffs[k] for k in range(9)]


def eval_sh(coeffs: list[float], n: Vec) -> float:
    """The function with these nine coefficients, at the direction n."""
    return sum(c * y for c, y in zip(coeffs, sh9(n)))


class IrradianceVolume:
    """A grid of dims[0] by dims[1] by dims[2] probes at origin + spacing * (i, j, k)."""

    def __init__(self, origin: Vec = (0.0, 0.0, 0.0), spacing: float = 1.0,
                 dims: tuple[int, int, int] = (2, 2, 2)) -> None:
        if min(dims) < 2 or spacing <= 0.0:
            raise ValueError("need at least 2 probes per axis and a positive spacing")
        self.origin = origin
        self.spacing = spacing
        self.dims = dims
        nx, ny, nz = dims
        self.probes = [[[[0.0] * 9 for _ in range(nz)] for _ in range(ny)] for _ in range(nx)]

    def probe_position(self, i: int, j: int, k: int) -> Vec:
        o, h = self.origin, self.spacing
        return (o[0] + h * i, o[1] + h * j, o[2] + h * k)

    def set_probe(self, i: int, j: int, k: int, coeffs: list[float]) -> None:
        """Store nine irradiance coefficients at probe (i, j, k)."""
        if len(coeffs) != 9:
            raise ValueError("a probe holds nine coefficients")
        self.probes[i][j][k] = [float(c) for c in coeffs]

    def probe(self, i: int, j: int, k: int) -> list[float]:
        return list(self.probes[i][j][k])

    def bake(self, coeffs_at) -> None:
        """Fill every probe with coeffs_at(position), for example a projection of the radiance there."""
        nx, ny, nz = self.dims
        for i in range(nx):
            for j in range(ny):
                for k in range(nz):
                    self.set_probe(i, j, k, coeffs_at(self.probe_position(i, j, k)))

    def cell_and_weights(self, p: Vec) -> tuple[tuple[int, int, int], Vec]:
        """The lowest corner of the cell of p and the fractions inside it, after clamping."""
        base, frac = [], []
        for a in range(3):
            g = (p[a] - self.origin[a]) / self.spacing  # @line L1
            g = min(max(g, 0.0), self.dims[a] - 1.0)
            i = min(int(math.floor(g)), self.dims[a] - 2)  # @line L2
            base.append(i)
            frac.append(g - i)
        return (base[0], base[1], base[2]), (frac[0], frac[1], frac[2])

    def sample_coeffs(self, p: Vec) -> list[float]:
        """The trilinear blend of the nine coefficients of the 8 probes around p."""
        (i, j, k), (fx, fy, fz) = self.cell_and_weights(p)
        out = [0.0] * 9  # @line L3
        for a in (0, 1):  # @line L4
            wa = fx if a else 1.0 - fx
            for b in (0, 1):
                wb = fy if b else 1.0 - fy
                for c in (0, 1):
                    w = wa * wb * (fz if c else 1.0 - fz)  # @line L5
                    pr = self.probes[i + a][j + b][k + c]
                    for m in range(9):
                        out[m] += w * pr[m]  # @line L6
        return out

    def sample(self, p: Vec, n: Vec) -> float:
        """SAMPLE: the irradiance at the point p for the unit normal n."""
        return eval_sh(self.sample_coeffs(p), n)  # @line L7

    def check_invariant(self) -> None:
        nx, ny, nz = self.dims
        assert len(self.probes) == nx
        for plane in self.probes:
            assert len(plane) == ny
            for row in plane:
                assert len(row) == nz
                assert all(len(c) == 9 for c in row)
test_irradiance_volume.py 172 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/irradiance-volume/. The authors are listed in prov/CE3Y53.jsonl.

"""Tests of the irradiance volume against a brute force blend and a dict model.

The sample at a probe is the probe, affine fields of coefficients are
reproduced exactly, the weights form a partition of unity, the blend is
linear in the probe data and equals a sum of tensor-product hat functions
over all probes, random stores and samples agree with a dict model, and a
thin wall between two probes shows the light leak that the page describes.
"""

import math
import random

import pytest

from irradiance_volume import IrradianceVolume, eval_sh, irradiance_coeffs, sh9


def rand_dir(rng: random.Random) -> tuple[float, float, float]:
    while True:
        v = (rng.gauss(0, 1), rng.gauss(0, 1), rng.gauss(0, 1))
        r = math.sqrt(sum(c * c for c in v))
        if r > 1e-6:
            return (v[0] / r, v[1] / r, v[2] / r)


def rand_coeffs(rng: random.Random) -> list[float]:
    return [rng.uniform(-1, 1) for _ in range(9)]


def hat(u: float) -> float:
    return max(0.0, 1.0 - abs(u))


def brute_force(vol: IrradianceVolume, p) -> list[float]:
    """Sum over every probe of its coefficients times the product of three hat functions."""
    g = []
    for a in range(3):
        x = (p[a] - vol.origin[a]) / vol.spacing
        g.append(min(max(x, 0.0), vol.dims[a] - 1.0))
    nx, ny, nz = vol.dims
    out = [0.0] * 9
    for i in range(nx):
        for j in range(ny):
            for k in range(nz):
                w = hat(g[0] - i) * hat(g[1] - j) * hat(g[2] - k)
                if w:
                    pr = vol.probe(i, j, k)
                    for m in range(9):
                        out[m] += w * pr[m]
    return out


def test_point_light_probe() -> None:
    # One probe lit by a unit point light from +z: E(+z) = 17/16, E(-z) = 1/16, E(+x) = 3/32.
    vol = IrradianceVolume(dims=(2, 2, 2))
    vol.bake(lambda p: irradiance_coeffs(sh9((0.0, 0.0, 1.0))))
    for p in ((0, 0, 0), (0.3, 0.7, 0.2), (5, -3, 2)):
        assert abs(vol.sample(p, (0, 0, 1)) - 17 / 16) < 1e-12
        assert abs(vol.sample(p, (0, 0, -1)) - 1 / 16) < 1e-12
        assert abs(vol.sample(p, (1, 0, 0)) - 3 / 32) < 1e-12


def test_sample_at_probe_is_the_probe() -> None:
    rng = random.Random(1)
    vol = IrradianceVolume(origin=(-1.0, 2.0, 0.5), spacing=0.75, dims=(3, 4, 2))
    vol.bake(lambda p: rand_coeffs(rng))
    for i in range(3):
        for j in range(4):
            for k in range(2):
                got = vol.sample_coeffs(vol.probe_position(i, j, k))
                assert all(abs(a - b) < 1e-12 for a, b in zip(got, vol.probe(i, j, k)))


def test_affine_fields_are_exact() -> None:
    rng = random.Random(2)
    base = rand_coeffs(rng)
    grad = [rand_coeffs(rng) for _ in range(3)]

    def field(p):
        return [base[m] + sum(grad[a][m] * p[a] for a in range(3)) for m in range(9)]

    vol = IrradianceVolume(origin=(0.0, 0.0, 0.0), spacing=0.5, dims=(4, 3, 5))
    vol.bake(field)
    for _ in range(500):
        p = (rng.uniform(0, 1.5), rng.uniform(0, 1.0), rng.uniform(0, 2.0))
        got = vol.sample_coeffs(p)
        assert all(abs(a - b) < 1e-12 for a, b in zip(got, field(p)))


def test_weights_are_a_partition_of_unity() -> None:
    rng = random.Random(3)
    vol = IrradianceVolume(spacing=1.0, dims=(3, 3, 3))
    c = rand_coeffs(rng)
    vol.bake(lambda p: c)
    for _ in range(500):
        p = (rng.uniform(-2, 4), rng.uniform(-2, 4), rng.uniform(-2, 4))
        assert all(abs(a - b) < 1e-12 for a, b in zip(vol.sample_coeffs(p), c))
        (i, j, k), f = vol.cell_and_weights(p)
        assert all(0.0 <= x <= 1.0 for x in f)
        assert 0 <= i <= 1 and 0 <= j <= 1 and 0 <= k <= 1


def test_blend_is_linear_and_matches_brute_force() -> None:
    rng = random.Random(4)
    dims = (4, 3, 3)
    a = IrradianceVolume(origin=(1.0, -1.0, 0.0), spacing=0.4, dims=dims)
    b = IrradianceVolume(origin=(1.0, -1.0, 0.0), spacing=0.4, dims=dims)
    s = IrradianceVolume(origin=(1.0, -1.0, 0.0), spacing=0.4, dims=dims)
    for i in range(dims[0]):
        for j in range(dims[1]):
            for k in range(dims[2]):
                ca, cb = rand_coeffs(rng), rand_coeffs(rng)
                a.set_probe(i, j, k, ca)
                b.set_probe(i, j, k, cb)
                s.set_probe(i, j, k, [2 * x - 3 * y for x, y in zip(ca, cb)])
    for _ in range(300):
        p = (rng.uniform(0.5, 2.6), rng.uniform(-1.5, 0.2), rng.uniform(-0.3, 1.2))
        n = rand_dir(rng)
        assert abs(s.sample(p, n) - (2 * a.sample(p, n) - 3 * b.sample(p, n))) < 1e-12
        got, want = a.sample_coeffs(p), brute_force(a, p)
        assert all(abs(x - y) < 1e-12 for x, y in zip(got, want))
        assert abs(a.sample(p, n) - eval_sh(want, n)) < 1e-12


def test_random_operations_against_a_dict() -> None:
    rng = random.Random(5)
    dims = (3, 2, 4)
    vol = IrradianceVolume(origin=(0.0, 0.0, 0.0), spacing=2.0, dims=dims)
    model = {}
    for _ in range(1500):
        if rng.random() < 0.5:
            key = (rng.randrange(dims[0]), rng.randrange(dims[1]), rng.randrange(dims[2]))
            c = rand_coeffs(rng)
            vol.set_probe(*key, c)
            model[key] = c
        else:
            key = (rng.randrange(dims[0]), rng.randrange(dims[1]), rng.randrange(dims[2]))
            n = rand_dir(rng)
            want = eval_sh(model.get(key, [0.0] * 9), n)
            assert abs(vol.sample(vol.probe_position(*key), n) - want) < 1e-12
            p = (rng.uniform(0, 4), rng.uniform(0, 2), rng.uniform(0, 6))
            ref = IrradianceVolume(origin=(0.0, 0.0, 0.0), spacing=2.0, dims=dims)
            for kk, cc in model.items():
                ref.set_probe(*kk, cc)
            assert abs(vol.sample(p, n) - eval_sh(brute_force(ref, p), n)) < 1e-12
        vol.check_invariant()


def test_light_leak_through_a_thin_wall() -> None:
    # A measurement of the failure, not a property to rely on: probes at x = 0 are in a
    # dark room, probes at x = 1 in a bright one, and a wall stands at x = 0.5. A point
    # at x = 0.4, still on the dark side, gets 40 percent of the bright irradiance.
    vol = IrradianceVolume(spacing=1.0, dims=(2, 2, 2))
    bright = irradiance_coeffs(sh9((0.0, 0.0, 1.0)))
    for j in range(2):
        for k in range(2):
            vol.set_probe(0, j, k, [0.0] * 9)
            vol.set_probe(1, j, k, bright)
    e = vol.sample((0.4, 0.5, 0.5), (0, 0, 1))
    assert abs(e - 0.4 * 17 / 16) < 1e-12


def test_bad_arguments() -> None:
    with pytest.raises(ValueError):
        IrradianceVolume(dims=(1, 2, 2))
    with pytest.raises(ValueError):
        IrradianceVolume(spacing=0.0)
    with pytest.raises(ValueError):
        IrradianceVolume().set_probe(0, 0, 0, [1.0, 2.0])

History

Greger, Shirley, Hubbard and Greenberg (1998) defined the irradiance volume: they extended the irradiance from points on surfaces to all points and directions of space, sampled it at the points of a grid, and interpolated it to light objects that move through a precomputed scene. Ramamoorthi and Hanrahan (2001) showed that nine spherical harmonic coefficients represent irradiance well, and probe grids in games then moved to that encoding or to similar small bases such as six color ambient cubes. Majercik, Guertin, Nowrouzezahrai and McGuire (2019) added per probe visibility and ray traced updates, which made dynamic probe grids practical on hardware with ray tracing.

References

  1. Gene Greger, Peter Shirley, Philip M. Hubbard and Donald P. Greenberg, The irradiance volume, IEEE Computer Graphics and Applications 18(2), 1998, 32 to 43, the definition of the irradiance at all points and directions of space, its sampling on a grid and its interpolation for moving objects
  2. Zander Majercik, Jean-Philippe Guertin, Derek Nowrouzezahrai and Morgan McGuire, Dynamic Diffuse Global Illumination with Ray-Traced Irradiance Fields, Journal of Computer Graphics Techniques 8(2), 2019, 1 to 30, the probe grid that ray tracing updates each frame, and the per probe visibility data against light leaks
  3. Tomas Akenine-Möller, Eric Haines, Naty Hoffman, Angelo Pesce, Michał Iwanicki and Sébastien Hillaire, Real-Time Rendering, fourth edition, CRC Press, 2018, Chapter 11, Global Illumination (the part on precomputed lighting stored in probes)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.bake
  • a full proof of time.sample
  • a full proof of time.set_probe
  • a full proof of space.total
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/CE3Y53/text.yaml