Algorithmresearch
Moment shadow mapping
Also called moment shadow maps.
Store four power moments of depth and compute the sharp lower bound on the occluded fraction, an upper bound on the lit fraction with less light leaking than variance shadow maps.
- Solves
- Shadow determination
- Time
- Θ(w h + q) worst
- Space
- Θ(w h) extra
- Where
- h = the map height in texels; q = the number of shadow lookups; w = the map width in texels
- Model
- Real RAM
- Properties
- not adaptivenot comparison baseddeterministicnot in placeofflineiterativenot stable
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Christoph Peters, Reinhard Klein, 2015
Moment shadow mapping stores the first four powers of the depth, , at each texel and filters them like variance shadow maps filter their two moments. The lookup solves a small linear system and a quadratic to get the sharp lower bound on the occluded fraction for these four moments, so is an upper bound on the lit fraction. With four moments the bound is never weaker than the two-moment Chebyshev bound of variance shadow maps, and in scenes with several occluders it is much tighter, so the light leaking is smaller. It costs twice the storage and more arithmetic per lookup.
In plain words
Variance shadow maps keep two summary numbers for the distances near each dot of the shadow map: the average and the spread. From them they estimate how much of the area is behind a point. When objects at very different distances overlap, the estimate is far too bright.
This method keeps two more numbers, from the cube and the fourth power of the distance. With four numbers it can tell more about the mix of distances. The lookup finds the mix of at most three distances that agrees with the four numbers and makes the point as bright as possible, and uses that brightness. The answer is never darker than the truth, and it is never brighter than the answer from two numbers.
The problem
The input is a map of depths in the Direct3D range , smaller nearer, a filter, and lookups with a receiver depth . The filter defines a distribution of the depths under it, as on the variance shadow maps page. The map stores the filtered power moments with the filtered mean of . The lit fraction is the probability that a depth is at least , the receiver depth after the bias. The output is the smallest value that is an upper bound on the lit fraction for every distribution with the moments , together with tunings that make the computation stable.
The algorithm
MSM-LOOKUP(b, z, α, β) ▷ b = (b1, b2, b3, b4), receiver depth z- 1
b' ← (1 - α) b + α (1/2, 1/2, 1/2, 1/2) ▷ the moment bias - 2
z_f ← z - β ▷ the depth bias - 3
solve B c = (1, z_f, z_f^2) for B = [[1, b'1, b'2], [b'1, b'2, b'3], [b'2, b'3, b'4]] by Cholesky - 4
z2 < z3 ← the two roots of c3 x^2 + c2 x + c1 - 5
if z_f ≤ z2 then G ← 0 - 6
else if z_f ≤ z3 then G ← (z_f z3 - b'1 (z_f + z3) + b'2) / ((z3 - z2)(z_f - z2)) - 7
else G ← 1 - (z2 z3 - b'1 (z2 + z3) + b'2) / ((z_f - z2)(z_f - z3)) - 8
return 1 - clamp(G, 0, 1) ▷ the lit estimate
Line L3 uses the Cholesky decomposition of the Hankel matrix of the moments. Its two pivots are , the variance, and ; both are positive when the filter holds at least three distinct depths. The roots , and are the support of the canonical distribution: the distribution on three points with the moments that has a point at . The value is its weight below . Lines L6 and L7 are that weight in closed form, so the lookup needs no explicit solve for the weights.
The bias of line L1 mixes in a small amount of the distribution with half its mass at 0 and half at 1, whose moments are all . It keeps positive definite for maps with one or two distinct depths, such as a plane over a plane, and it hides the rounding of moments stored with few bits. Peters and Klein use ; this value is a tuning.
Example
A filter holds three depths 0.2, 0.4 and 0.6 with equal weights. Then , with the mean 0.4 and the variance . There is no bias.
| receiver | VSM bound | MSM | true lit fraction | support points |
|---|---|---|---|---|
| 0.8 | 0.01754 | 0 | 0.8, 0.22380, 0.53620 | |
| 0.5 | 0.57961 | 0.5, 0.21729, 0.66271 | ||
| 0.3 | 1 | 0.88416 | 0.3 and two more |
At all three depths are in front of the receiver. The variance bound shows 14 percent of the light, and the moment bound 1.75 percent. At the receiver is in front of the mean, so the variance bound gives no information, but the moment bound still says that at least 11.6 percent is occluded.
Two depths. A filter with the depths 0.2 and 0.6 has a singular Hankel matrix, and line L3 cannot be solved. With , the lookup at returns 0.000122, where the true value is 0 and the variance bound is .
Correctness
The proof file gives the full argument, and the tests check each claim against the true lit fraction of random distributions and against a direct solve of the canonical weights.
- The kernel polynomial. The solution of line L3 defines with for every quadratic . From this, , and has two real roots that differ from , by a sum of squares argument.
- The canonical distribution. The three points carry positive weights that sum to 1 and reproduce all four moments.
- The bound. For each of the three cases of lines L5 to L7 there is a polynomial of degree 4 that lies above the step function of the lit set and meets it at the three points. Integrating it against any distribution with the moments gives lit fraction , and the canonical distribution reaches it. So is the sharp lower bound on the occluded fraction, and is the sharp upper bound on the lit fraction, over all distributions on the real line.
- Better than two moments. The set of distributions with four given moments is a subset of the set with two of them, so is at most the variance bound.
- The bias. With the bias of line L1, the result is at least the true lit fraction minus .
The depths lie in , but the support points can lie outside it. The bound is then still valid, but a distribution on may not reach it.
Proof: The Hamburger 4MSM lookup returns the sharp lower bound on the occluded fraction given four power moments, so 1 - G is an upper bound on the lit fraction and is never above the VSM boundfull
We use the notation of the page. A filter defines a probability distribution of depths on the real line. Its power moments are for , with . The lit fraction for the depth is and the occluded fraction is , as in variance shadow maps. Define the linear functional on polynomials of degree at most 4. Then for every distribution with these moments. The Hankel matrix is , and for the polynomial .
The standing hypothesis is that is positive definite: for every nonzero polynomial of degree at most 2. This holds when has at least three support points. The factorization in solve_hankel checks it: the pivots and of are positive exactly when is positive definite. We also assume that in line L4; the code stops otherwise. The arithmetic is exact real arithmetic.
The kernel polynomial
Line L3 solves , and we write .
Lemma 1. for every polynomial of degree at most 2.
Proof. Row of is , and it equals , for . Both sides are linear in .
Lemma 2. , and has two real roots , both different from . These are the roots of line L4.
Proof. , because . By Lemma 1 with , . Suppose that does not change sign. Since , then on the real line, so is a nonnegative polynomial of degree at most 4. It is not the zero polynomial. A nonnegative polynomial in one variable is a sum of squares of polynomials of half its degree, so by the hypothesis on . But Lemma 1 with gives . So changes sign. As , is a quadratic with two distinct real roots, and shows that is neither of them.
The canonical representation
Let , , , and let be the Lagrange polynomials of degree 2 on these three nodes, with if and 0 otherwise.
Lemma 3. The weights are positive, sum to 1, and the measure has the moments . So for every of degree at most 4.
Proof. Let , a cubic whose roots are the three nodes. Divide a polynomial of degree at most 4 by : with and . Then by Lemma 1, because has degree at most 2 and is zero at . So . Since , we get , because . With , the weights sum to . With , of degree 4, by the hypothesis on .
The two weights that the code uses are, from ,
The first is line L6. Line L7 returns .
The bound
Let be the value of lines L5 to L7: if , if , and if . In each case , the weight of the nodes less than . (By Lemma 2, is not a node of , so the tests and of the code are strict.)
Theorem 4. Every distribution on the real line with the moments has , and attains it. So is the sharp lower bound on the occluded fraction, and is the sharp upper bound on the lit fraction.
Proof. We give in each case a polynomial of degree at most 4 with on the real line and at the three nodes. Then by Lemma 3.
Case . Take . Here .
Case . Take with . Then , and . For the factor is positive and increasing, so is increasing there and on .
Case . We want and . Take and choose and so that and . At we have , so is the condition that the logarithmic derivative of is zero there:
This fixes . Then gives . For , the factors , and are all nonnegative, so . For we need . The roots of are , with double, so by Rolle's theorem has a root in , a root in and the root . These are its three roots. Since and , is the only root of below . The leading coefficient is positive, so decreases on and increases on . So on .
The measure has the moments by Lemma 3 and , so no larger lower bound holds for all .
This is the Markov-Krein type result that Peters and Klein use (Krein and Nudel'man, Theorem IV.3.1). The bound is sharp over distributions on the whole real line (the Hamburger problem). The depths of a map lie in , and the nodes can lie outside it; then the bound is still valid, but a distribution on may not attain it.
Corollary 5. is never larger than the VSM value of the same distribution.
Proof. If , the VSM value is 1. Otherwise, the set of distributions with the moments is a subset of the set with the moments . The largest lit fraction over the smaller set is (Theorem 4), and over the larger set it is (Cantelli's inequality, which is sharp).
The moment bias
Proposition 6. Line L1 with and replaces by the mixture . For the result satisfies . If and has a depth outside , the biased Hankel matrix is positive definite.
Proof. The point masses at 0 and 1 have equal to 0 and 1 for , so their moments are all , and the moments of are . With , . By Theorem 4 applied to , , because . For the last claim, , and . If this is 0, then is zero at 0, at 1 and at a depth of outside , so and .
So the bias trades an upper bound for an estimate that is at most below the true lit fraction, and it makes maps with one or two distinct depths usable, as a plane under a plane is. Peters and Klein use for their quantized formats; this value is a tuning, not a derived constant. The clamp of line L8 does nothing in exact arithmetic, because ; it guards against rounding.
Complexity
The map pass computes four moments per texel, and any linear filter acts on them as on the two moments of variance shadow maps, in for a summed-area table or a fixed-size blur. A lookup is : a Cholesky solve, a quadratic and a few divisions, so lookups cost in the worst case. The map takes four values per texel. Peters and Klein store them in 64 bits per texel with a quantization transform, or in 128 bits as floats.
Properties
- Sharp for four moments. No lookup that sees only to can give a lower upper bound on the lit fraction (a proved property).
- At most the variance bound. The leak is never larger than that of variance shadow maps for the same filter (a proved property).
- Filterable. The moments are linear in the weights, so blurs, mipmaps and summed-area tables apply before the lookup.
- Still leaks. The bound is an upper bound, not the lit fraction. In the example it shows 58 percent of the light where the truth is 33 percent.
- Sensitive to precision. Without the bias of line L1, moments of one or two distinct depths, or moments rounded to 16 bits, make line L3 singular or unstable.
Variants and improvements
- Optimized quantization. Peters and Klein store an affine transform of the moments in place of the raw powers, so that 16 bits per moment are enough with a small .
- Hausdorff moments. A variant uses the moment problem on a bounded interval, which knows that the depths lie in ; it needs more work per lookup.
- Soft shadows. The filtered moments also give an estimate of the average blocker depth, so the blocker search of percentage-closer soft shadows can run on a summed-area table of moments.
- Fewer moments. Variance shadow maps keep two moments and the Chebyshev bound; exponential maps keep one moment of a warped depth.
When to use it
Use moment shadow maps where filtered shadows are needed, as for variance shadow maps, and the light leaking of two moments is visible: scenes with several layers of occluders, such as foliage or buildings, or a large filter on a distant cascade. If the filter is small, PCF is cheaper and exact for its taps. If memory bandwidth is tight, the four moments cost twice as much as two.
Pitfalls
- No moment bias. With in line L1, a texel that holds one plane, or a plane over a plane, gives a singular , and line L3 divides by zero.
- Unsorted roots. If line L4 does not order the roots so that , lines L5 and L6 test the wrong case and return a weight of the wrong node.
- No depth bias. With in line L2, a lit receiver can lie a rounding error behind its own depth in the map, and the bound then darkens it a little; peaks of this kind show as acne.
- Raw powers in 16 bits. Storing and in 16 bits destroys the information that the lookup needs; use 32-bit floats or the quantization transform.
- No clamp. In floating point, from lines L6 and L7 can fall slightly outside ; line L8 must clamp it.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/moment-shadow-mapping/. The authors are listed in prov/ZPXE0M.jsonl.
"""Moment shadow mapping with four power moments (Peters and Klein 2015).
This is the Hamburger 4MSM lookup of the paper. Depth is in [0, 1] (the
Direct3D clip range), smaller is nearer to the light. A filtered texel holds
b = (b1, b2, b3, b4), the means of z, z^2, z^3 and z^4 over the depths z under
the filter. The lookup computes G, the sharp lower bound on the occluded
fraction (the weight of the depths z < zf), and returns 1 - G, which is an
upper bound on the lit fraction (the weight of the depths z >= zf).
"""
from math import sqrt
def power_moments(depths, weights=None):
"""The filtered moments (b1, b2, b3, b4) of a list of depths."""
if weights is None:
weights = [1] * len(depths)
total = sum(weights)
return tuple(sum(w * z ** k for z, w in zip(depths, weights)) / total for k in range(1, 5))
def solve_hankel(b, zf):
"""Solve B c = (1, zf, zf^2) for B = [[1, b1, b2], [b1, b2, b3], [b2, b3, b4]]
by the Cholesky factorization B = L D L^T, as in the paper's shader."""
b1, b2, b3, b4 = b
d1 = b2 - b1 * b1
if d1 <= 0:
raise ValueError("the moments are not in the interior of the moment space")
l32 = (b3 - b1 * b2) / d1
d2 = (b4 - b2 * b2) - l32 * l32 * d1
if d2 <= 0:
raise ValueError("the moments are not in the interior of the moment space")
# Forward substitution with the unit lower triangle L = [[1,0,0],[b1,1,0],[b2,l32,1]].
y1 = 1
y2 = zf - b1 * y1
y3 = zf * zf - b2 * y1 - l32 * y2
# Divide by D and back substitution with L^T.
c3 = y3 / d2
c2 = y2 / d1 - l32 * c3
c1 = y1 - b1 * c2 - b2 * c3
return c1, c2, c3
def shadow_intensity(b, zf):
"""G of the paper: the sharp lower bound on the occluded fraction."""
c1, c2, c3 = solve_hankel(b, zf) # @line L3
if c3 == 0:
raise ZeroDivisionError("c3 = 0: no canonical representation for this depth")
p, q = c2 / c3, c1 / c3 # @line L4
disc = sqrt(max(p * p / 4 - q, 0.0))
z2, z3 = -p / 2 - disc, -p / 2 + disc
b1, b2 = b[0], b[1]
if zf <= z2: # @line L5
return 0.0
if zf <= z3: # @line L6
return (zf * z3 - b1 * (zf + z3) + b2) / ((z3 - z2) * (zf - z2))
return 1 - (z2 * z3 - b1 * (z2 + z3) + b2) / ((zf - z2) * (zf - z3)) # @line L7
def msm_lookup(b, z, alpha=0.0, beta=0.0):
"""The lit estimate 1 - G for the receiver depth z.
alpha is the moment bias (the paper uses 3e-5 for its quantized formats),
beta the depth bias. Both are tuning.
"""
bb = tuple((1 - alpha) * x + alpha * 0.5 for x in b) # @line L1
zf = z - beta # @line L2
g = shadow_intensity(bb, zf)
return 1 - min(max(g, 0.0), 1.0) # @line L8
def canonical_nodes(b, zf):
"""The support {zf, z2, z3} of the canonical representation."""
c1, c2, c3 = solve_hankel(b, zf)
p, q = c2 / c3, c1 / c3
disc = sqrt(max(p * p / 4 - q, 0.0))
return zf, -p / 2 - disc, -p / 2 + disc
test_moment_shadow_mapping.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/moment-shadow-mapping/. The authors are listed in prov/ZPXE0M.jsonl.
import random
from moment_shadow_mapping import canonical_nodes, msm_lookup, power_moments, shadow_intensity
TOL = 1e-7
def solve3(a, r):
"""Gaussian elimination with partial pivoting on a 3 x 3 system."""
m = [row[:] + [v] for row, v in zip(a, r)]
for c in range(3):
p = max(range(c, 3), key=lambda k: abs(m[k][c]))
m[c], m[p] = m[p], m[c]
for k in range(c + 1, 3):
f = m[k][c] / m[c][c]
for j in range(c, 4):
m[k][j] -= f * m[c][j]
x = [0.0] * 3
for c in (2, 1, 0):
x[c] = (m[c][3] - sum(m[c][j] * x[j] for j in range(c + 1, 3))) / m[c][c]
return x
def random_distribution(rng):
"""3 to 7 distinct depths in [0, 1], at least 0.05 apart, with weights."""
while True:
k = rng.randrange(3, 8)
zs = sorted(rng.uniform(0.0, 1.0) for _ in range(k))
if all(b - a >= 0.05 for a, b in zip(zs, zs[1:])):
ws = [rng.randrange(1, 10) for _ in range(k)]
return zs, ws
def occluded(zs, ws, zf):
return sum(w for z, w in zip(zs, ws) if z < zf) / sum(ws)
def vsm_bound(b, t):
m1, m2 = b[0], b[1]
if t <= m1:
return 1.0
v = m2 - m1 * m1
return v / (v + (t - m1) ** 2)
def test_lower_bound_on_the_occluded_fraction():
rng = random.Random(1)
for _ in range(400):
zs, ws = random_distribution(rng)
b = power_moments(zs, ws)
for _ in range(5):
zf = rng.uniform(0.0, 1.0)
g = shadow_intensity(b, zf)
assert g <= occluded(zs, ws, zf) + TOL
assert 1 - min(max(g, 0.0), 1.0) >= 1 - occluded(zs, ws, zf) - TOL
def test_sharp_the_canonical_measure_attains_the_bound():
rng = random.Random(2)
for _ in range(300):
zs, ws = random_distribution(rng)
b = power_moments(zs, ws)
zf = rng.uniform(0.0, 1.0)
nodes = canonical_nodes(b, zf)
assert abs(nodes[1] - nodes[2]) > 1e-9
assert min(abs(nodes[0] - nodes[1]), abs(nodes[0] - nodes[2])) > 1e-9
# Weights from the 3 x 3 Vandermonde system on moments 0, 1, 2.
vand = [[x ** k for x in nodes] for k in range(3)]
w = solve3(vand, [1.0, b[0], b[1]])
assert min(w) > -TOL
# The same weights reproduce moments 3 and 4 as well.
assert abs(sum(wi * x ** 3 for wi, x in zip(w, nodes)) - b[2]) < 1e-6
assert abs(sum(wi * x ** 4 for wi, x in zip(w, nodes)) - b[3]) < 1e-6
g = sum(wi for wi, x in zip(w, nodes) if x < zf)
assert abs(g - shadow_intensity(b, zf)) < 1e-6
def test_four_moments_are_at_least_as_tight_as_two():
rng = random.Random(3)
for _ in range(400):
zs, ws = random_distribution(rng)
b = power_moments(zs, ws)
t = rng.uniform(0.0, 1.0)
assert msm_lookup(b, t) <= vsm_bound(b, t) + TOL
def test_moment_bias_costs_at_most_half_alpha():
rng = random.Random(4)
for _ in range(300):
zs, ws = random_distribution(rng)
b = power_moments(zs, ws)
alpha = rng.choice([3e-5, 1e-3, 0.05])
zf = rng.uniform(0.01, 1.0)
lit = 1 - occluded(zs, ws, zf)
assert msm_lookup(b, zf, alpha=alpha) >= lit - alpha / 2 - TOL
def test_bias_makes_two_point_maps_usable():
# Two depths give a singular Hankel matrix; the moment bias fixes it.
b = power_moments([0.1, 0.9], [1, 1])
got = msm_lookup(b, 1.0, alpha=3e-5)
assert 0.0 <= got <= 1.0
try:
shadow_intensity(b, 1.0)
except ValueError:
pass
else:
raise AssertionError("an unbiased two-point map must be rejected")
def test_receiver_in_front_is_lit():
rng = random.Random(5)
for _ in range(200):
zs, ws = random_distribution(rng)
b = power_moments(zs, ws)
zf = rng.uniform(-0.5, zs[0])
assert abs(msm_lookup(b, zf) - 1.0) < TOL
History
The bound that moment shadow mapping uses is a classical result on the moment problem, treated in the book of Krein and Nudel'man (1977) on the Markov moment problem. Peters and Klein brought it to shadows at I3D 2015, as the next step after the two moments of variance shadow maps. They gave a closed form for four moments that fits in a pixel shader, the moment bias, and a quantization of the moments for 64 bits per texel. Later work by Peters and others used the same bounds for transparency and for other filterable signals.
References
- Christoph Peters and Reinhard Klein, Moment shadow mapping, Proceedings of the 19th Symposium on Interactive 3D Graphics and Games (I3D 2015), 7 to 14, the Hamburger 4MSM lookup (the Cholesky solve, the quadratic and the three cases), the moment bias with alpha = 3e-5 in the supplementary Algorithm 3, and the comparison with variance shadow maps
- M. G. Krein and A. A. Nudel'man, The Markov Moment Problem and Extremal Problems, Translations of Mathematical Monographs 50, American Mathematical Society, 1977, Theorem IV.3.1 (the sharp bound from the canonical representation, as cited by Peters and Klein)
- Tomas Akenine-Möller, Eric Haines, Naty Hoffman, Angelo Pesce, Michał Iwanicki and Sébastien Hillaire, Real-Time Rendering, fourth edition, CRC Press, 2018, Chapter 7, the part on filtered shadow maps (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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag ZPXE0M Edit this page History Report an error Markdown