Algorithm Search⌘K

Algorithmresearch

Ground-truth ambient occlusion

Also called GTAO.

A horizon-based screen-space method that integrates cosine-weighted visibility in closed form per slice. Its match with ray traced AO is a measurement, for one depth layer only.

Time
O(p m s) worst
Space
O(p) extra
Where
m = the number of slices per pixel; p = the number of pixels; s = the number of steps per side of a slice
Properties
deterministicnot in placeofflineiterative
Origin
Jorge Jimenez, Xian Chun Wu, Angelo Pesce, Adrian Jarabo, 2016

Ground-truth ambient occlusion is a screen-space method that computes the cosine-weighted ambient occlusion of the surface seen in the depth buffer. Like horizon-based ambient occlusion, it marches the depth buffer to find horizon angles. It differs in how it splits the hemisphere: into slices, planes through the view vector, each with a horizon on both sides. Inside a slice, the integral of the cosine between the normal and the direction over the open angles has a closed form, so the only numerical integration left is over the slices. Jimenez, Wu, Pesce and Jarabo described it in 2016. The name says ground truth, but the result equals ray traced ambient occlusion only for the scene that the depth buffer describes, a single layer read as a solid height field. How close it comes on real scenes is a measurement.

In plain words

Ambient occlusion asks how much of the sky a point sees, counting directions near the normal more than directions near the ground, as a matte surface does. Horizon methods walk across the depth buffer in a few directions and find, in each, how high the surrounding surface rises. GTAO cuts the half sphere above the point into thin vertical slices, like slices of an orange around the line of sight. In each slice, it finds the horizon on the left and on the right. Between the two horizons the sky is open, and the cosine-weighted share of that open arc can be written down with a formula. So each slice costs one march and one formula, and a few slices give the answer.

The problem

The input is a depth buffer DD of pp pixels and the normals, from a G-buffer or from differences of DD. The output is the visibility

A=1π∫n⋅ω>0V(ω) (n⋅ω) dω∈[0,1]A = \frac{1}{\pi} \int_{n \cdot \omega > 0} V(\omega)\, (n \cdot \omega) \, d\omega \in [0, 1]

per pixel, where V(ω)V(\omega) is 1 if the direction ω\omega is open. The depth buffer does not say what is behind the visible surface, so the method assumes that, seen from the pixel, a direction is blocked exactly when it is below the horizon of its slice.

This page and its code use an orthographic camera that looks along −z-z, so the view vector is v=(0,0,1)v = (0, 0, 1) at every pixel and the tests can use height fields. In a perspective camera the view vector changes from pixel to pixel; the slices are planes through it, and the points of the march are reconstructed as P=d (u,v,−1)P = d\,(u, v, -1) from the depth and the slopes of the pixel.

The algorithm

mm slices with a per-pixel offset ξ\xi, ss steps of length ℓ\ell per side, and a radius RR. A slice φ\varphi is spanned by vv and the screen direction c=(cos⁡φ,sin⁡φ,0)c = (\cos\varphi, \sin\varphi, 0). Angles hh in a slice are measured from vv, positive toward cc.

  1. GTAO(D, q, n, m, s, ℓ, R, ξ)
  2. 1A ← 0; P ← the point of q
  3. 2for k ← 0 to m - 1: φ ← π (k + ξ) / m; c ← (cos φ, sin φ, 0)
  4. 3n_p ← (n · c) c + (n · v) v; γ ← the angle of n_p from v
  5. 4h2 ← the smallest angle from v of the points of D at P + i ℓ c, i = 1..s, within R, and at most γ + π/2
  6. 5h1 ← minus the same on the side P - i ℓ c, and at least γ - π/2
  7. 6â ← ¼(-cos(2h1 - γ) + cos γ + 2 h1 sin γ) + ¼(-cos(2h2 - γ) + cos γ + 2 h2 sin γ)
  8. 7A ← A + |n_p| â
  9. 8return A / m

The slice (line L3). The projected normal npn_p has the length ∣np∣≤1|n_p| \le 1 and the angle γ\gamma from vv in the slice. For a direction ω\omega of the slice at the angle hh, n⋅ω=∣np∣cos⁡(h−γ)n \cdot \omega = |n_p| \cos(h - \gamma).

