Algorithm Search⌘K

Algorithmcore

Screen-space ambient occlusion

Also called SSAO.

Estimate ambient occlusion per pixel by testing sample points around it against the depth buffer, then blur the noisy result.

Time
O(p s + p r^2) worst
Space
O(p + s) extra
Where
p = the number of pixels; r = the radius of the blur in pixels; s = the number of samples per pixel
Properties
deterministicnot in placeofflineiterative
Origin
Martin Mittring, Perumalla Shanmugam, Okan Arikan, 2007

Screen-space ambient occlusion estimates, for each pixel, how much of the space around the visible surface is filled by other surfaces, using only the depth buffer of the frame. For a pixel at the point PP, it places a few sample points in a small sphere or hemisphere around PP, projects each one to the screen, and compares its depth with the depth stored there. A sample behind the stored surface counts as occluded. The share of occluded samples darkens the ambient light of the pixel, so creases, corners and contact areas get darker. The result is noisy with few samples, so a blur follows. Mittring presented it for the game Crysis in 2007. It approximates ambient occlusion, but what it computes is a volume fraction of one depth layer, not the integral over directions, and how close it comes is a measurement, not a guarantee.

In plain words

Corners and gaps get less light from the sky than open surfaces, and it helps to darken them. A ray tracer would shoot rays from each point to see how much of the sky is blocked. That is too slow for every frame. SSAO does something cheaper with the picture that the GPU has already made. Around each point, it throws a handful of small test points, and for each one it asks the depth buffer: is there a surface in front of this test point, as seen from the camera? If yes, the test point is probably inside something. Many test points inside means the point sits in a corner. The answer is noisy, so neighboring pixels are averaged.

The problem

The input is a depth buffer DD of pp pixels with the view depth dd of the visible surface, and for the hemisphere form the normals, from a G-buffer or from differences of DD. The output is a visibility A∈[0,1]A \in [0, 1] per pixel, 1 for open and smaller in creases, to multiply into the ambient light. The reference is the ambient occlusion of the scene, but the depth buffer holds only the nearest surface per pixel, so anything hidden behind it, and anything outside the screen, is unknown.

This page and its code use an orthographic camera that looks along −z-z, so that the tests can use height fields with known answers. The pixel (i,j)(i, j) has its center at (i+1/2,j+1/2)(i + 1/2, j + 1/2) in view units, and its point is P=(x,y,−d)P = (x, y, -d). In a perspective camera, P=d (u,v,−1)P = d\,(u, v, -1) with the slopes of the pixel, and a sample is projected with the camera matrix; the method is otherwise the same.

The algorithm

The kernel is a list of ss offsets of length at most RR. In the sphere form they fill a ball. In the hemisphere form they fill a half ball and are turned so that its axis is the normal nn of the pixel. The bias β\beta and the range function are tuning.

  1. SSAO(D, kernel, R, β)
  2. 1for each pixel q with depth d: P ← the point of q
  3. 2n ← the normal at q ▷ hemisphere form only
  4. 3occ ← 0
  5. 4for each offset k of the kernel: S ← P + k, or P + ROTATE(k, n) in the hemisphere form
  6. 5b ← the depth of D at the screen position of S; dS ← the depth of S
  7. 6if b < dS - β then occ ← occ + RANGE(R, |d - b|)
  8. 7A[q] ← 1 - occ / s
  9. 8return BLUR(A)

The test (lines L5 and L6). The sample is occluded if the surface stored at its screen position is nearer to the camera than the sample. The bias β\beta removes self-occlusion from depth precision and from a coarse reconstruction of the surface.

The range check (line L6). A surface far in front of PP, such as a near object in front of a far wall, also passes the test. The common fix multiplies the count by a falloff in the depth gap. The code uses smoothstep⁡(0,1,R/∣d−b∣)\operatorname{smoothstep}(0, 1, R / |d - b|), a form found in many engines. The falloff is tuning.

The kernel and the noise. A few samples per pixel give banding. Engines rotate the kernel per pixel with a small tile of random rotations, which turns the banding into high-frequency noise, and the blur of line L8 removes most of it. A bilateral filter that does not blur across depth edges is the usual choice. The code uses a box blur.

Example

