Algorithm Search⌘K

Algorithmadvanced

Precomputed atmospheric scattering

Also called Bruneton atmospheric scattering.

Precompute transmittance and single and multiple Rayleigh and Mie scattering into 2D and 4D tables, so that sky and aerial perspective render from any altitude with a few lookups.

Time
Θ(q) single_scattering_rayΘ(t q) transmittance_table
Space
Θ(t) table
Where
q = the number of quadrature steps along one ray; t = the number of entries of the transmittance table
Properties
deterministicnot in placeofflineiterative
Origin
Eric Bruneton, Fabrice Neyret, 2008

Precomputed atmospheric scattering draws the color of a clear sky, and the haze between the camera and distant objects, from tables that are computed once for a given atmosphere. The atmosphere is a spherical shell around the planet, with air molecules that scatter by the Rayleigh law and aerosols that scatter by the Mie law, each with a density that falls exponentially with altitude. Bruneton and Neyret (2008) store the transmittance in a 2D table over altitude and view angle, and the single and multiple scattered light in a 4D table over altitude, view angle, sun angle and the angle between the view and the sun. A pixel then costs a few texture reads, from any altitude and for any sun position. This page explains the method and gives a toy version in code: the code builds the transmittance table and computes single scattering along one view ray by quadrature with it. The toy does not build the 4D table and has no multiple scattering, and its numbers are those of a toy atmosphere.

In plain words

Sunlight that enters the air bounces off molecules and small particles. Blue light bounces much more than red light, which is why the sky looks blue, and why the sun looks red near the horizon, when its light crosses much more air. To find the color of the sky in one direction, you would add up the light that bounces toward you from every point along that direction, weakened by the air it crosses on its way. That sum is slow. But in a round planet with layered air, the answer only depends on a few numbers: how high you are, where you look and where the sun is. So the method works out the answer for many such cases ahead of time and stores them in tables. At run time it reads the tables.

The problem

The input is an atmosphere: the ground radius RgR_g, the top radius RtR_t, the scattering and extinction coefficients of molecules and aerosols at sea level, their scale heights, and the phase functions. The output is the radiance L(x,v)L(x, v) that reaches a point xx from the direction −v-v, for the sun at a fixed direction ℓ\ell with irradiance EsunE_{\text{sun}}, and the transmittance T(x,y)T(x, y) between two points. The standing assumptions are physical laws of the model, stated as such:

  • Extinction. Light along a segment is attenuated by T(x,y)=exp⁡(−∫xyσ)T(x, y) = \exp(-\int_x^y \sigma), the Beer-Lambert law, with σ(h)=βR(h)+βMext(h)\sigma(h) = \beta_R(h) + \beta_M^{\text{ext}}(h).
  • Density. βR(h)=βR(0)e−h/HR\beta_R(h) = \beta_R(0) e^{-h/H_R} and βM(h)=βM(0)e−h/HM\beta_M(h) = \beta_M(0) e^{-h/H_M} at altitude hh. Bruneton and Neyret use HR=8H_R = 8 km and HM=1.2H_M = 1.2 km, and βR(0)=(5.8,13.5,33.1)×10−3\beta_R(0) = (5.8, 13.5, 33.1) \times 10^{-3} per km at 680, 550 and 440 nm. These ratios follow the λ−4\lambda^{-4} law of Rayleigh scattering within 1%.
  • Phase functions. Rayleigh PR(ν)=316π(1+ν2)P_R(\nu) = \frac{3}{16\pi}(1 + \nu^2) and the Cornette-Shanks function PM(ν)=38π1−g22+g21+ν2(1+g2−2gν)3/2P_M(\nu) = \frac{3}{8\pi} \frac{1 - g^2}{2 + g^2} \frac{1 + \nu^2}{(1 + g^2 - 2g\nu)^{3/2}} for Mie, with ν\nu the cosine of the angle between the view and the sun.
  • Symmetry. The atmosphere depends only on altitude. Then LL depends only on r=∣x∣r = |x|, μ=v⋅x/r\mu = v \cdot x / r, μs=ℓ⋅x/r\mu_s = \ell \cdot x / r and ν=v⋅ℓ\nu = v \cdot \ell, four numbers. This is why a 4D table is enough.

The single scattered part is

L1(x,v)=Esun∫0DT(x,ys) V(ys) Tsun(ys)(βR(ys)PR(ν)+βM(ys)PM(ν)) ds,L_1(x, v) = E_{\text{sun}} \int_0^D T(x, y_s)\, V(y_s)\, T_{\text{sun}}(y_s) \big(\beta_R(y_s) P_R(\nu) + \beta_M(y_s) P_M(\nu)\big)\, ds,

with ys=x+svy_s = x + s v, DD the distance to the ground or to the top, VV the visibility of the sun and TsunT_{\text{sun}} the transmittance from ysy_s toward the sun. Higher orders replace EsunTsunE_{\text{sun}} T_{\text{sun}} by the light of the previous order that arrives at ysy_s from all directions.

The algorithm

The full method of Bruneton and Neyret has these steps:

  1. Transmittance. Compute T(r,μ)T(r, \mu) to the top of the atmosphere on a 2D grid, by quadrature of the optical depth.
  2. Single scattering. Compute L1(r,μ,μs,ν)L_1(r, \mu, \mu_s, \nu) on a 4D grid, by quadrature along each ray, with every transmittance read from step 1. Implementations usually keep the single scattering phase functions out of the table and apply them per pixel, so that the sharp forward peak of Mie scattering does not need a fine angular grid (a design choice, not a requirement).
  3. Ground irradiance. Compute the irradiance on the ground as a function of rr and μs\mu_s, for light that the ground reflects back into the air.
  4. Higher orders. For each order k=2,…,ok = 2, \dots, o: at every 4D grid point, integrate the order k−1k - 1 light over mm incoming directions with the phase functions, which gives the scattering density; then integrate that density along each ray with the transmittance, and add the result to the 4D table.
  5. Rendering. For a sky pixel, read the 4D table at the camera and multiply by the phase functions. For a surface at yy seen from xx, the aerial perspective is L(x)−T(x,y)L(y)L(x) - T(x, y) L(y), two 4D lookups and one transmittance, and the surface color is attenuated by T(x,y)T(x, y).