The horizons (lines L4 and L5). Each side is marched as in HBAO, but the code keeps the largest cosine to vv of the vectors from PP to the samples, which is the smallest angle. The search starts at the tangent of the surface, γ±π/2\gamma \pm \pi/2, so that the horizons are clamped to the hemisphere of the normal.

The inner integral (line L6). With dω=∣sin⁡h∣ dh dφd\omega = |\sin h| \, dh \, d\varphi in slice coordinates, the open part of a slice contributes ∫h1h2cos⁡(h−γ)∣sin⁡h∣ dh\int_{h_1}^{h_2} \cos(h - \gamma) |\sin h| \, dh, and the expression of line L6 is its antiderivative evaluated at the two horizons. The proofs folder derives it. The report of Jimenez and others gives a closed form for the same integral; this page does not quote its equation.

The rest of the frame. The report runs few slices per pixel, rotates them per pixel and per frame, and removes the noise with spatial and temporal filters. These choices are tuning and are not in the code.

Example

A frontal floor meets a block that rises by H=8H = 8 toward the camera along a straight line. At the distance δ\delta from its foot, the cosine-weighted visibility of the height field is A=12(1+δ/δ2+H2)A = \tfrac12 (1 + \delta / \sqrt{\delta^2 + H^2}), the view factor of a strip (proved in the proofs folder). The code uses 32 slices and steps of 0.25 units with no radius limit.

δ\delta exact GTAO value code HBAO with no falloff
2.5 0.649 0.654 0.596
4.5 0.745 0.750 0.663
8.5 0.864 0.867 0.760

The code is within 0.005 of the formula; the rest comes from the step length at the edge of the block. HBAO without falloff measures the solid angle without the cosine, so the same wall darkens the point more: directions near the ground count as much as directions near the normal.

One layer. Replace the block by a plate of thickness 1 that floats 4 units above the floor and is 6 units wide. The depth buffer looks the same as for a solid block 5 units high and 6 wide. At a floor point 3.5 units from the plate, the code gives A=0.792A = 0.792. Cosine-weighted rays against the true plate, which can pass under it, give 0.8280.828 with 40000 rays. The method is exact for the depth buffer but not for the scene.

Correctness

The proofs are in the proofs folder. In slice coordinates, a direction is ω=cos⁡h v+sin⁡h c(φ)\omega = \cos h \, v + \sin h \, c(\varphi) with φ∈[0,π)\varphi \in [0, \pi) and h∈(−π,π]h \in (-\pi, \pi]; this covers the sphere once, with dω=∣sin⁡h∣ dh dφd\omega = |\sin h| \, dh \, d\varphi, and n⋅ω=∣np∣cos⁡(h−γ)n \cdot \omega = |n_p| \cos(h - \gamma). Under the height-field assumption, the open directions of a slice are those between the two clamped horizons, so the cosine-weighted visibility is 1π∫0π∣np∣∫h1h2cos⁡(h−γ)∣sin⁡h∣ dh dφ\frac1\pi \int_0^\pi |n_p| \int_{h_1}^{h_2} \cos(h - \gamma) |\sin h| \, dh \, d\varphi, and line L6 is the inner integral in closed form. An open slice gives cos⁡γ+γsin⁡γ\cos\gamma + \gamma\sin\gamma, and the outer integral of an open hemisphere is exactly 1, so every plane gives A=1A = 1. The wall formula of the example is proved with a standard integral. The tests check the closed form against Simpson's rule, planes against 1, and the wall against both the formula and cosine-weighted rays. That the result also matches ray traced ambient occlusion is true only for the height field; for real scenes it is a measurement, as the plate shows.

Proof: The slice integral of ground-truth ambient occlusion and its closed formfull