A frontal floor at depth 40 meets a block nearer to the camera by 30 units along a line at x=20x = 20. The kernel has s=6000s = 6000 points in the half ball of radius R=6R = 6 around the normal (0,0,1)(0, 0, 1), and the lookup is nearest. A point of the floor at the distance δ\delta from the foot of the block has the expected occluded fraction (R−δ)2(2R+δ)/(4R3)(R - \delta)^2 (2R + \delta) / (4 R^3), the share of a cap of the ball.

δ\delta formula measured 1−A1 - A
0.5 0.438 0.471
1.5 0.316 0.313
2.5 0.206 0.204
4.5 0.043 0.044
5.5 0.005 0.004

The row at δ=0.5\delta = 0.5 is off by more than the noise. Its normal comes from central differences that cross the edge, so it tilts, and the hemisphere leans into the block. The other rows agree within the sampling error of about 0.006.

With a sphere kernel in antithetic pairs k,−kk, -k and the bilinear lookup, every plane gives A=1/2A = 1/2 exactly: of each pair, one point is in front of the plane and one is behind it. So a flat open floor comes out as gray as a corner. With the hemisphere kernel, every plane gives A=1A = 1.

Correctness

SSAO is an estimator, so its correctness is a statement of what it estimates, and the proofs folder proves it. With independent uniform offsets in the half ball and no bias or range check, the expected value of 1−A1 - A is the fraction of the volume of the half ball that lies behind the surface seen in the depth buffer, and its variance is at most 1/(4s)1/(4s). That volume fraction is a measure of how closed the neighborhood is. It is not the cosine-weighted integral of the ambient occlusion page. The exact cases are planes: the sphere kernel gives 1/21/2 on every plane, because the test of an offset kk is the sign of m⋅km \cdot k for the plane normal mm and antithetic pairs split evenly; the hemisphere kernel gives 1 on every plane, because its offsets have m⋅k>0m \cdot k > 0. The wall formula of the example is proved by a cap volume. The tests check all of these, the plane cases exactly.

Proof: What screen-space ambient occlusion estimates, and its exact casesfull

Setting. The camera is orthographic and looks along −z-z, as in the code. The pixel (i,j)(i, j) has its center at (i+1/2,j+1/2)(i + 1/2, j + 1/2) and the depth Dij>0D_{ij} > 0, and its point is P=(x,y,−d)P = (x, y, -d). The reconstructed depth D^(x,y)\hat D(x, y) is the bilinear or the nearest lookup of the buffer. For an offset kk, the sample S=P+kS = P + k is occluded when D^(Sx,Sy)<d−kz−β\hat D(S_x, S_y) < d - k_z - \beta with the bias β≥0\beta \ge 0: the stored surface is nearer to the camera than the sample. Without the range check, each occluded sample adds 1, and the result is A=1−(occluded samples)/sA = 1 - (\text{occluded samples}) / s for ss samples. The claims assume that every sample projects inside the buffer, away from the clamped border.

Lemma 1 (bilinear lookup on a plane). If Dij=d0+gx(i+1/2)+gy(j+1/2)D_{ij} = d_0 + g_x (i + 1/2) + g_y (j + 1/2) for all pixels, then the bilinear lookup gives D^(x,y)=d0+gxx+gyy\hat D(x, y) = d_0 + g_x x + g_y y inside the buffer.

Proof. Bilinear interpolation is a convex combination of the four corner values with the weights (1−fu)(1−fv)(1 - f_u)(1 - f_v), fu(1−fv)f_u (1 - f_v), (1−fu)fv(1 - f_u) f_v and fufvf_u f_v. These weights sum to 1 and reproduce the coordinates: the weighted mean of the corner positions is (x,y)(x, y). An affine function of the corners therefore interpolates to the same affine function at (x,y)(x, y). □\square

Theorem 1 (sphere kernel on a plane). Let the buffer hold a plane as in Lemma 1, read with the bilinear lookup, with β=0\beta = 0. Let the kernel be made of pairs k,−kk, -k with m⋅k≠0m \cdot k \ne 0 for m=(gx,gy,1)m = (g_x, g_y, 1). Then A=1/2A = 1/2 at every pixel.