The toy code covers step 1 and step 2 for one view ray:

  1. SINGLE-SCATTERING(r, μ, μs, ν)
  2. 1for each table entry (x_r, x_μ): T[x_r][x_μ] ← exp(-optical depth from (r, μ) to the top) ▷ once
  3. 2D ← distance to the ground if the ray hits it, else to the top
  4. 3S ← 0
  5. 4for k ← 0 to q: s ← k D / q; w ← 1/2 at the two ends, 1 inside
  6. 5r_s ← sqrt(r² + s² + 2 r μ s); μ_s,y ← (r μs + s ν) / r_s
  7. 6T_view ← T(r, μ) / T(r_s, μ_y), or T(r_s, -μ_y) / T(r, -μ) if the ray hits the ground
  8. 7if the sun is below the horizon at r_s, skip this step; else T_sun ← T(r_s, μ_s,y)
  9. 8S ← S + w · T_view · T_sun · (β_R(r_s) P_R(ν) + β_M(r_s) P_M(ν))
  10. 9return S · D / q

Line L1 fills the transmittance table at the rays given by the mapping of Bruneton's 2017 code: xr=ρ/Hx_r = \rho / H with ρ=r2−Rg2\rho = \sqrt{r^2 - R_g^2} and H=Rt2−Rg2H = \sqrt{R_t^2 - R_g^2}, and xμx_\mu the distance dd to the top scaled between its least value Rt−rR_t - r (looking up) and its largest value ρ+H\rho + H (along the horizon). Lookups are bilinear in (xr,xμ)(x_r, x_\mu). Line L2 gives the length of the ray in the atmosphere. Line L5 uses the law of cosines for the point at distance ss. Line L6 gets the transmittance of the part of the ray up to ss from two table entries, because transmittance multiplies along a ray. Line L7 checks whether the planet hides the sun at that point. Line L8 adds the light scattered toward the camera, and line L9 finishes the trapezoidal rule.

Example

The toy atmosphere uses the Rayleigh values above, Rg=6360R_g = 6360 km, Rt=6420R_t = 6420 km, βM(0)=4×10−3\beta_M(0) = 4 \times 10^{-3} per km, an albedo of 0.9 for the aerosols and g=0.8g = 0.8; these last values are tuning of the toy. The table has 32×6432 \times 64 entries with 200 steps each, and single scattering uses q=100q = 100. The three numbers are red, green and blue, per unit sun irradiance.

view from the ground quantity red green blue
straight up transmittance to the top 0.9496 0.8929 0.7633
along the horizon (876 km of air) transmittance to the top 0.1192 0.0135 0.0001
straight up, sun at the zenith single scattering, 1/sr 0.0242 0.0293 0.0393
straight up, sun 60 degrees from the zenith single scattering, 1/sr 0.0033 0.0069 0.0133
78 degrees from the zenith, toward a setting sun (μs=0.05\mu_s = 0.05, ν=0.9\nu = 0.9) single scattering, 1/sr 0.0190 0.0216 0.0135

These are measurements of the toy. The zenith is blue when the sun is high, by a factor of 4 between blue and red, and the light near a low sun is yellow and red, because the blue part of the sunlight is lost on the long path to each scattering point. The table lookups agree with direct quadrature to within 1.7×10−31.7 \times 10^{-3} in transmittance over random rays, and the single scattering values to within 1% for the five test rays. With a table that is linear in μ\mu instead of in the distance dd, the largest transmittance error grew to 4.6×10−24.6 \times 10^{-2}, all of it near the horizon.

Correctness

The proof shows that line L5 gives the altitude and the sun angle at each point of the ray, that the ground test of lines L2 and L7 is exact, that the table mapping of line L1 is a bijection with the stated inverse, that line L6 equals the transmittance of the segment (because optical depth adds along a ray and does not depend on the direction), that the phase functions integrate to 1 over the sphere for any gg, and that lines L3 to L9 are the trapezoidal rule for the single scattering integral, which converges as qq grows. These are proved properties. The model itself (exponential layers, Rayleigh and Mie laws, single and multiple scattering) is physical law applied to an idealized atmosphere. The error of the bilinear table is not bounded by the proof; it is a measurement of the tests.

Proof: Correctness of the transmittance table and the single scattering sumfull

Setting. The planet is a ball of radius RgR_g with its center at the origin, and the atmosphere is the shell up to radius RtR_t. The extinction coefficient σ(y)\sigma(y) depends only on ∣y∣|y| and is continuous and nonnegative. A view ray starts at xx with ∣x∣=r|x| = r, in the unit direction vv with μ=v⋅x/r\mu = v \cdot x / r; the sun is in the unit direction ℓ\ell with μs=ℓ⋅x/r\mu_s = \ell \cdot x / r and ν=v⋅ℓ\nu = v \cdot \ell. The transmittance of a segment [y,z][y, z] is T(y,z)=exp⁡(−∫[y,z]σ)T(y, z) = \exp\big(-\int_{[y, z]} \sigma\big), and T(r,μ)T(r, \mu) is the transmittance from xx to the top boundary along a ray that does not hit the ground. The claims are in exact arithmetic, except where a claim names the quadrature.

Claim 1 (the point on the ray). The point y=x+svy = x + s v has ∣y∣=rs=r2+s2+2rμs|y| = r_s = \sqrt{r^2 + s^2 + 2 r \mu s}, view cosine μy=(rμ+s)/rs\mu_y = (r \mu + s) / r_s and sun cosine μs,y=(rμs+sν)/rs\mu_{s,y} = (r \mu_s + s \nu) / r_s (line L5).