Setting. The camera is orthographic and looks along −z-z, so the view vector is v=(0,0,1)v = (0, 0, 1) at every pixel, as in the code. A pixel has the point PP and the unit normal nn with n⋅v>0n \cdot v > 0. For φ∈[0,π)\varphi \in [0, \pi) let c(φ)=(cos⁡φ,sin⁡φ,0)c(\varphi) = (\cos\varphi, \sin\varphi, 0). The slice φ\varphi is the plane spanned by vv and cc, and a direction in it is ω(h,φ)=cos⁡h v+sin⁡h c\omega(h, \varphi) = \cos h \, v + \sin h \, c with h∈(−π,π]h \in (-\pi, \pi], measured from vv and positive toward cc. The projection of nn into the slice is np=(n⋅c) c+(n⋅v) vn_p = (n \cdot c)\, c + (n \cdot v)\, v, with the length ∣np∣|n_p| and the angle γ=atan2⁡(n⋅c,n⋅v)∈(−π/2,π/2)\gamma = \operatorname{atan2}(n \cdot c, n \cdot v) \in (-\pi/2, \pi/2) from vv. The height-field assumption: in each slice, the directions between the two horizons h1≤0≤h2h_1 \le 0 \le h_2 are open and the others are blocked, where the horizons are clamped to [γ−π/2,γ+π/2][\gamma - \pi/2, \gamma + \pi/2]. The ambient occlusion visibility is A=1π∫n⋅ω>0V(ω) (n⋅ω) dωA = \frac{1}{\pi} \int_{n \cdot \omega > 0} V(\omega)\, (n \cdot \omega)\, d\omega.

Lemma 1 (slice coordinates). The map (h,φ)↦ω(h,φ)(h, \varphi) \mapsto \omega(h, \varphi) on (−π,π]×[0,π)(-\pi, \pi] \times [0, \pi) covers the unit sphere once, apart from the two directions ±v\pm v, with dω=∣sin⁡h∣ dh dφd\omega = |\sin h| \, dh \, d\varphi. In it, n⋅ω=∣np∣cos⁡(h−γ)n \cdot \omega = |n_p| \cos(h - \gamma).

Proof. With vv as the polar axis, a direction with h>0h > 0 has the polar angle hh and the azimuth φ\varphi, and one with h<0h < 0 has the polar angle −h-h and the azimuth φ+π\varphi + \pi. As φ\varphi runs over [0,π)[0, \pi) the two cases cover all azimuths once, and the spherical element is sin⁡(polar) d(polar) d(azimuth)=∣sin⁡h∣ dh dφ\sin(\text{polar}) \, d(\text{polar}) \, d(\text{azimuth}) = |\sin h| \, dh \, d\varphi. Next, n⋅ω=(n⋅v)cos⁡h+(n⋅c)sin⁡h=∣np∣(cos⁡γcos⁡h+sin⁡γsin⁡h)=∣np∣cos⁡(h−γ)n \cdot \omega = (n \cdot v) \cos h + (n \cdot c) \sin h = |n_p| (\cos\gamma \cos h + \sin\gamma \sin h) = |n_p| \cos(h - \gamma). □\square

Theorem 1 (the slice integral). Under the height-field assumption,

A=1π∫0π∣np∣ a^(φ) dφ,a^=∫h1h2cos⁡(h−γ) ∣sin⁡h∣ dh.A = \frac{1}{\pi} \int_0^\pi |n_p| \, \hat a(\varphi) \, d\varphi, \qquad \hat a = \int_{h_1}^{h_2} \cos(h - \gamma)\, |\sin h| \, dh.

Proof. By Lemma 1, n⋅ω>0n \cdot \omega > 0 in the slice exactly for h∈(γ−π/2,γ+π/2)h \in (\gamma - \pi/2, \gamma + \pi/2), and the open part of it is [h1,h2][h_1, h_2] because of the clamp. Substituting Lemma 1 into the definition of AA gives the formula. □\square

Theorem 2 (closed form). For h1≤0≤h2h_1 \le 0 \le h_2,

a^=14(−cos⁡(2h1−γ)+cos⁡γ+2h1sin⁡γ)+14(−cos⁡(2h2−γ)+cos⁡γ+2h2sin⁡γ).\hat a = \tfrac14 \big( -\cos(2h_1 - \gamma) + \cos\gamma + 2 h_1 \sin\gamma \big) + \tfrac14 \big( -\cos(2h_2 - \gamma) + \cos\gamma + 2 h_2 \sin\gamma \big).