Proof. By Lemma 1, D^(Sx,Sy)=d+gxkx+gyky\hat D(S_x, S_y) = d + g_x k_x + g_y k_y, so the sample is occluded if and only if d+gxkx+gyky<d−kzd + g_x k_x + g_y k_y < d - k_z, that is, m⋅k<0m \cdot k < 0. Of kk and −k-k, exactly one has m⋅k<0m \cdot k < 0. So half of the samples are occluded. □\square

So the sphere kernel shows every plane, open or not, as half occluded. This is the gray of flat surfaces that the first form of SSAO has, and it is the reason for the normal-oriented form.

Lemma 2 (normal of a plane). For a plane as in Lemma 1, the central differences of the code give the unit normal n=m/∥m∥n = m / \lVert m \rVert, which faces the camera.

Proof. The differences of an affine function over two pixels, divided by 2, are exactly gxg_x and gyg_y. The surface is the zero set of F(x,y,z)=z+d0+gxx+gyyF(x, y, z) = z + d_0 + g_x x + g_y y, whose gradient is mm. □\square

Theorem 2 (hemisphere kernel on a plane). For a plane as in Lemma 1 with any lookup that is exact on the plane, and for any kernel in the open upper half ball (tangent offsets with kz>0k_z > 0) rotated into the frame of nn, A=1A = 1 at every pixel for every β≥0\beta \ge 0.

Proof. The rotation keeps the length and sends the third axis to nn, so the offset oo has n⋅o=kz>0n \cdot o = k_z > 0, hence m⋅o>0m \cdot o > 0. As in the proof of Theorem 1, the sample is occluded only if m⋅o<−β≤0m \cdot o < -\beta \le 0, which does not happen. □\square

Theorem 3 (what the estimate converges to). Let the ss offsets be independent and uniform in the half ball of radius RR around nn, with β=0\beta = 0 and no range check. Let VV be the set of offsets oo of this half ball with D^(Px+ox,Py+oy)<d−oz\hat D(P_x + o_x, P_y + o_y) < d - o_z, the part of the half ball that lies behind the surface seen in the buffer. Then 1−A1 - A is an unbiased estimate of ∣V∣/(23πR3)\lvert V \rvert / (\tfrac{2}{3} \pi R^3), the volume fraction of VV, with variance at most 1/(4s)1 / (4 s).

Proof. Each sample is occluded with probability ∣V∣/(23πR3)\lvert V \rvert / (\tfrac{2}{3}\pi R^3), the measure of VV under the uniform distribution. 1−A1 - A is the mean of ss independent Bernoulli variables with this mean, and a Bernoulli variable has variance at most 1/41/4. □\square

This volume fraction is not the cosine-weighted ambient occlusion integral over directions. The two agree at the ends (0 for an open plane and 1 for a closed one), and in between they are different functions of the geometry. A claim that SSAO matches ray traced ambient occlusion would be a measurement on scenes, not a consequence of this theorem.

Theorem 4 (the wall). Let PP lie on a frontal floor (n=(0,0,1)n = (0, 0, 1)) at a distance δ∈[0,R]\delta \in [0, R] from the foot of an infinite wall that is nearer to the camera by H≥RH \ge R, with the edge on a pixel boundary and the nearest lookup. Then the volume fraction of Theorem 3 is

(R−δ)2(2R+δ)4R3,\frac{(R - \delta)^2 (2R + \delta)}{4 R^3},

which is 1/21/2 at the foot of the wall.

Proof. With the nearest lookup the buffer holds the step exactly. An offset with ox>δo_x > \delta projects onto the wall, whose depth is d−H<d−ozd - H < d - o_z because oz<R≤Ho_z < R \le H, so it is behind the wall; an offset with ox<δo_x < \delta projects onto the floor at depth d>d−ozd > d - o_z and is free. VV is the part of the half ball with ox>δo_x > \delta. The ball is symmetric in zz, so this fraction equals the fraction of the whole ball with ox>δo_x > \delta, a cap of height R−δR - \delta with the volume π(R−δ)2(3R−(R−δ))/3\pi (R - \delta)^2 (3R - (R - \delta)) / 3. Dividing by 43πR3\tfrac43 \pi R^3 gives the formula. □\square