Proof. ∣y∣2=r2+2s x⋅v+s2|y|^2 = r^2 + 2 s\, x \cdot v + s^2 and x⋅v=rμx \cdot v = r \mu. The view cosine at yy is v⋅y/∣y∣=(rμ+s)/rsv \cdot y / |y| = (r\mu + s)/r_s, and the sun cosine is ℓ⋅y/∣y∣=(ℓ⋅x+s ℓ⋅v)/rs=(rμs+sν)/rs\ell \cdot y / |y| = (\ell \cdot x + s\, \ell \cdot v)/r_s = (r \mu_s + s \nu)/r_s. □\square

Claim 2 (the ground test). For r≥Rgr \ge R_g, the ray (r,μ)(r, \mu) meets the ground sphere at a positive distance if and only if μ<μh(r)=−1−(Rg/r)2\mu < \mu_h(r) = -\sqrt{1 - (R_g / r)^2}. The distances to the ground and to the top used in line L2 are −rμ−r2(μ2−1)+Rg2-r\mu - \sqrt{r^2(\mu^2 - 1) + R_g^2} and −rμ+r2(μ2−1)+Rt2-r\mu + \sqrt{r^2(\mu^2 - 1) + R_t^2}.

Proof. By Claim 1, ∣x+sv∣=R|x + s v| = R when s2+2rμs+r2−R2=0s^2 + 2 r \mu s + r^2 - R^2 = 0, so s=−rμ±r2(μ2−1)+R2s = -r\mu \pm \sqrt{r^2(\mu^2 - 1) + R^2}. For R=Rt>rR = R_t > r, the product of the roots r2−Rt2r^2 - R_t^2 is negative, so exactly one root is positive, the one with the plus sign. For R=Rg≤rR = R_g \le r, the product of the roots is r2−Rg2≥0r^2 - R_g^2 \ge 0 and their sum is −2rμ-2 r\mu. Real positive roots need a nonnegative discriminant, μ2≥1−Rg2/r2\mu^2 \ge 1 - R_g^2/r^2, and a positive sum, μ<0\mu < 0; together these say μ≤μh(r)\mu \le \mu_h(r). The tangent case μ=μh\mu = \mu_h only touches the sphere, which the code counts as a miss. The first hit is the smaller root, with the minus sign. □\square

Claim 3 (the table coordinates). Let H=Rt2−Rg2H = \sqrt{R_t^2 - R_g^2}, ρ=r2−Rg2\rho = \sqrt{r^2 - R_g^2} and dd the distance to the top. The map (r,μ)↦(xr,xμ)=(ρ/H, (d−(Rt−r))/(ρ+H−(Rt−r)))(r, \mu) \mapsto (x_r, x_\mu) = \big(\rho/H,\ (d - (R_t - r)) / (\rho + H - (R_t - r))\big) is a bijection from the rays that miss the ground, r∈[Rg,Rt]r \in [R_g, R_t] and μ∈[μh(r),1]\mu \in [\mu_h(r), 1], onto [0,1]2[0, 1]^2 (for r<Rtr < R_t), and its inverse is r=H2xr2+Rg2r = \sqrt{H^2 x_r^2 + R_g^2}, μ=(H2−ρ2−d2)/(2rd)\mu = (H^2 - \rho^2 - d^2)/(2 r d) with d=(Rt−r)+xμ(ρ+H−(Rt−r))d = (R_t - r) + x_\mu(\rho + H - (R_t - r)).

Proof. xrx_r is an increasing function of rr from 0 to 1. For fixed rr, Claim 2 gives d=−rμ+r2μ2+Rt2−r2d = -r\mu + \sqrt{r^2\mu^2 + R_t^2 - r^2}, whose derivative in μ\mu is −r+r2μ/⋅=−r(1−rμ/⋅)<0-r + r^2\mu / \sqrt{\cdot} = -r (1 - r\mu/\sqrt{\cdot}) < 0 since ⋅>r∣μ∣\sqrt{\cdot} > r|\mu|. So dd decreases strictly from its value at μh\mu_h to its value at μ=1\mu = 1, which is Rt−rR_t - r. At μh\mu_h the ray is tangent to the ground at distance ρ\rho from xx and then reaches the top after a further HH, so d=ρ+Hd = \rho + H. Hence xμx_\mu is a strictly monotone map onto [0,1][0, 1]. For the inverse, ∣x+dv∣=Rt|x + d v| = R_t gives r2+d2+2rμd=Rt2r^2 + d^2 + 2 r \mu d = R_t^2, so μ=(Rt2−r2−d2)/(2rd)\mu = (R_t^2 - r^2 - d^2)/(2rd), and Rt2−r2=(H2+Rg2)−(ρ2+Rg2)=H2−ρ2R_t^2 - r^2 = (H^2 + R_g^2) - (\rho^2 + R_g^2) = H^2 - \rho^2. □\square

So line L1 fills the table at well defined rays, and a lookup returns the bilinear interpolation of the exact table values at the coordinates of the query.

Claim 4 (transmittance from two lookups). Let y=x+svy = x + s v with 0≤s≤D0 \le s \le D, where DD is the distance of line L2. If the ray misses the ground, T(x,y)=T(r,μ)/T(rs,μy)T(x, y) = T(r, \mu) / T(r_s, \mu_y). If it hits the ground, T(x,y)=T(rs,−μy)/T(r,−μ)T(x, y) = T(r_s, -\mu_y) / T(r, -\mu). This is line L6.