Proof. On [0,h2][0, h_2], ∣sin⁡h∣=sin⁡h|\sin h| = \sin h and sin⁡hcos⁡(h−γ)=12(sin⁡(2h−γ)+sin⁡γ)\sin h \cos(h - \gamma) = \tfrac12 (\sin(2h - \gamma) + \sin\gamma), so

∫0h2sin⁡hcos⁡(h−γ) dh=12[−12cos⁡(2h−γ)+hsin⁡γ]0h2=14(−cos⁡(2h2−γ)+cos⁡γ+2h2sin⁡γ),\int_0^{h_2} \sin h \cos(h - \gamma)\, dh = \tfrac12 \Big[ -\tfrac12 \cos(2h - \gamma) + h \sin\gamma \Big]_0^{h_2} = \tfrac14 \big( -\cos(2h_2 - \gamma) + \cos\gamma + 2 h_2 \sin\gamma \big),

using cos⁡(−γ)=cos⁡γ\cos(-\gamma) = \cos\gamma. On [h1,0][h_1, 0], ∣sin⁡h∣=−sin⁡h|\sin h| = -\sin h, and the same antiderivative gives −12[−12cos⁡(2h−γ)+hsin⁡γ]h10=14(−cos⁡(2h1−γ)+cos⁡γ+2h1sin⁡γ)-\tfrac12 \big[ -\tfrac12 \cos(2h - \gamma) + h \sin\gamma \big]_{h_1}^{0} = \tfrac14 \big( -\cos(2h_1 - \gamma) + \cos\gamma + 2 h_1 \sin\gamma \big). □\square

The tests compare this form with Simpson's rule at random arguments and find agreement to 10−1010^{-10}. This page derives the formula itself; it is not copied from the report of Jimenez and others.

Theorem 3 (open surfaces). If every slice is open, h1=γ−π/2h_1 = \gamma - \pi/2 and h2=γ+π/2h_2 = \gamma + \pi/2, then a^=cos⁡γ+γsin⁡γ\hat a = \cos\gamma + \gamma \sin\gamma and A=1A = 1. In particular, a plane gives A=1A = 1, and a frontal plane gives a^=1\hat a = 1 in every slice.

Proof. With h1,2=γ∓π/2h_{1,2} = \gamma \mp \pi/2, cos⁡(2h1,2−γ)=cos⁡(γ∓π)=−cos⁡γ\cos(2h_{1,2} - \gamma) = \cos(\gamma \mp \pi) = -\cos\gamma, and Theorem 2 gives 14(4cos⁡γ+4γsin⁡γ)\tfrac14 (4 \cos\gamma + 4\gamma \sin\gamma). The integral of Theorem 1 is then 1π∫n⋅ω>0n⋅ω dω=1\frac1\pi \int_{n \cdot \omega > 0} n \cdot \omega \, d\omega = 1, the cosine integral over a hemisphere. On a plane, every sample lies in the tangent plane, so no horizon rises above the clamp. For n=vn = v, γ=0\gamma = 0 and a^=1\hat a = 1. □\square

The code sums mm equally spaced slices, the rectangle rule for an integrand that is smooth and periodic in φ\varphi with period π\pi. For a tilted plane the sum is not exactly 1, but the error falls fast with mm: the tests measure an error below 10−910^{-9} with 16 slices for slopes up to 1.3.

Theorem 4 (the wall). Let PP lie on a frontal floor, n=vn = v, at the distance δ>0\delta > 0 from the foot of an infinite straight wall that rises by HH toward the camera, with a flat top. With no radius limit,

A=12(1+δδ2+H2).A = \frac12 \Big( 1 + \frac{\delta}{\sqrt{\delta^2 + H^2}} \Big).