The tests compare 6000 samples with this formula at pixels 1.5 to 5.5 units from the wall and find errors below 0.025. A pixel next to the edge is not tested: its central difference crosses the edge and tilts the normal.

Theorem 5 (cost). For pp pixels, ss samples and a blur of radius rr, the cost is O(ps)O(p s) lookups and O(pr2)O(p r^2) for the box blur.

Proof. Each pixel does ss samples of O(1)O(1) work, and the blur sums (2r+1)2(2r + 1)^2 values per pixel. □\square

Complexity

The model is the real RAM. Each pixel takes ss samples with one depth lookup each, so the pass costs O(ps)O(p s). A box blur of radius rr costs O(pr2)O(p r^2), or O(pr)O(p r) if it is separable. The kernel takes O(s)O(s) memory and the result O(p)O(p). At 1920 by 1080 pixels with 16 samples, this is about 33 million depth reads per frame. Engines often run SSAO at half resolution and upsample, which cuts this by 4.

The reads of the samples are scattered around each pixel, so their cost is mostly in the texture cache. A larger radius in pixels spreads the reads and lowers the hit rate.

Properties

  • Screen space only. The input is one depth layer. Surfaces hidden behind it and outside the screen do not occlude.
  • Depends on the view. The same corner gets other values from other angles, because the depth buffer changes.
  • Volume, not angle. The value is a share of volume, not of directions weighted by the cosine.
  • Bias toward gray. The sphere form darkens open planes to 1/21/2. The hemisphere form fixes this but needs normals.
  • Noise and blur. Few samples need a rotation pattern and a blur, or temporal accumulation.
  • Cheap and local. The cost per pixel is fixed and independent of the scene.

Variants and improvements

  • Sphere kernel. The original form needs no normals. Open surfaces come out half gray, and the image is usually rescaled.
  • Hemisphere kernel. Turn the kernel to the normal, so that open planes get A=1A = 1.
  • Range check. A falloff in the depth gap removes halos around near objects.
  • Horizon-based methods. March the depth buffer in a few directions and integrate the angle of the horizon, see horizon-based ambient occlusion. The ground-truth ambient occlusion method integrates the cosine-weighted visibility of each slice in closed form.
  • Temporal accumulation. Change the kernel each frame and blend with the reprojected result of earlier frames, as in temporal antialiasing.
  • Multiple layers. Render a second depth layer to see behind the first, at the cost of another pass.

When to use it

Use SSAO for cheap contact darkening in real-time rendering when the frame has a depth buffer and the budget allows a few samples per pixel. It works best with a deferred shading renderer that has normals in its G-buffer. When the look must be close to ray traced ambient occlusion, use a horizon-based method or ray tracing.

Pitfalls

  • Halos. Without a range check, a near object darkens the far wall behind it in a band around its silhouette.
  • Self-occlusion. Without a bias, depth precision and a coarse lookup make flat surfaces look occluded in patterns.
  • Normals from depth at edges. Differences across a depth edge tilt the normal, as the example shows. Use G-buffer normals, or one-sided differences that pick the smaller gap.
  • Radius in the wrong space. The radius is a distance in the scene. In a perspective camera its size on the screen shrinks with depth, so far pixels sample a few pixels only.
  • Screen borders. Samples that leave the screen read clamped or missing depths. Fade the effect near the borders, or render a guard band.
  • Gray planes. The sphere kernel darkens open surfaces by half. Rescale or use the hemisphere form.

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.

screen_space_ambient_occlusion.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/screen-space-ambient-occlusion/. The authors are listed in prov/EGC7ET.jsonl.

"""Screen-space ambient occlusion with sample points tested against the depth buffer.

The camera is orthographic and looks along -z, so that the tests can use
height fields with known answers. The pixel (i, j) has its center at
(i + 1/2, j + 1/2) in view units, j counted from the bottom, and D[j][i] is the
positive view depth of the visible surface. The point of a pixel with depth d
is P = (x, y, -d). The result per pixel is the visibility A in [0, 1]: 1 means
not occluded.

Two kernels are given: points in a sphere around P, as in the first SSAO of
2007, and points in the hemisphere around the normal. The depth lookup is
bilinear (exact on planes) or nearest (exact on steps at pixel edges).
"""