Proof. The optical depth is an integral over a segment, so it adds over consecutive segments, and TT multiplies: T(x,z)=T(x,y) T(y,z)T(x, z) = T(x, y)\, T(y, z) for yy on [x,z][x, z]. It depends only on the segment, not on the direction, so T(x,y)=T(y,x)T(x, y) = T(y, x). If the ray misses the ground, let zz be its exit point at the top. The ray from yy in direction vv is the rest of the same ray, with (rs,μy)(r_s, \mu_y) by Claim 1, so T(r,μ)=T(x,y) T(rs,μy)T(r, \mu) = T(x, y)\, T(r_s, \mu_y), and T(rs,μy)>0T(r_s, \mu_y) > 0. If the ray hits the ground, the cosine μt=(rμ+t)/rt\mu_t = (r\mu + t)/r_t is negative for all t<Dt < D (by Claim 2 the hit is before the closest approach to the center, where rμ+t=0r\mu + t = 0), so −μ>0-\mu > 0 and −μy≥0-\mu_y \ge 0, and the reversed rays from xx and yy point upward and miss the ground. The reversed ray from yy in direction −v-v passes through xx and then reaches the top at a point z′z', which is also the exit point of the reversed ray from xx. So T(rs,−μy)=T(y,x) T(x,z′)=T(x,y) T(r,−μ)T(r_s, -\mu_y) = T(y, x)\, T(x, z') = T(x, y)\, T(r, -\mu). □\square

Claim 5 (sun visibility). At the point yy, the sun is blocked by the planet exactly when μs,y<μh(rs)\mu_{s,y} < \mu_h(r_s), and otherwise the light that reaches yy from the sun is the sun irradiance times T(rs,μs,y)T(r_s, \mu_{s,y}). This is line L7.

Proof. The sunlight that reaches yy travels along the ray from yy in direction ℓ\ell, reversed. By Claim 1 that ray has the coordinates (rs,μs,y)(r_s, \mu_{s,y}), and by Claim 2 it hits the ground exactly when μs,y<μh(rs)\mu_{s,y} < \mu_h(r_s). If it misses the ground, it leaves the atmosphere at the top, and the light is attenuated by the transmittance of that segment. □\square

Claim 6 (the single scattering sum). Lines L3 to L9 compute the composite trapezoidal rule with qq intervals for

S=Esun∫0DT(x,ys) V(ys) T(rs,μs,y) (βR(rs)PR(ν)+βM(rs)PM(ν)) ds,S = E_{\text{sun}} \int_0^D T(x, y_s)\, V(y_s)\, T(r_s, \mu_{s, y})\, \big(\beta_R(r_s) P_R(\nu) + \beta_M(r_s) P_M(\nu)\big)\, ds,

where VV is 1 if the sun is visible at ysy_s and 0 otherwise, with the transmittances replaced by the table lookups of Claims 3 and 4. With exact transmittances the sum converges to SS as q→∞q \to \infty, with error O(1/q2)O(1/q^2) when the integrand is twice continuously differentiable on [0,D][0, D].

Proof. Line L4 visits the q+1q + 1 points sk=kD/qs_k = kD/q with weights 1/21/2 at the ends and 1 elsewhere, line L8 adds the weighted integrand per channel (zero when line L7 finds the sun blocked), and line L9 multiplies by D/qD/q; this is the trapezoidal rule. The integrand is bounded, and it is continuous except where VV jumps, which happens at most at finitely many points of the segment. A bounded function with finitely many discontinuities is Riemann integrable, and the trapezoidal sums converge to its integral. When the integrand is C2C^2, the standard error bound of the composite trapezoidal rule is D3max⁡∣f′′∣/(12q2)D^3 \max|f''| / (12 q^2). The single scattering integrand itself is the definition: light from the sun, attenuated to yy, scattered toward −v-v with the probability density of each phase function times its scattering coefficient, and attenuated back to xx. □\square

Claim 7 (the phase functions). 2π∫−11PR(ν) dν=12\pi \int_{-1}^1 P_R(\nu)\, d\nu = 1, and 2π∫−11PM(ν) dν=12\pi \int_{-1}^1 P_M(\nu)\, d\nu = 1 for every g∈(−1,1)g \in (-1, 1).

Proof. For Rayleigh, 2π⋅316π(2+23)=38⋅83=12\pi \cdot \frac{3}{16\pi} (2 + \frac{2}{3}) = \frac{3}{8} \cdot \frac{8}{3} = 1. For Cornette-Shanks, PM=k(1+ν2)(1+g2−2gν)−3/2P_M = k (1 + \nu^2) (1 + g^2 - 2g\nu)^{-3/2} with k=38π1−g22+g2k = \frac{3}{8\pi} \frac{1 - g^2}{2 + g^2}. For g=0g = 0, PM=PRP_M = P_R. For g<0g < 0, the substitution ν→−ν\nu \to -\nu reduces to ∣g∣|g|. For 0<g<10 < g < 1, set a=1+g2a = 1 + g^2, b=2gb = 2g and w=a−bνw = a - b\nu, which runs over [(1−g)2,(1+g)2][(1 - g)^2, (1 + g)^2], so w\sqrt w runs over [1−g,1+g][1 - g, 1 + g]. Then ∫−11(1+ν2)w−3/2dν=1b∫(1+(a−w)2/b2)w−3/2dw\int_{-1}^1 (1 + \nu^2) w^{-3/2} d\nu = \frac{1}{b} \int \big(1 + (a - w)^2 / b^2\big) w^{-3/2} dw, and the three needed integrals are ∫w−3/2dw=4g1−g2\int w^{-3/2} dw = \frac{4g}{1 - g^2}, ∫w−1/2dw=4g\int w^{-1/2} dw = 4g and ∫w1/2dw=4g3(3+g2)\int w^{1/2} dw = \frac{4g}{3}(3 + g^2). Expanding (a−w)2=a2−2aw+w2(a - w)^2 = a^2 - 2aw + w^2,

∫−111+ν2w3/2 dν=21−g2+12g2(a21−g2−2a+1+g23)=21−g2+2(1+2g2)3(1−g2)=4(2+g2)3(1−g2),\int_{-1}^1 \frac{1 + \nu^2}{w^{3/2}}\, d\nu = \frac{2}{1 - g^2} + \frac{1}{2g^2} \Big(\frac{a^2}{1 - g^2} - 2a + 1 + \frac{g^2}{3}\Big) = \frac{2}{1 - g^2} + \frac{2(1 + 2g^2)}{3(1 - g^2)} = \frac{4(2 + g^2)}{3(1 - g^2)},