Proof. Here γ=0\gamma = 0 and ∣np∣=1|n_p| = 1. Put the wall at x≥δx \ge \delta. In the slice φ\varphi with cos⁡φ≠0\cos\varphi \ne 0, the side that points to +x+x reaches the foot at the horizontal distance δ/∣cos⁡φ∣\delta / |\cos\varphi|, and the top edge has the elevation ee above the view plane with tan⁡e=H∣cos⁡φ∣/δ\tan e = H |\cos\varphi| / \delta, which is the largest elevation on that side. So that horizon is π/2−e\pi/2 - e in absolute value, and the other side is open with the horizon π/2\pi/2. By Theorem 2 with γ=0\gamma = 0, the open side gives 14(1−cos⁡π)=12\tfrac14 (1 - \cos\pi) = \tfrac12, and the wall side gives 14(1−cos⁡(π−2e))=14(1+cos⁡2e)=12cos⁡2e\tfrac14 (1 - \cos(\pi - 2e)) = \tfrac14 (1 + \cos 2e) = \tfrac12 \cos^2 e. So a^=1−12sin⁡2e\hat a = 1 - \tfrac12 \sin^2 e with sin⁡2e=H2cos⁡2φ/(δ2+H2cos⁡2φ)\sin^2 e = H^2 \cos^2\varphi / (\delta^2 + H^2 \cos^2\varphi), and

1−A=12π∫0πH2cos⁡2φδ2+H2cos⁡2φ dφ=12π(π−δ2∫0πdφδ2+H2cos⁡2φ).1 - A = \frac{1}{2\pi} \int_0^\pi \frac{H^2 \cos^2\varphi}{\delta^2 + H^2 \cos^2\varphi} \, d\varphi = \frac{1}{2\pi} \Big( \pi - \delta^2 \int_0^\pi \frac{d\varphi}{\delta^2 + H^2 \cos^2\varphi} \Big).

The standard integral ∫0πdφ/(a+bcos⁡2φ)=π/a(a+b)\int_0^\pi d\varphi / (a + b \cos^2\varphi) = \pi / \sqrt{a (a + b)} for a>0a > 0, b≥0b \ge 0 gives π/(δδ2+H2)\pi / (\delta \sqrt{\delta^2 + H^2}), so 1−A=12(1−δ/δ2+H2)1 - A = \tfrac12 (1 - \delta / \sqrt{\delta^2 + H^2}). □\square

This is the view factor of an infinite strip seen from a point, which also follows from the crossed-strings rule. The same wall gives 1−arctan⁡(H/δ)/π1 - \arctan(H/\delta)/\pi under the solid-angle measure of horizon-based ambient occlusion. The tests check the formula by cosine-weighted Monte Carlo rays and the code against it within 0.01.

Theorem 5 (range). In the integral of Theorem 1, 0≤A≤10 \le A \le 1, and the occlusion grows when a horizon rises.

Proof. On [h1,h2]⊆[γ−π/2,γ+π/2][h_1, h_2] \subseteq [\gamma - \pi/2, \gamma + \pi/2] the integrand cos⁡(h−γ)∣sin⁡h∣\cos(h - \gamma) |\sin h| is non-negative, so a^≥0\hat a \ge 0 and a^\hat a shrinks when [h1,h2][h_1, h_2] shrinks. The largest value is the open case of Theorem 3. □\square

What is not a theorem. The match of AA with ray traced ambient occlusion holds under the height-field assumption, that is, for the scene as the one layer of the depth buffer shows it. A real scene can have open space behind the visible surface. The tests render a plate of thickness 1 whose bottom is 4 units above the floor: the depth buffer sees only its top, as if it were a solid block, and the code gives A=0.792A = 0.792 at a floor point 3.5 units from the plate, while cosine-weighted rays against the true plate give 0.8280.828. Any statement about how close GTAO comes to ray traced ambient occlusion in real scenes is a measurement.

Theorem 6 (cost). For pp pixels, mm slices and ss steps per side, the cost is O(pms)O(p m s).

Proof. Each slice marches 2s2s steps of O(1)O(1) work and evaluates Theorem 2 once. □\square

Complexity

The model is the real RAM. Each pixel marches mm slices with 2s2s steps each and evaluates the closed form mm times: O(pms)O(p m s) in total, and O(p)O(p) memory for the result. This is the cost of HBAO with 2m2m directions. The closed form costs a few trigonometric functions per slice, which is small next to the depth reads.

Properties

  • Cosine weighted. The value is the ambient occlusion integral with the cosine to the normal, not the solid angle.
  • Exact for the height field. With exact horizons and many slices, the result is the visibility of the depth buffer read as a solid surface.
  • One layer. Space behind the visible surface counts as blocked, so thin objects over-occlude.
  • Planes are open. Every plane gives A=1A = 1, tilted or not.
  • Smooth in the slice. The inner integral needs no samples, only the two horizons.
  • Screen space. Off-screen geometry does not occlude.