import math
import random
from typing import List, Optional, Sequence, Tuple

Vec = Tuple[float, float, float]
Grid = List[List[float]]


def lookup(D: Grid, x: float, y: float, mode: str = "bilinear") -> float:
    """The depth buffer at a screen position, clamped at the borders."""
    h, w = len(D), len(D[0])
    if mode == "nearest":
        i = min(max(int(math.floor(x)), 0), w - 1)
        j = min(max(int(math.floor(y)), 0), h - 1)
        return D[j][i]
    u = min(max(x - 0.5, 0.0), w - 1.0)
    v = min(max(y - 0.5, 0.0), h - 1.0)
    i0, j0 = min(int(u), w - 2) if w > 1 else 0, min(int(v), h - 2) if h > 1 else 0
    i1, j1 = min(i0 + 1, w - 1), min(j0 + 1, h - 1)
    fu, fv = u - i0, v - j0
    top = D[j0][i0] * (1 - fu) + D[j0][i1] * fu
    bot = D[j1][i0] * (1 - fu) + D[j1][i1] * fu
    return top * (1 - fv) + bot * fv


def normal_from_depth(D: Grid, i: int, j: int) -> Vec:
    """The normal of the surface z = -D from central differences, facing +z."""
    h, w = len(D), len(D[0])
    il, ir = max(i - 1, 0), min(i + 1, w - 1)
    jb, jt = max(j - 1, 0), min(j + 1, h - 1)
    gx = (D[j][ir] - D[j][il]) / (ir - il) if ir > il else 0.0
    gy = (D[jt][i] - D[jb][i]) / (jt - jb) if jt > jb else 0.0
    n = (gx, gy, 1.0)
    s = math.sqrt(gx * gx + gy * gy + 1.0)
    return (n[0] / s, n[1] / s, n[2] / s)


def _ball_point(rng: random.Random, radius: float) -> Vec:
    while True:
        p = (rng.uniform(-1, 1), rng.uniform(-1, 1), rng.uniform(-1, 1))
        if 0 < p[0] ** 2 + p[1] ** 2 + p[2] ** 2 <= 1:
            return (p[0] * radius, p[1] * radius, p[2] * radius)


def sphere_kernel(rng: random.Random, pairs: int, radius: float) -> List[Vec]:
    """Uniform points in a ball, in antithetic pairs k and -k."""
    out = []
    for _ in range(pairs):
        k = _ball_point(rng, radius)
        out += [k, (-k[0], -k[1], -k[2])]
    return out


def hemisphere_kernel(rng: random.Random, count: int, radius: float) -> List[Vec]:
    """Uniform points in the half ball with z > 0, in the tangent frame."""
    out = []
    while len(out) < count:
        k = _ball_point(rng, radius)
        if k[2] != 0:
            out.append((k[0], k[1], abs(k[2])))
    return out


def to_normal_frame(k: Vec, n: Vec) -> Vec:
    """Rotate a tangent-frame offset so that its z axis becomes n."""
    a = (1.0, 0.0, 0.0) if abs(n[0]) < 0.9 else (0.0, 1.0, 0.0)
    # t = normalize(a - (a . n) n), b = n x t
    d = a[0] * n[0] + a[1] * n[1] + a[2] * n[2]
    t = (a[0] - d * n[0], a[1] - d * n[1], a[2] - d * n[2])
    tl = math.sqrt(t[0] ** 2 + t[1] ** 2 + t[2] ** 2)
    t = (t[0] / tl, t[1] / tl, t[2] / tl)
    b = (n[1] * t[2] - n[2] * t[1], n[2] * t[0] - n[0] * t[2], n[0] * t[1] - n[1] * t[0])
    return tuple(k[0] * t[c] + k[1] * b[c] + k[2] * n[c] for c in range(3))


def smoothstep01(t: float) -> float:
    t = min(max(t, 0.0), 1.0)
    return t * t * (3 - 2 * t)