where the bracket simplifies with a2−(1+53g2)(1−g2)=43g2(1+2g2)a^2 - (1 + \frac{5}{3} g^2)(1 - g^2) = \frac{4}{3} g^2 (1 + 2g^2). Multiplying by 2πk2\pi k gives 1. □\square

What is not proved. The bilinear interpolation of the table adds an error that the claims do not bound; the tests measure it against direct quadrature. The coefficients of the toy atmosphere are data, and the page labels them.

Cost. Line L1 computes t=nrnμt = n_r n_\mu table entries with qq quadrature steps each, Θ(tq)\Theta(t q) work once. One view ray costs Θ(q)\Theta(q) with three table lookups per step, O(1)O(1) each, independent of tt. ■\blacksquare

Complexity

The model is the real RAM, with tt table entries and qq quadrature steps per ray. The transmittance table costs Θ(tq)\Theta(t q) once. One view ray of single scattering costs Θ(q)\Theta(q), with three O(1)O(1) table lookups per step, independent of tt. The table needs Θ(t)\Theta(t) space, three numbers per entry.

For the full method, let tt be the number of entries of the 4D table, mm the number of directions for the scattering density and oo the number of orders. Each order costs Θ(tm)\Theta(t m) for the density and Θ(tq)\Theta(t q) for the integration along rays, so the precomputation costs Θ(ot(m+q))\Theta(o t (m + q)). Rendering costs Θ(1)\Theta(1) per pixel. With a few dozen entries along each of the four axes, the 4D table has a few hundred thousand to a few million entries; the cost is paid again whenever the atmosphere changes, but not when the sun or the camera moves.

Properties

  • Exact symmetry reduction. For a spherically layered atmosphere, two configurations with the same (r,μ,μs,ν)(r, \mu, \mu_s, \nu) differ by a rotation about the center of the planet, which maps the atmosphere to itself, so the four numbers determine the radiance exactly (a proved property). The tables lose information only through their resolution.
  • Linearity. The result is linear in EsunE_{\text{sun}}, and single scattering is linear in the scattering coefficients for a fixed transmittance.
  • No dependence on the camera path. The tables are the same for every viewpoint, from the ground to space; only a change of the atmosphere needs a new precomputation.
  • Only the planet casts shadows. The tables assume that nothing but the planet blocks the sun inside the air, so light shafts behind mountains or clouds need separate methods.

Variants and improvements

  • Fewer tables. Hillaire (2020) replaces the 4D table by a sky view table for the current camera, a small 3D table for aerial perspective in the view frustum and a 2D table for multiple scattering, recomputed each frame, which lets artists change the atmosphere at run time.
  • Better parameterizations. Bruneton's 2017 reimplementation maps the angles with the distance to the boundary, as in line L1, to put more entries near the horizon and to avoid extrapolation at the ends of the table.
  • Ozone. An absorbing layer in the middle atmosphere changes the color of the twilight sky; later implementations add it as one more extinction term.
  • Analytic fits. For a camera on the ground only, the Preetham sky model and its successors fit formulas to simulated skies and need no tables.
  • Path tracing. Volumetric path tracing of the same atmosphere gives reference images, at a cost far from real time.

When to use it

Use precomputed scattering when the camera can be anywhere from the ground to space, the sun moves, and the atmosphere is the same for long periods, as in flight simulators, planet renderers and open world games. Use an analytic sky model when the camera stays on the ground and only the sky dome is needed. Use per frame methods such as Hillaire's when the atmosphere parameters change often. For clouds, fog banks and other local media, use ray marching of participating media, since the tables assume a layered, clear atmosphere.

Pitfalls

  • Units. Kilometers and meters mixed between the radii and the scattering coefficients change every result by orders of magnitude. Line L1 must use the same length unit for both.
  • The horizon. Transmittance changes fastest near the horizon. A table that is linear in μ\mu undersamples it, as the example measured, and gives a dark or bright band at the horizon. Use the distance mapping of line L1.
  • Division in line L6. Near the horizon both table values in line L6 are small and their ratio is unstable; the result can exceed 1. Clamp it to 1, and use the reversed form for rays that hit the ground, since the direct form would read the table for rays that are not in it.
  • Too few steps in line L4. A horizontal ray crosses about 876 km of air in the toy atmosphere, while the Mie layer has a scale height of 1.2 km. A fixed number of steps that works for upward rays misses most of the haze along the horizon.
  • The shadow of the planet. Without the test of line L7, points in the shadow of the planet still scatter sunlight, and the sky stays bright after sunset.
  • Phase in the table. Putting the Mie phase function into the 4D table blurs the bright halo around the sun, because the table has a coarse grid in ν\nu.
  • Display. The output is linear radiance with a large range; it needs tone mapping before display.

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.

precomputed_atmospheric_scattering.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/precomputed-atmospheric-scattering/. The authors are listed in prov/22XP7T.jsonl.

"""A toy of precomputed atmospheric scattering: a transmittance table and single scattering.

This is a toy, not the full method. It precomputes the transmittance table
T(r, mu) of a spherical planet with an exponential Rayleigh and Mie
atmosphere, and uses it to compute the single scattered light along one view
ray by quadrature. The full method also stores single scattering in a 4D
table over (r, mu, mu_s, nu), adds multiple scattering orders and ground
irradiance, and reads the tables in a shader; this file does none of that.

Units: lengths in km, scattering coefficients in 1/km, the sun irradiance is
1 in each of the three channels (red 680 nm, green 550 nm, blue 440 nm), so
the result is radiance per unit sun irradiance, in 1/sr. The Rayleigh values
and scale heights are those of Bruneton and Neyret (2008); the Mie values and
the planet radii are tuning constants of this toy.

Geometry: r is the distance to the planet center, mu the cosine of the view
zenith angle, mu_s that of the sun zenith angle, nu the cosine of the angle
between the view and the sun. A point at distance s along the view ray has
r_s = sqrt(r^2 + s^2 + 2 r mu s), mu_s' = (r mu + s) / r_s and
mu_s_s = (r mu_s + s nu) / r_s.
"""