Variants and improvements

  • Multiple bounces. The report maps the visibility to an approximate multi-bounce value with a function fitted to ray traced data, as a function of the visibility and the albedo. The fit is a measurement.
  • Specular occlusion. The report also derives an occlusion term for glossy reflections from the visibility and a bent normal.
  • Thickness heuristic. Let the horizon fall back over distance, as if objects had a finite thickness, which reduces the over-occlusion of thin objects.
  • Temporal accumulation. One or two slices per pixel and frame, with a different rotation each frame, filtered over time as in temporal antialiasing.
  • Bitmask visibility. Later methods replace the two horizons by a bit mask of open sectors per slice, which can represent gaps behind thin objects.

When to use it

Use GTAO when the ambient occlusion of a real-time renderer should look close to that of a ray tracer and the budget is that of HBAO. It needs depth and normals and a denoiser. Use ray traced ambient occlusion when thin geometry, off-screen occluders or the space behind the first layer matter.

Pitfalls

  • Ground truth of what. The match is for the depth buffer as a height field. Thin objects, foliage and gaps under objects come out too dark.
  • Wrong normals. The clamp and γ\gamma depend on the normal. Normals from depth differences tilt at edges, and normal maps give normals that do not match the depth surface.
  • Radius. A limit on the march radius opens far occluders abruptly. Use a falloff and accept it as tuning.
  • Perspective. In a perspective camera the view vector and the slice change per pixel. Using a constant view vector bends the slices near the edges of a wide view.
  • Noise. Few slices need filtering, and the filter must respect depth edges, or the occlusion leaks across them.

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.

ground_truth_ambient_occlusion.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ground-truth-ambient-occlusion/. The authors are listed in prov/2H8H92.jsonl.

"""Ground-truth ambient occlusion: horizons per slice and a closed-form
cosine-weighted inner integral.

The camera is orthographic and looks along -z, so the view vector is
v = (0, 0, 1) everywhere and the tests can use height fields. The pixel (i, j)
has its center at (i + 1/2, j + 1/2) in view units, D[j][i] is the positive
view depth, and the point of a pixel is (x, y, -d).

A slice is the plane through v and a screen direction (cos phi, sin phi, 0).
Angles h in a slice are measured from v, positive toward the screen
direction. The two horizons h1 <= 0 <= h2 are found by marching the depth
buffer both ways and clamped to the hemisphere of the normal. The visibility is

    A = (1 / pi) integral over phi in [0, pi) of |n_p| a(phi) dphi,
    a = integral from h1 to h2 of cos(h - gamma) |sin h| dh,

where n_p is the normal projected into the slice and gamma its angle from v.
The inner integral has the closed form of inner_integral().
"""

import math
from typing import List, Optional, Tuple

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


def lookup(D: Grid, x: float, y: float, mode: str = "nearest") -> float:
    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), min(int(v), h - 2)
    fu, fv = u - i0, v - j0
    top = D[j0][i0] * (1 - fu) + D[j0][i0 + 1] * fu
    bot = D[j0 + 1][i0] * (1 - fu) + D[j0 + 1][i0 + 1] * fu
    return top * (1 - fv) + bot * fv


def normal_from_depth(D: Grid, i: int, j: int) -> Vec:
    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)
    gy = (D[jt][i] - D[jb][i]) / (jt - jb)
    s = math.sqrt(gx * gx + gy * gy + 1.0)
    return (gx / s, gy / s, 1.0 / s)


def inner_integral(h1: float, h2: float, gamma: float) -> float:
    """The integral of cos(h - gamma) |sin h| over [h1, h2], for h1 <= 0 <= h2."""
    a = 0.25 * (-math.cos(2 * h1 - gamma) + math.cos(gamma) + 2 * h1 * math.sin(gamma))
    b = 0.25 * (-math.cos(2 * h2 - gamma) + math.cos(gamma) + 2 * h2 * math.sin(gamma))
    return a + b