def ssao_pixel(
    D: Grid,
    i: int,
    j: int,
    kernel: Sequence[Vec],
    oriented: bool,
    bias: float = 0.0,
    range_radius: Optional[float] = None,
    mode: str = "bilinear",
) -> float:
    d = D[j][i]
    P = (i + 0.5, j + 0.5, -d)  # @line L1
    n = normal_from_depth(D, i, j) if oriented else None  # @line L2
    occ = 0.0  # @line L3
    for k in kernel:  # @line L4
        o = to_normal_frame(k, n) if oriented else k
        s = (P[0] + o[0], P[1] + o[1], P[2] + o[2])
        b = lookup(D, s[0], s[1], mode)  # @line L5
        ds = -s[2]
        if b < ds - bias:  # @line L6
            if range_radius is None:
                occ += 1.0
            else:
                gap = abs(d - b)
                occ += 1.0 if gap == 0 else smoothstep01(range_radius / gap)
    return 1.0 - occ / len(kernel)  # @line L7


def box_blur(A: Grid, r: int) -> Grid:
    """A (2r+1) by (2r+1) box filter, clamped at the borders."""
    h, w = len(A), len(A[0])
    out = []
    for j in range(h):
        row = []
        for i in range(w):
            acc, cnt = 0.0, 0
            for jj in range(max(0, j - r), min(h, j + r + 1)):
                for ii in range(max(0, i - r), min(w, i + r + 1)):
                    acc += A[jj][ii]
                    cnt += 1
            row.append(acc / cnt)
        out.append(row)
    return out


def ssao(D: Grid, kernel: Sequence[Vec], oriented: bool, blur: int = 0, **kw) -> Grid:
    A = [[ssao_pixel(D, i, j, kernel, oriented, **kw) for i in range(len(D[0]))] for j in range(len(D))]
    return box_blur(A, blur) if blur > 0 else A  # @line L8


def half_ball_beyond(delta: float, radius: float) -> float:
    """The fraction of the half ball of the given radius with x > delta, for
    0 <= delta <= radius: the occluded fraction next to an infinite wall at
    distance delta that is higher than the radius."""
    return (radius - delta) ** 2 * (2 * radius + delta) / (4 * radius ** 3)
test_screen_space_ambient_occlusion.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/screen-space-ambient-occlusion/. The authors are listed in prov/EGC7ET.jsonl.

"""SSAO on height fields with known answers."""

import math
import random

from screen_space_ambient_occlusion import (
    box_blur,
    half_ball_beyond,
    hemisphere_kernel,
    lookup,
    normal_from_depth,
    sphere_kernel,
    ssao,
    ssao_pixel,
    to_normal_frame,
)


def plane(w, h, d0, gx, gy):
    return [[d0 + gx * (i + 0.5) + gy * (j + 0.5) for i in range(w)] for j in range(h)]


def test_bilinear_lookup_is_exact_on_a_plane() -> None:
    D = plane(12, 10, 20.0, 0.25, -0.5)
    rng = random.Random(61)
    for _ in range(200):
        x, y = rng.uniform(0.5, 11.5), rng.uniform(0.5, 9.5)
        assert abs(lookup(D, x, y) - (20.0 + 0.25 * x - 0.5 * y)) < 1e-9


def test_sphere_kernel_gives_one_half_on_any_plane() -> None:
    rng = random.Random(62)
    kernel = sphere_kernel(rng, 16, 3.0)
    for gx, gy in [(0.0, 0.0), (0.3, 0.0), (-0.4, 0.7), (1.5, -0.2)]:
        D = plane(24, 24, 50.0, gx, gy)
        for i, j in [(10, 10), (12, 8), (8, 14)]:
            assert ssao_pixel(D, i, j, kernel, oriented=False) == 0.5


def test_hemisphere_kernel_gives_one_on_any_plane() -> None:
    rng = random.Random(63)
    kernel = hemisphere_kernel(rng, 32, 3.0)
    for gx, gy in [(0.0, 0.0), (0.3, 0.0), (-0.4, 0.7), (1.5, -0.2)]:
        D = plane(24, 24, 50.0, gx, gy)
        n = normal_from_depth(D, 11, 11)
        s = math.hypot(gx, gy, 1.0)
        assert all(abs(a - b) < 1e-12 for a, b in zip(n, (gx / s, gy / s, 1 / s)))
        for i, j in [(10, 10), (12, 8), (8, 14)]:
            assert ssao_pixel(D, i, j, kernel, oriented=True) == 1.0