import math

Vec3 = tuple[float, float, float]

RG = 6360.0                        # ground radius, km (tuning of the toy)
RT = 6420.0                        # top of the atmosphere, km (tuning of the toy)
H_R = 8.0                          # Rayleigh scale height, km
H_M = 1.2                          # Mie scale height, km
BETA_R = (5.8e-3, 13.5e-3, 33.1e-3)  # Rayleigh scattering at sea level, 1/km
BETA_M_SCA = 4.0e-3                # Mie scattering at sea level, 1/km (tuning)
BETA_M_EXT = BETA_M_SCA / 0.9      # Mie extinction, 1/km (tuning: albedo 0.9)
G_MIE = 0.8                        # Mie asymmetry (tuning)


def phase_rayleigh(nu: float) -> float:
    """Rayleigh phase function, normalized over the sphere: 3 / (16 pi) (1 + nu^2)."""
    return 3.0 / (16.0 * math.pi) * (1.0 + nu * nu)


def phase_mie(nu: float, g: float = G_MIE) -> float:
    """Cornette-Shanks phase function, normalized over the sphere."""
    k = 3.0 / (8.0 * math.pi) * (1.0 - g * g) / (2.0 + g * g)
    return k * (1.0 + nu * nu) / (1.0 + g * g - 2.0 * g * nu) ** 1.5


def extinction(r: float) -> Vec3:
    """Extinction coefficient at radius r, per channel, in 1/km."""
    h = max(r - RG, 0.0)
    rm = BETA_M_EXT * math.exp(-h / H_M)
    rr = math.exp(-h / H_R)
    return (BETA_R[0] * rr + rm, BETA_R[1] * rr + rm, BETA_R[2] * rr + rm)


def mu_horizon(r: float) -> float:
    """The cosine of the view zenith angle of the horizon seen from radius r."""
    return -math.sqrt(max(0.0, 1.0 - (RG / r) ** 2))


def hits_ground(r: float, mu: float) -> bool:
    return mu < mu_horizon(r)


def dist_to_top(r: float, mu: float) -> float:
    return max(0.0, -r * mu + math.sqrt(max(0.0, r * r * (mu * mu - 1.0) + RT * RT)))


def dist_to_ground(r: float, mu: float) -> float:
    return max(0.0, -r * mu - math.sqrt(max(0.0, r * r * (mu * mu - 1.0) + RG * RG)))


def point_on_ray(r: float, mu: float, s: float) -> tuple[float, float]:
    """Radius and view zenith cosine at distance s along the ray (r, mu)."""
    rs = math.sqrt(max(r * r + s * s + 2.0 * r * mu * s, RG * RG))
    return rs, max(-1.0, min(1.0, (r * mu + s) / rs))


def optical_depth(r: float, mu: float, d: float, q: int = 200) -> Vec3:
    """Integral of the extinction over the first d km of the ray, trapezoidal rule with q steps."""
    if d <= 0.0:
        return (0.0, 0.0, 0.0)
    ds = d / q
    acc = [0.0, 0.0, 0.0]
    for k in range(q + 1):
        w = 0.5 if k in (0, q) else 1.0
        e = extinction(point_on_ray(r, mu, k * ds)[0])
        for c in range(3):
            acc[c] += w * e[c]
    return (acc[0] * ds, acc[1] * ds, acc[2] * ds)


def transmittance_to_top(r: float, mu: float, q: int = 200) -> Vec3:
    """Direct quadrature of the transmittance from (r, mu) to the top, for a ray that misses the ground."""
    tau = optical_depth(r, mu, dist_to_top(r, mu), q)
    return (math.exp(-tau[0]), math.exp(-tau[1]), math.exp(-tau[2]))


H_TOP = math.sqrt(RT * RT - RG * RG)  # distance from the ground to the top along the horizon


def table_coords(r: float, mu: float) -> tuple[float, float]:
    """The unit coordinates (x_r, x_mu) of a ray (r, mu) that misses the ground.

    x_r = rho / H with rho = sqrt(r^2 - RG^2), and x_mu places the distance d
    to the top between its least value RT - r (straight up) and its largest
    value rho + H (along the horizon). This is the mapping of Bruneton's 2017
    code; it puts more entries near the horizon, where T changes fast.
    """
    rho = math.sqrt(max(0.0, r * r - RG * RG))
    d = dist_to_top(r, mu)
    d_min, d_max = RT - r, rho + H_TOP
    x_mu = (d - d_min) / (d_max - d_min) if d_max > d_min else 0.0
    return rho / H_TOP, min(max(x_mu, 0.0), 1.0)


def ray_of_coords(x_r: float, x_mu: float) -> tuple[float, float]:
    """The inverse of table_coords."""
    rho = H_TOP * x_r
    r = math.sqrt(rho * rho + RG * RG)
    d_min, d_max = RT - r, rho + H_TOP
    d = d_min + x_mu * (d_max - d_min)
    mu = 1.0 if d == 0.0 else (H_TOP * H_TOP - rho * rho - d * d) / (2.0 * r * d)
    return r, max(-1.0, min(1.0, mu))