def _max_cos(D, px, py, d, cx, cy, steps, step, radius, start, mode):
    """The largest cosine to v of the samples on one side, starting at the
    cosine of the clamped tangent horizon."""
    best = start
    for s in range(1, steps + 1):
        r = s * step
        dz = d - lookup(D, px + r * cx, py + r * cy, mode)
        dist = math.hypot(r, dz)
        if dist > radius:
            continue
        best = max(best, dz / dist)
    return best


def gtao_pixel(
    D: Grid,
    i: int,
    j: int,
    slices: int,
    steps: int,
    step: float,
    radius: float,
    jitter: float = 0.0,
    normal: Optional[Vec] = None,
    mode: str = "nearest",
) -> float:
    d = D[j][i]
    px, py = i + 0.5, j + 0.5
    n = normal if normal is not None else normal_from_depth(D, i, j)
    acc = 0.0  # @line L1
    for k in range(slices):  # @line L2
        phi = math.pi * (k + jitter) / slices
        cx, cy = math.cos(phi), math.sin(phi)
        n_dir = n[0] * cx + n[1] * cy  # @line L3
        n_v = n[2]
        length = math.hypot(n_dir, n_v)
        gamma = math.atan2(n_dir, n_v)
        # The tangent horizons gamma -/+ pi/2 have the cosines sin(gamma) and -sin(gamma).
        c2 = _max_cos(D, px, py, d, cx, cy, steps, step, radius, -math.sin(gamma), mode)  # @line L4
        c1 = _max_cos(D, px, py, d, -cx, -cy, steps, step, radius, math.sin(gamma), mode)  # @line L5
        h1 = -math.acos(min(1.0, c1))  # @line L6
        h2 = math.acos(min(1.0, c2))
        acc += length * inner_integral(h1, h2, gamma)  # @line L7
    return acc / slices  # @line L8


def gtao(D: Grid, slices: int, steps: int, step: float, radius: float, **kw) -> Grid:
    return [[gtao_pixel(D, i, j, slices, steps, step, radius, **kw) for i in range(len(D[0]))] for j in range(len(D))]


def wall_reference(delta: float, height: float) -> float:
    """The cosine-weighted visibility of a point on a frontal floor at the
    distance delta from an infinite wall of the given height, with no radius
    limit: (1 + delta / sqrt(delta^2 + height^2)) / 2."""
    return 0.5 * (1.0 + delta / math.hypot(delta, height))
test_ground_truth_ambient_occlusion.py 102 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ground-truth-ambient-occlusion/. The authors are listed in prov/2H8H92.jsonl.

"""GTAO: the closed form, planes, the wall, and the limit of one depth layer."""

import math
import random

from ground_truth_ambient_occlusion import (
    gtao,
    gtao_pixel,
    inner_integral,
    wall_reference,
)

FLOOR = 200.0


def simpson(f, a, b, n=2000):
    h = (b - a) / n
    s = f(a) + f(b)
    for k in range(1, n):
        s += (4 if k % 2 else 2) * f(a + k * h)
    return s * h / 3


def test_closed_form_matches_quadrature() -> None:
    rng = random.Random(81)
    for _ in range(40):
        gamma = rng.uniform(-1.5, 1.5)
        h1 = rng.uniform(gamma - math.pi / 2, 0.0) if gamma < math.pi / 2 else 0.0
        h2 = rng.uniform(0.0, gamma + math.pi / 2)
        ref = simpson(lambda h: math.cos(h - gamma) * abs(math.sin(h)), h1, 0.0) + simpson(
            lambda h: math.cos(h - gamma) * abs(math.sin(h)), 0.0, h2
        )
        assert abs(inner_integral(h1, h2, gamma) - ref) < 1e-10
    assert abs(inner_integral(-math.pi / 2, math.pi / 2, 0.0) - 1.0) < 1e-15


def test_open_slice_integrates_to_one_over_the_hemisphere() -> None:
    # For a normal tilted by beta, (1/pi) * integral of |n_p| (cos g + g sin g) is 1.
    for beta in (0.2, 0.7, 1.2):
        def f(phi):
            nd, nv = math.sin(beta) * math.cos(phi), math.cos(beta)
            g = math.atan2(nd, nv)
            return math.hypot(nd, nv) * inner_integral(g - math.pi / 2, g + math.pi / 2, g)
        assert abs(simpson(f, 0.0, math.pi) / math.pi - 1.0) < 1e-10


