Algorithmadvanced
Tiled shading
Also called tiled light culling, Forward+.
Cut the screen into tiles, keep for each tile the lights whose volume can reach its frustum between the nearest and farthest depth, and shade each pixel with the lights of its tile only.
- Time
- O(p l) worstO(p + t l) cullingO(p k) shading
- Space
- O(t l) lists
- Where
- k = the average number of lights kept per pixel; l = the number of lights; p = the number of pixels; t = the number of tiles
- Model
- Real RAM
- Properties
- deterministicnot in placeofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ola Olsson, Ulf Assarsson, Takahiro Harada, Jay McKee, Jason C. Yang, 2011
Tiled shading is a light culling method for scenes with many local lights. It cuts the screen into square tiles, often 16 by 16 pixels. For each tile it finds the nearest and the farthest depth of its pixels, builds the frustum that these bounds cut out of the view, and keeps the lights whose sphere of influence is not outside it. Each pixel then shades only the lights in the list of its tile. With deferred shading, the culling and the shading run in one compute pass over the G-buffer, and each pixel reads its G-buffer record once. In tiled forward shading, a depth pre-pass gives the tile depths and the forward pass reads the lists. Olsson and Assarsson described both forms in 2011. Clustered shading is the successor that also cuts the depth range into slices.
In plain words
A scene has hundreds of small lights, but each one lights only a small part of the screen. Testing every light at every pixel wastes almost all the work. So the screen is cut into small squares. For each square, the method looks at how near and how far the visible surfaces are, and asks of each light: can its light reach anything in this box? If the answer is no, the light is left out of the list of that square. Then every pixel goes only through the short list of its square. The test is careful in one direction: it can keep a light that does not reach any pixel, but it never leaves out a light that does.
The problem
The input is a depth buffer of pixels with the view depth of the visible surface (or none for the background), the surface attributes of each pixel, and point lights. Light has a center , a radius and an intensity. It reaches a point only if , and its contribution is exactly 0 elsewhere. The output is the shaded image: for each pixel, the sum of the contributions of all lights. The brute-force method costs light evaluations. The goal is a list of lights per tile that contains every light that reaches a pixel of the tile and as few other lights as possible.
The camera looks along , and the page stores the linear view depth . The pixel has its center at , with counted from the bottom. With the aspect ratio and the vertical field of view , a screen position in pixels has the slope , and ; the pixel at depth is at . The radius of a light is part of the light model. Real lights fall off without end, so the radius cuts them, and that cut is tuning.
The algorithm
is the number of tiles. Lines L1 to L6 build the lists and lines L7 to L10 shade. SPHERE-IN-TILE is the conservative test of a sphere against the four side planes of the tile, which pass through the eye, and against the depth range.
TILED-SHADING(D, G, lights, T)- 1
for each tile τ of T × T pixels ▷ one thread group per tile - 2
(dmin, dmax) ← the smallest and largest D over the pixels of τ - 3
F ← the inward unit normals of the four side planes of τ - 4
list[τ] ← empty - 5
for each light j ▷ the threads of the group share this loop - 6
if SPHERE-IN-TILE(F, dmin, dmax, cj, rj) then append j to list[τ] - 7
for each pixel q with geometry, in tile τ - 8
P ← the view position of q; c ← 0 - 9
for each j in list[τ]: c ← c + SHADE(G[q], P, light j) - 10
out[q] ← c SPHERE-IN-TILE(F, dmin, dmax, c, r)- 11
for each m in F: if m · c < -r then return false - 12
if -cz + r < dmin or -cz - r > dmax then return false - 13
return true
The planes (line L3). The tile covers the pixel rectangle . Its left plane holds the points with , which is , so its normal is after normalizing. The right plane has , and the two planes in are the same with . The planes depend only on the tile, so they can be computed once per frame.
The depth range (line L2). On a GPU, the threads of a tile read one pixel each and reduce the depth with atomic min and max in shared memory. Background pixels do not take part. A tile with no geometry gets an empty list.
The light loop (lines L5 and L6). The threads of the group take the lights in steps of the group size and append the kept ones to a list in shared memory with an atomic add on its length. The order in the list then depends on the timing of the threads. The code of this page keeps the index order, which makes the floating-point sum equal to the brute-force sum.
The test (lines L11 to L13). A sphere that is fully outside one plane, or fully nearer than or farther than , cannot reach a point in the tile. The test does not catch every miss. A sphere near the corner of two planes can be outside the frustum but not outside either plane.
Example
The test by hand. The screen is 32 by 32 pixels with and 16-pixel tiles. The tile in the lower left covers . Its four normals are , , and . Say its pixels have the depth range .
| light | center | the test | result | |
|---|---|---|---|---|
| A | 1 | right plane , the other planes positive, meets | kept | |
| B | 1 | right plane | culled | |
| C | 2 | culled | ||
| D | 0.5 | all planes pass, | kept |
If the tile shows a box face at depth 3 and a wall at depth 12 and nothing between, light D reaches no pixel but stays in the list. This is a false positive caused by the depth gap.
A measured scene. The tests render a room of 32 by 32 pixels: a floor, two side walls, a back wall at depth 12 with an open window, and a box face at depth 3. 994 pixels have geometry, and there are 60 random lights with radii between 0.3 and 0.8. Brute force evaluates (pixel, light) pairs. Tiled shading with 8-pixel tiles evaluates 5246 pairs, and only 63 pairs have a nonzero contribution. Clustered shading on the same scene evaluates 2374 pairs. The image is the same in all three cases, value for value. These counts are a measurement on one scene.
Correctness
The proofs are in the proofs folder. The pixel center of a tile lies on the inner side of all four planes at every depth, because the slope is an increasing function of the screen position. If a light reaches a pixel, then , and for each unit normal the Cauchy-Schwarz inequality gives . The depth of the pixel is in and differs from by less than . So no line of the test rejects the light: culling never drops a light that reaches a pixel. Since a dropped light contributes exactly 0, the tiled image equals the brute-force image, and with the lights visited in index order the two floating-point sums are equal too. The tests check both claims at every pixel, with the exact distance test as the reference.
Proof: Tiled light culling never drops a light that reaches a pixelfull
Setting. The camera is at the origin and looks along . The screen has pixels, the aspect ratio is and is the tangent of half the vertical field of view. A screen point in pixels has the slopes and , and the pixel with view depth has the position . A light has a center and a radius , and it reaches if . SHADE returns exactly 0 when . A tile covers the pixel rectangle , and and are the smallest and largest depths of its pixels with geometry. Lines L11 to L13 keep a light unless for one of the four unit plane normals , or , or . The claims are in exact arithmetic. The code adds a slack of to the radius, which only keeps more lights.
Lemma 1 (pixels lie in their tile frustum). Let , , , , and let the four planes have the normals , , and , each divided by its length. Then for each of these normals and for every pixel of the tile at any depth .
Proof. is an increasing linear function of , and , so with . For the first normal, . For the second, . The two planes in are the same with . Dividing by a positive length keeps the signs.
Theorem 1 (no miss). If a light reaches the position of a pixel of a tile, then the light is in the list of that tile.
Proof. Let . For each unit normal of the tile, Lemma 1 and the Cauchy-Schwarz inequality give
so no plane rejects the light. For the depth test, the depth of the pixel is with , and . So and , and the depth test does not reject it either. Line L13 then keeps the light.
Theorem 2 (the image is the brute-force image). Suppose that each tile list holds every light that reaches a pixel of the tile, and that its lights are visited in increasing index order. Then the tiled image equals the image of shading every pixel with every light in index order, value for value, also in floating point.
Proof. For a pixel, let be the list of its tile. By the assumption, every light not in does not reach the pixel, so SHADE returns exactly 0 for it. The brute-force sum visits the lights in index order and adds for each light not in ; in IEEE 754 arithmetic for every that is not , and the partial sums start at and stay . So the brute-force sum performs the same nonzero additions in the same order as the tiled sum, and the two results are equal.
Theorem 1 gives the assumption of Theorem 2 in exact arithmetic. In floating point, a rounded plane test could drop a light whose sphere touches the frustum within the rounding error. The slack on the radius is there for that case, and the tests check the assumption directly against the exact distance test at every pixel.
Theorem 3 (cost). With tiles, lights and pixels, building the lists costs and shading costs .
Proof. The depth ranges read each pixel once. Each tile tests each light once at cost. Each pixel loops over its list once.
What is not claimed. The test is conservative, not exact. It keeps lights that reach no pixel of the tile: lights near the corner of two planes, where the sphere is outside the frustum but not outside one plane, and lights that sit in a depth gap between the near and the far pixels of a tile. The number of such false positives depends on the scene and is measured, not proved. The radius of a light is a property of the light model: a light whose real falloff never reaches 0 is cut at a radius, and the error of that cut is tuning.
Complexity
The model is the real RAM, with pixels, lights, tiles and an average of kept lights per pixel. The depth ranges cost , the culling sphere tests, and the shading light evaluations. In the worst case every light reaches every tile, and the cost is the of brute force. The lists take space in the worst case; GPUs reserve a fixed maximum per tile. At 1920 by 1080 pixels with 16-pixel tiles, , so 1000 lights cost about 8.2 million sphere tests per frame.
On a GPU, the gain is also in memory traffic. Each pixel reads its G-buffer record once instead of once per light volume, and all pixels of a tile read the same list, which is good for the SIMT model: the threads of a warp run the same loop with the same lights, and their branches agree.
Properties
- Conservative. No light that reaches a pixel is dropped. False positives cost time, not correctness.
- Sensitive to depth range. A tile that holds a near object and a far background gets every light between them.
- Brute force per tile. Each tile tests every light. With very many lights, the term dominates, and a hierarchy over the lights helps.
- Screen-space only. The lists depend on the view and are built again each frame.
- Shared lists. The pixels of a tile run the same light loop, so the work is coherent on SIMT hardware.
Variants and improvements
- Tiled deferred shading. The lists and the shading are built in one compute pass that reads the G-buffer.
- Tiled forward shading. A depth pre-pass gives and . The forward pass reads the list of the tile of each fragment. It supports MSAA and transparent surfaces; for transparent fragments, the tile range must reach from the near plane to , since they lie in front of the opaque depth. Harada, McKee and Yang (2012) published a renderer of this kind.
- 2.5D culling. The depth range of the tile is cut into a fixed number of bins, and a bit mask records which bins hold geometry. A light is kept only if its depth range meets an occupied bin. This removes most of the false positives of depth gaps.
- Tighter tests. Test the sphere against the bounding box of the tile frustum, or the cone of the tile, to remove corner false positives.
- Clusters. Cut the depth into slices as well, and build lists per cluster, see clustered shading.
- Other light shapes. Spot lights use a cone test, and area lights a bounding volume of their range.
When to use it
Use tiled shading when a scene has tens to thousands of local lights with a limited range, and the depth inside a tile is mostly continuous, as in most indoor scenes and top-down views. Use the forward form when MSAA, transparency or many material types matter. Use clustered shading when tiles often hold a large depth range, for example in first-person views with foliage or long views, or when transparent surfaces need light lists at their own depth.
Pitfalls
- No slack in the test. A plane test in floating point can drop a light that touches the frustum by a rounding error. Add a small slack to the radius.
- Depth in the wrong space. The range must be in the same depth as the test. Convert a nonlinear depth buffer value to view depth before the min and max.
- Background pixels. Exclude them from the depth range, or the far plane makes the range of every border tile huge.
- List overflow. A fixed maximum per tile drops lights when it is full, which breaks the guarantee. Size the list for the worst case or fall back to all lights.
- Transparent surfaces. In tiled forward shading, the opaque depth range does not cover them.
- Lights with no range. A light with an infinite falloff cannot be culled. Give every local light a radius, and accept the cut as tuning.
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/tiled-shading/. The authors are listed in prov/TE6F11.jsonl.
"""Tiled light culling and shading, after Olsson and Assarsson (2011).
The screen is cut into square tiles. For each tile the method finds the
smallest and the largest view depth of its pixels, forms the four side planes
of the tile frustum through the eye, and keeps every point light whose sphere
of influence is not fully outside one of these planes or outside the depth
range. Each pixel then loops only over the lights of its tile.
Conventions: the camera is at the origin and looks along -z. The depth buffer
holds the linear view depth d = -z > 0, or math.inf for the background. Pixel
(i, j) has its center at (i + 1/2, j + 1/2), with j counted from the bottom.
A light reaches a point only if the distance is below its radius: the falloff
is exactly 0 from the radius on, so a culled light changes nothing.
"""
import math
from dataclasses import dataclass
Vec3 = tuple[float, float, float]
@dataclass(frozen=True)
class Camera:
width: int
height: int
tan_half: float # tan of half the vertical field of view
def ndc_to_slope(self, sx: float, sy: float) -> tuple[float, float]:
"""Screen position in pixels to the slopes x / d and y / d of the ray."""
aspect = self.width / self.height
u = (2.0 * sx / self.width - 1.0) * aspect * self.tan_half
v = (2.0 * sy / self.height - 1.0) * self.tan_half
return u, v
def position(self, i: int, j: int, d: float) -> Vec3:
"""View-space position of the center of pixel (i, j) at view depth d."""
u, v = self.ndc_to_slope(i + 0.5, j + 0.5)
return (u * d, v * d, -d)
@dataclass(frozen=True)
class Light:
center: Vec3
radius: float
intensity: float
def dot(a: Vec3, b: Vec3) -> float:
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def shade(p: Vec3, n: Vec3, light: Light) -> float:
"""Lambert term times a falloff that is 0 for distances >= radius."""
lx, ly, lz = light.center[0] - p[0], light.center[1] - p[1], light.center[2] - p[2]
dist2 = lx * lx + ly * ly + lz * lz
r2 = light.radius * light.radius
if dist2 >= r2:
return 0.0
dist = math.sqrt(dist2)
cos_t = 0.0 if dist == 0.0 else max(0.0, (n[0] * lx + n[1] * ly + n[2] * lz) / dist)
w = 1.0 - dist2 / r2
return light.intensity * cos_t * w * w
def affects(p: Vec3, light: Light) -> bool:
c = light.center
return (c[0] - p[0]) ** 2 + (c[1] - p[1]) ** 2 + (c[2] - p[2]) ** 2 < light.radius * light.radius
def brute_force(depth, normals, cam: Camera, lights: list[Light]) -> list[list[float]]:
"""Shade every pixel with every light, in the order of the light list."""
out = [[0.0] * cam.width for _ in range(cam.height)]
for j in range(cam.height):
for i in range(cam.width):
d = depth[j][i]
if d == math.inf:
continue
p = cam.position(i, j, d)
c = 0.0
for light in lights:
c += shade(p, normals[j][i], light)
out[j][i] = c
return out
def side_planes(cam: Camera, x0: float, x1: float, y0: float, y1: float) -> list[Vec3]:
"""Unit inward normals of the four planes through the eye that bound the
screen rectangle [x0, x1] x [y0, y1] (in pixels). Each plane is m . x = 0."""
u0, v0 = cam.ndc_to_slope(x0, y0)
u1, v1 = cam.ndc_to_slope(x1, y1)
planes = []
# x / d >= u0, with d = -z, is x + u0 z >= 0; the other three are alike.
for m in ((1.0, 0.0, u0), (-1.0, 0.0, -u1), (0.0, 1.0, v0), (0.0, -1.0, -v1)):
length = math.sqrt(dot(m, m))
planes.append((m[0] / length, m[1] / length, m[2] / length))
return planes
def sphere_in_frustum(planes: list[Vec3], dmin: float, dmax: float, light: Light) -> bool:
"""Conservative test: False only if the sphere misses the tile frustum.
The radius gets a small slack so that rounding cannot drop a light."""
c, r = light.center, light.radius * (1.0 + 1e-9) + 1e-12
for m in planes: # @line L11
if dot(m, c) < -r:
return False
dc = -c[2] # @line L12
if dc + r < dmin or dc - r > dmax:
return False
return True # @line L13
def tile_depth_range(depth, x0: int, x1: int, y0: int, y1: int) -> tuple[float, float] | None:
dmin, dmax = math.inf, -math.inf
for j in range(y0, y1):
for i in range(x0, x1):
d = depth[j][i]
if d != math.inf:
dmin = min(dmin, d)
dmax = max(dmax, d)
if dmin == math.inf:
return None
return dmin, dmax
def build_light_lists(depth, cam: Camera, lights: list[Light], tile: int) -> dict[tuple[int, int], list[int]]:
"""The light list of every tile, in increasing light index."""
lists = {}
for ty in range((cam.height + tile - 1) // tile): # @line L1
for tx in range((cam.width + tile - 1) // tile):
x0, y0 = tx * tile, ty * tile
x1, y1 = min(x0 + tile, cam.width), min(y0 + tile, cam.height)
rng = tile_depth_range(depth, x0, x1, y0, y1) # @line L2
chosen = [] # @line L4
if rng is not None:
planes = side_planes(cam, x0, x1, y0, y1) # @line L3
for idx, light in enumerate(lights): # @line L5
if sphere_in_frustum(planes, rng[0], rng[1], light): # @line L6
chosen.append(idx)
lists[(tx, ty)] = chosen
return lists
def tiled_shading(depth, normals, cam: Camera, lights: list[Light], tile: int = 16):
"""Shade with the tile light lists. Returns the image and the lists."""
lists = build_light_lists(depth, cam, lights, tile)
out = [[0.0] * cam.width for _ in range(cam.height)]
for j in range(cam.height): # @line L7
for i in range(cam.width):
d = depth[j][i]
if d == math.inf:
continue
p = cam.position(i, j, d) # @line L8
c = 0.0
for idx in lists[(i // tile, j // tile)]: # @line L9
c += shade(p, normals[j][i], lights[idx])
out[j][i] = c # @line L10
return out, lists
test_tiled_shading.py 119 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tiled-shading/. The authors are listed in prov/TE6F11.jsonl.
"""Tiled shading against brute-force shading of every light at every pixel."""
import math
import random
from tiled_shading import (
Camera,
Light,
affects,
brute_force,
build_light_lists,
shade,
side_planes,
tiled_shading,
)
def room(cam: Camera, box: bool = True):
"""Depth and normals of a room seen from the origin: a floor at y = -1,
side walls at x = -4 and x = 4, a back wall at z = -12 with an open
window, and a small box face at z = -3."""
depth = [[math.inf] * cam.width for _ in range(cam.height)]
normals = [[(0.0, 0.0, 1.0)] * cam.width for _ in range(cam.height)]
for j in range(cam.height):
for i in range(cam.width):
u, v = cam.ndc_to_slope(i + 0.5, j + 0.5)
hits = []
if not (u * 12.0 > 2.0 and v * 12.0 > 1.0):
hits.append((12.0, (0.0, 0.0, 1.0)))
if v < 0.0:
hits.append((-1.0 / v, (0.0, 1.0, 0.0)))
if u < 0.0 and -4.0 / u <= 12.0:
hits.append((-4.0 / u, (1.0, 0.0, 0.0)))
if u > 0.0 and 4.0 / u <= 12.0:
hits.append((4.0 / u, (-1.0, 0.0, 0.0)))
if box and -1.0 <= 3.0 * u <= 0.5 and -1.0 <= 3.0 * v <= 0.5:
hits.append((3.0, (0.0, 0.0, 1.0)))
if hits:
d, n = min(hits)
depth[j][i] = d
normals[j][i] = n
return depth, normals
def random_lights(rng: random.Random, count: int) -> list[Light]:
return [
Light(
(rng.uniform(-4.0, 4.0), rng.uniform(-1.0, 3.0), rng.uniform(-12.0, -1.0)),
rng.uniform(0.5, 3.0),
rng.uniform(0.5, 2.0),
)
for _ in range(count)
]
def test_no_light_is_missed() -> None:
rng = random.Random(21)
cam = Camera(48, 32, 1.0)
depth, _ = room(cam)
for tile in (4, 8, 16):
lights = random_lights(rng, 40)
lists = build_light_lists(depth, cam, lights, tile)
for j in range(cam.height):
for i in range(cam.width):
if depth[j][i] == math.inf:
continue
p = cam.position(i, j, depth[j][i])
kept = set(lists[(i // tile, j // tile)])
for idx, light in enumerate(lights):
if affects(p, light):
assert idx in kept
def test_equals_brute_force_exactly() -> None:
rng = random.Random(22)
cam = Camera(40, 24, 0.7)
depth, normals = room(cam)
lights = random_lights(rng, 30)
ref = brute_force(depth, normals, cam, lights)
out, _ = tiled_shading(depth, normals, cam, lights, tile=8)
assert out == ref
def test_pixel_centers_are_inside_their_tile_frustum() -> None:
cam = Camera(32, 32, 1.0)
tile = 8
for j in range(cam.height):
for i in range(cam.width):
x0, y0 = (i // tile) * tile, (j // tile) * tile
planes = side_planes(cam, x0, x0 + tile, y0, y0 + tile)
p = cam.position(i, j, 5.0)
assert all(m[0] * p[0] + m[1] * p[1] + m[2] * p[2] >= -1e-12 for m in planes)
def test_light_outside_the_view_is_culled_everywhere() -> None:
cam = Camera(32, 32, 1.0)
depth, _ = room(cam)
behind = Light((0.0, 0.0, 5.0), 2.0, 1.0)
lists = build_light_lists(depth, cam, [behind], 8)
assert all(not v for v in lists.values())
def test_depth_gap_gives_false_positives() -> None:
"""A tile that holds the box (d = 3) and the back wall (d = 12) keeps a
small light at d = 7 in front of the wall, although it reaches no pixel."""
cam = Camera(32, 32, 1.0)
depth, normals = room(cam)
light = Light((-0.3, -0.2, -7.0), 0.5, 1.0)
lists = build_light_lists(depth, cam, [light], 16)
holders = [t for t, v in lists.items() if v]
assert holders
for j in range(cam.height):
for i in range(cam.width):
if depth[j][i] != math.inf:
p = cam.position(i, j, depth[j][i])
assert shade(p, normals[j][i], light) == 0.0
History
Light volumes in deferred shading draw one bounding shape per light and blend the results, which reads the G-buffer once per light. Tiles replace this with one pass that reads the G-buffer once per pixel, which became practical with compute shaders and shared memory on GPUs. Olsson and Assarsson (2011) described tiled deferred and tiled forward shading in a journal paper and studied their cost. Harada, McKee and Yang (2012) showed a forward renderer with a depth pre-pass and per-tile light culling, and argued that it keeps the material freedom of forward shading. Olsson, Billeter and Assarsson (2012) then added depth slices and built clustered shading, noting that the tiled methods test every light against every tile.
References
- Ola Olsson and Ulf Assarsson, Tiled shading, Journal of Graphics, GPU, and Game Tools 15(4), 235-251, 2011, the tile grid, the per-tile depth range and light lists, and tiled deferred and tiled forward shading
- Takahiro Harada, Jay McKee and Jason C. Yang, Forward+: bringing deferred lighting to the next level, Eurographics 2012 Short Papers, 5-8, the depth pre-pass, the light culling per tile in a compute shader, and the forward shading pass that reads the tile lists
- Ola Olsson, Markus Billeter and Ulf Assarsson, Clustered deferred and forward shading, High-Performance Graphics 2012, 87-96, Section 3.3 (light assignment), which notes that tiled methods test all lights per tile by brute force
- 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 20, Efficient Shading (the part on tiled shading)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| 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 TE6F11 Edit this page History Report an error Markdown