class TransmittanceTable:
    """T(r, mu) to the top of the atmosphere on a regular grid in (x_r, x_mu)."""

    def __init__(self, nr: int = 32, nu: int = 64, q: int = 200) -> None:
        if nr < 2 or nu < 2:
            raise ValueError("the table needs at least 2 entries per axis")
        self.nr, self.nu = nr, nu
        self.data = []
        for i in range(nr):
            row = []
            for j in range(nu):
                r, mu = ray_of_coords(i / (nr - 1), j / (nu - 1))
                row.append(transmittance_to_top(r, mu, q))  # @line L1
            self.data.append(row)

    def lookup(self, r: float, mu: float) -> Vec3:
        """Bilinear lookup of T(r, mu) for a ray that does not hit the ground."""
        r = min(max(r, RG), RT)
        x_r, x_mu = table_coords(r, mu)
        x = x_r * (self.nr - 1)
        y = x_mu * (self.nu - 1)
        i, j = min(int(x), self.nr - 2), min(int(y), self.nu - 2)
        fx, fy = x - i, y - j
        d = self.data
        return tuple(
            (1 - fx) * ((1 - fy) * d[i][j][c] + fy * d[i][j + 1][c])
            + fx * ((1 - fy) * d[i + 1][j][c] + fy * d[i + 1][j + 1][c])
            for c in range(3))

    def between(self, r: float, mu: float, s: float, ground: bool) -> Vec3:
        """Transmittance from (r, mu) to the point at distance s, from two table lookups."""
        rs, mus = point_on_ray(r, mu, s)
        if ground:
            num, den = self.lookup(rs, -mus), self.lookup(r, -mu)
        else:
            num, den = self.lookup(r, mu), self.lookup(rs, mus)
        return tuple(min(1.0, num[c] / den[c]) for c in range(3))


def single_scattering(table: TransmittanceTable, r: float, mu: float, mu_s: float,
                      nu: float, q: int = 100, g: float = G_MIE) -> Vec3:
    """Single scattered radiance along the view ray (r, mu) for the sun at (mu_s, nu)."""
    ground = hits_ground(r, mu)
    d = dist_to_ground(r, mu) if ground else dist_to_top(r, mu)  # @line L2
    pr, pm = phase_rayleigh(nu), phase_mie(nu, g)
    acc = [0.0, 0.0, 0.0]  # @line L3
    for k in range(q + 1):  # @line L4
        s = k * d / q
        w = 0.5 if k in (0, q) else 1.0
        ry, _ = point_on_ray(r, mu, s)  # @line L5
        mu_sy = max(-1.0, min(1.0, (r * mu_s + s * nu) / ry))
        t_view = table.between(r, mu, s, ground)  # @line L6
        if hits_ground(ry, mu_sy):  # @line L7
            continue
        t_sun = table.lookup(ry, mu_sy)
        h = ry - RG
        br, bm = math.exp(-h / H_R), BETA_M_SCA * math.exp(-h / H_M)
        for c in range(3):
            acc[c] += w * t_view[c] * t_sun[c] * (BETA_R[c] * br * pr + bm * pm)  # @line L8
    ds = d / q
    return (acc[0] * ds, acc[1] * ds, acc[2] * ds)  # @line L9


def single_scattering_direct(r: float, mu: float, mu_s: float, nu: float,
                             q: int = 100, q_inner: int = 200, g: float = G_MIE) -> Vec3:
    """The same integral with every transmittance by direct quadrature, for the tests."""
    ground = hits_ground(r, mu)
    d = dist_to_ground(r, mu) if ground else dist_to_top(r, mu)
    pr, pm = phase_rayleigh(nu), phase_mie(nu, g)
    acc = [0.0, 0.0, 0.0]
    for k in range(q + 1):
        s = k * d / q
        w = 0.5 if k in (0, q) else 1.0
        ry, _ = point_on_ray(r, mu, s)
        mu_sy = max(-1.0, min(1.0, (r * mu_s + s * nu) / ry))
        if hits_ground(ry, mu_sy):
            continue
        tau = optical_depth(r, mu, s, q_inner)
        t_sun = transmittance_to_top(ry, mu_sy, q_inner)
        h = ry - RG
        br, bm = math.exp(-h / H_R), BETA_M_SCA * math.exp(-h / H_M)
        for c in range(3):
            acc[c] += w * math.exp(-tau[c]) * t_sun[c] * (BETA_R[c] * br * pr + bm * pm)
    ds = d / q
    return (acc[0] * ds, acc[1] * ds, acc[2] * ds)
test_precomputed_atmospheric_scattering.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/precomputed-atmospheric-scattering/. The authors are listed in prov/22XP7T.jsonl.

"""Tests of the toy: the transmittance table and single scattering against direct quadrature.

The table coordinates invert, the table matches a direct quadrature of the
optical depth, optical depth adds along a ray, the transmittance between two
points from two table lookups matches the direct value, the phase functions
integrate to 1 over the sphere, and single scattering from the table matches
the same integral with every transmittance computed directly. The color
checks at the end are measurements of the toy, not proved properties.
"""

import math
import random

import pytest

from precomputed_atmospheric_scattering import (
    BETA_R, RG, RT, TransmittanceTable, dist_to_ground, dist_to_top,
    mu_horizon, optical_depth, phase_mie, phase_rayleigh, point_on_ray, ray_of_coords,
    single_scattering, single_scattering_direct, table_coords, transmittance_to_top)

TABLE = TransmittanceTable(32, 64, 200)


def rand_ray(rng: random.Random, ground: bool = False) -> tuple[float, float]:
    r = RG + rng.uniform(0.0, RT - RG)
    mh = mu_horizon(r)
    mu = rng.uniform(-1.0, mh) if ground else rng.uniform(mh, 1.0)
    return r, mu


def test_table_coordinates_invert() -> None:
    rng = random.Random(1)
    for _ in range(500):
        x, y = rng.random(), rng.random()
        r, mu = ray_of_coords(x, y)
        assert RG - 1e-9 <= r <= RT + 1e-9 and mu >= mu_horizon(r) - 1e-9
        x2, y2 = table_coords(r, mu)
        assert abs(x - x2) < 1e-9 and abs(y - y2) < 1e-9
    # The corners: the ground looking up, the ground along the horizon, the top looking up.
    assert table_coords(RG, 1.0) == (0.0, 0.0)
    assert abs(table_coords(RG, 0.0)[1] - 1.0) < 1e-12
    assert abs(table_coords(RT, 1.0)[0] - 1.0) < 1e-12


def test_table_matches_direct_quadrature() -> None:
    rng = random.Random(2)
    for _ in range(300):
        r, mu = rand_ray(rng)
        a, b = TABLE.lookup(r, mu), transmittance_to_top(r, mu)
        assert all(abs(x - y) < 3e-3 for x, y in zip(a, b))
        assert all(0.0 < y <= 1.0 for y in b)