def test_planes_are_open() -> None:
    for gx, gy in [(0.0, 0.0), (0.4, 0.0), (-0.3, 0.6), (1.2, 0.5)]:
        D = [[100.0 + gx * (i + 0.5) + gy * (j + 0.5) for i in range(60)] for j in range(60)]
        A = gtao_pixel(D, 30, 30, 16, 20, 1.0, 1e9, jitter=0.5, mode="bilinear")
        assert abs(A - 1.0) < 1e-9


def test_wall_matches_the_cosine_weighted_formula() -> None:
    D = [[FLOOR if i < 100 else FLOOR - 8.0 for i in range(200)] for _ in range(200)]
    for i, delta in ((97, 2.5), (95, 4.5), (91, 8.5)):
        A = gtao_pixel(D, i, 100, 32, 360, 0.25, 1e9, jitter=0.5)
        assert abs(A - wall_reference(delta, 8.0)) < 0.01
    assert wall_reference(0.0, 8.0) == 0.5


def test_wall_formula_by_cosine_weighted_rays() -> None:
    rng = random.Random(82)
    delta, H, count, hit = 3.0, 5.0, 40000, 0
    for _ in range(count):
        u1, u2 = rng.random(), rng.random()
        ox = math.sqrt(u1) * math.cos(2 * math.pi * u2)
        oz = math.sqrt(1.0 - u1)
        if ox > 0 and oz * (delta / ox) < H:
            hit += 1
    assert abs((1 - hit / count) - wall_reference(delta, H)) < 0.01


def test_one_layer_over_occludes_a_floating_plate() -> None:
    # A plate of thickness 1 over x in [20, 26), its bottom 4 units above the
    # floor. The depth buffer shows only its top, as if it were a solid block.
    D = [[FLOOR - 5.0 if 20 <= i < 26 else FLOOR for i in range(60)] for _ in range(40)]
    A = gtao_pixel(D, 16, 20, 32, 200, 0.25, 1e9, jitter=0.5)
    rng = random.Random(83)
    delta, L, H, tau, count, hit = 3.5, 6.0, 4.0, 1.0, 40000, 0
    for _ in range(count):
        u1, u2 = rng.random(), rng.random()
        ox = math.sqrt(u1) * math.cos(2 * math.pi * u2)
        oz = math.sqrt(1.0 - u1)
        if ox <= 0:
            continue
        t0 = max(delta / ox, H / oz)
        t1 = min((delta + L) / ox, (H + tau) / oz)
        if t0 <= t1:
            hit += 1
    traced = 1 - hit / count
    assert A < traced - 0.02


def test_whole_image_in_range() -> None:
    rng = random.Random(84)
    D = [[50.0 + rng.uniform(-4, 4) for _ in range(14)] for _ in range(12)]
    A = gtao(D, 4, 4, 1.0, 6.0)
    assert all(-1e-12 <= a <= 1.0 + 1e-12 for row in A for a in row)

History

Horizon-based ambient occlusion of 2008 integrated the sine of the horizon angle over screen directions, which measures solid angle. Jimenez, Wu, Pesce and Jarabo (2016) reformulated the integral in slices through the view vector, with two horizons per slice and the cosine weight inside, solved the inner integral in closed form, and compared the result with ray traced references on the depth buffer. Their report also added a fitted multi-bounce term and a specular occlusion term, and it was used in a game engine of Activision. Later screen-space methods kept the slice structure and changed the horizon model, for example with bit masks of open sectors.

References

  1. Jorge Jimenez, Xian-Chun Wu, Angelo Pesce and Adrian Jarabo, Practical real-time strategies for accurate indirect occlusion, Activision technical report ATVI-TR-16-01, 2016, the slice formulation of the cosine-weighted visibility, the horizon search on both sides of a slice, the inner integral in closed form, and the comparison with ray traced references
  2. Louis Bavoil, Miguel Sainz and Rouslan Dimitrov, Image-space horizon-based ambient occlusion, SIGGRAPH 2008 talks, the horizon angles found by marching the depth buffer, which GTAO keeps
  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 horizon-based methods)

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