def test_rotation_keeps_the_kernel_in_the_hemisphere() -> None:
    rng = random.Random(64)
    for _ in range(100):
        v = (rng.gauss(0, 1), rng.gauss(0, 1), abs(rng.gauss(0, 1)) + 0.1)
        L = math.sqrt(sum(c * c for c in v))
        n = tuple(c / L for c in v)
        for k in hemisphere_kernel(rng, 5, 1.0):
            o = to_normal_frame(k, n)
            assert abs(sum(c * c for c in o) - sum(c * c for c in k)) < 1e-12
            assert abs(sum(a * b for a, b in zip(o, n)) - k[2]) < 1e-12


def test_step_matches_the_volume_fraction() -> None:
    # Floor at depth 40 for x < 20, a block nearer by 30 for x >= 20.
    w, h, R = 40, 20, 6.0
    D = [[40.0 if i < 20 else 10.0 for i in range(w)] for _ in range(h)]
    rng = random.Random(65)
    kernel = hemisphere_kernel(rng, 6000, R)
    # Pixel 19 is left out: its central difference straddles the edge and
    # tilts the normal, which is a known artifact of normals from depth.
    for i in (18, 17, 15, 14):
        delta = 20 - (i + 0.5)
        A = ssao_pixel(D, i, 10, kernel, oriented=True, mode="nearest")
        assert abs((1 - A) - half_ball_beyond(delta, R)) < 0.025
    assert half_ball_beyond(0.0, R) == 0.5


def test_range_check_fades_far_occluders() -> None:
    # A plate 30 units in front of a frontal floor covers the right half.
    w, h, R = 30, 10, 4.0
    D = [[60.0 if i < 15 else 30.0 for i in range(w)] for _ in range(h)]
    rng = random.Random(66)
    kernel = hemisphere_kernel(rng, 400, R)
    plain = ssao_pixel(D, 13, 5, kernel, oriented=True, mode="nearest")
    ranged = ssao_pixel(D, 13, 5, kernel, oriented=True, mode="nearest", range_radius=R)
    assert abs((1 - plain) - half_ball_beyond(1.5, R)) < 0.05
    assert ranged > 0.95


def test_blur_keeps_constants_and_averages() -> None:
    A = [[0.25] * 7 for _ in range(5)]
    assert box_blur(A, 2) == A
    B = [[1.0 if (i + j) % 2 else 0.0 for i in range(9)] for j in range(9)]
    out = box_blur(B, 1)
    assert abs(out[4][4] - 4 / 9) < 1e-12


def test_whole_image_on_a_plane() -> None:
    D = plane(16, 12, 30.0, 0.2, 0.1)
    rng = random.Random(67)
    A = ssao(D, hemisphere_kernel(rng, 16, 2.0), oriented=True, blur=1)
    assert all(abs(a - 1.0) < 1e-12 for row in A for a in row)

History

Ambient occlusion and obscurance were defined for offline rendering in the late 1990s and early 2000s, where rays are traced from each point. In 2007 Mittring described the screen-space form used in CryEngine 2 for Crysis: points in a sphere around the pixel, tested against the depth buffer, with a blur. Shanmugam and Arikan published in the same year a GPU method that also worked from the buffers of the visible surfaces. Later engines turned the kernel to the normal to remove the gray of open surfaces, added range checks, and replaced the random points by horizon searches, which led to horizon-based ambient occlusion in 2008 and ground-truth ambient occlusion in 2016.

References

  1. Martin Mittring, Finding next gen: CryEngine 2, SIGGRAPH 2007 course Advanced Real-Time Rendering in 3D Graphics and Games, the part on screen-space ambient occlusion, with sample points in a sphere tested against the depth buffer and a blur of the noise
  2. Perumalla Shanmugam and Okan Arikan, Hardware accelerated ambient occlusion techniques on GPUs, Symposium on Interactive 3D Graphics and Games 2007, ambient occlusion computed from the depth and normal buffers of the visible surfaces
  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, Section 11.3, Ambient Occlusion (the part on screen-space methods)

Where this leads

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.worst
  • a full proof of space.extra
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)
WritingW2 basic
  • a scene preset for the example