def test_transmittance_basics() -> None:
    assert transmittance_to_top(RT, 1.0) == (1.0, 1.0, 1.0)
    zen, hor = transmittance_to_top(RG, 1.0), transmittance_to_top(RG, 0.0)
    for c in range(3):
        assert hor[c] < zen[c] < 1.0
    # Blue light is scattered out more than red light.
    assert zen[2] < zen[1] < zen[0] and hor[2] < hor[1] < hor[0]


def test_optical_depth_adds_along_the_ray() -> None:
    rng = random.Random(3)
    for _ in range(20):
        r, mu = rand_ray(rng)
        d = dist_to_top(r, mu)
        s1 = rng.uniform(0.0, d)
        r1, mu1 = point_on_ray(r, mu, s1)
        whole = optical_depth(r, mu, d, 4000)
        parts = [a + b for a, b in zip(optical_depth(r, mu, s1, 4000), optical_depth(r1, mu1, d - s1, 4000))]
        assert all(abs(x - y) < 1e-5 * x for x, y in zip(whole, parts))


def test_transmittance_between_two_points() -> None:
    rng = random.Random(4)
    for ground in (False, True):
        for _ in range(100):
            r, mu = rand_ray(rng, ground)
            d = dist_to_ground(r, mu) if ground else dist_to_top(r, mu)
            s = rng.uniform(0.0, d)
            tau = optical_depth(r, mu, s, 400)
            want = [math.exp(-t) for t in tau]
            got = TABLE.between(r, mu, s, ground)
            assert all(abs(x - y) < 1e-2 for x, y in zip(got, want))


def test_phase_functions_are_normalized() -> None:
    def sphere_integral(f, m=20000):
        h = 2.0 / m
        acc = f(-1.0) + f(1.0)
        for k in range(1, m):
            acc += (4 if k % 2 else 2) * f(-1.0 + k * h)
        return 2.0 * math.pi * acc * h / 3.0

    assert abs(sphere_integral(phase_rayleigh) - 1.0) < 1e-9
    for g in (0.0, 0.5, 0.8):
        assert abs(sphere_integral(lambda nu: phase_mie(nu, g)) - 1.0) < 1e-6
    # With g = 0 the Cornette-Shanks function is the Rayleigh function.
    assert abs(phase_mie(0.3, 0.0) - phase_rayleigh(0.3)) < 1e-15
    assert phase_mie(1.0) > 50 * phase_mie(-1.0)


def test_single_scattering_matches_direct_transmittance() -> None:
    rays = [(RG + 0.001, 1.0, 1.0, 1.0), (RG + 0.001, 1.0, 0.5, 0.5),
            (RG + 0.001, 0.2, 0.05, 0.9), (RG + 10.0, -0.5, 0.7, 0.0),
            (RG + 30.0, 0.4, 0.3, -0.6)]
    for r, mu, mu_s, nu in rays:
        a = single_scattering(TABLE, r, mu, mu_s, nu)
        b = single_scattering_direct(r, mu, mu_s, nu)
        assert all(abs(x - y) < 1e-2 * y for x, y in zip(a, b))


def test_no_light_when_the_sun_is_far_below_the_horizon() -> None:
    assert single_scattering(TABLE, RG, 1.0, -0.5, -0.5) == (0.0, 0.0, 0.0)


def test_colors_of_the_toy_sky() -> None:
    # Measurements of the toy. Rayleigh data follow lambda^-4 within 1 percent.
    assert abs(BETA_R[2] / BETA_R[0] / (680.0 / 440.0) ** 4 - 1.0) < 1e-2
    # The zenith with the sun at 60 degrees from it is blue.
    s = single_scattering(TABLE, RG, 1.0, 0.5, 0.5)
    assert s[2] > s[1] > s[0] > 0.0
    # Looking near the sun as it sets, red and green win over blue.
    s = single_scattering(TABLE, RG, 0.2, 0.05, 0.9)
    assert s[0] > s[2] and s[1] > s[2]


def test_bad_table() -> None:
    with pytest.raises(ValueError):
        TransmittanceTable(1, 8)

History

Nishita, Sirai, Tadamura and Nakamae (1993) computed single scattering of sunlight in a spherical atmosphere with exponential density, to display the Earth from space. Preetham, Shirley and Smits (1999) fitted an analytic model to simulated skies seen from the ground. Bruneton and Neyret (2008) reduced the radiance of a layered atmosphere to four parameters, precomputed single and multiple scattering into tables, and rendered sky and aerial perspective from any altitude on the GPU. Bruneton published a documented reimplementation in 2017. Hillaire (2020) moved most of the work back to each frame with smaller tables, so that the atmosphere can change while the program runs.

References

  1. Eric Bruneton and Fabrice Neyret, Precomputed atmospheric scattering, Computer Graphics Forum 27(4), 2008, 1079 to 1086 (Eurographics Symposium on Rendering), the atmosphere model (Rayleigh and Mie scattering coefficients, scale heights, phase functions), the parameterization of the 2D and 4D tables, and the precomputation of multiple scattering orders
  2. Eric Bruneton, Precomputed Atmospheric Scattering, a new implementation (2017), documented source code, the file atmosphere/functions.glsl, with the transmittance computation, the mapping from (r, mu) to texture coordinates, the phase functions and the transmittance between two points from two lookups
  3. Tomoyuki Nishita, Takao Sirai, Katsumi Tadamura and Eihachiro Nakamae, Display of the earth taking into account atmospheric scattering, SIGGRAPH 93, 175 to 182, the single scattering model of sunlight in a spherical atmosphere with exponential density (general locator)
  4. Sébastien Hillaire, A Scalable and Production Ready Sky and Atmosphere Rendering Technique, Computer Graphics Forum 39(4), 2020, 13 to 22, the smaller lookup tables and the approximation of multiple scattering that replace the 4D table (general locator)

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.single_scattering_ray
  • a full proof of time.transmittance_table
  • a full proof of space.table
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