Algorithmadvanced
Per-pixel linked list transparency
Also called per-pixel fragment lists.
Append every transparent fragment to a linked list per pixel on the GPU with an atomic counter, then sort and blend each list in a resolve pass.
- Time
- O(p k^2) worstO(f) buildO(p + f k) resolve
- Space
- O(p + n) total
- Where
- f = the number of transparent fragments; k = the largest number of fragments of one pixel; n = the number of nodes in the pool; p = the number of pixels
- Model
- Word RAM
- Properties
- randomizednot in placeofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jason C. Yang, Justin Hensley, Holger Grün, Nicolas Thibieroz, 2010
Per-pixel linked lists are an exact method for order-independent transparency on the GPU. In one geometry pass, every transparent fragment takes a free node from a large shared buffer by an atomic increment of a counter, stores its color, opacity and depth there, and links the node to the front of the list of its pixel with an atomic exchange on a head pointer. In a second, full-screen pass, each pixel walks its list into a small local array, sorts it by depth, and blends it back to front with the over operator. The method is a GPU form of the A-buffer. Yang, Hensley, Grün and Thibieroz described it in 2010. It is exact as long as the shared buffer does not fill up, and its memory grows with the number of fragments.
In plain words
Each pixel keeps a chain of notes, one note per transparent surface that covers it. A big box of blank notes is shared by the whole screen. When a surface is drawn at a pixel, it takes the next blank note, by asking a shared counter for a number that nobody else gets, writes its color and depth on it, and pins it to the front of the chain of that pixel. Thousands of surfaces do this at the same time, so the two steps that touch shared things are atomic. When all surfaces are drawn, each pixel reads its chain, puts the notes in order from near to far, and blends them from the back. If the box of notes runs out, the late surfaces are lost.
The problem
The input is a stream of transparent fragments produced by the rasterizer in an unknown order and in parallel: the pixel , the premultiplied color , the opacity and the view depth , smaller is nearer. The opaque pass has already written the background color and depth of each pixel, and fragments behind the opaque depth are discarded by the depth test. The output is, for each pixel, the composite in depth order
with the fragments of the pixel numbered from front to back. The machine is the word RAM with the atomic operations ATOMIC-ADD (fetch and add) and ATOMIC-EXCHANGE, as GPUs provide on buffers and images.
The algorithm
Line L1 runs once per frame. Lines L2 to L5 run once per fragment, in parallel, in the fragment shader. Lines L6 to L10 run once per pixel, in a full-screen pass after the build. is the capacity of the node pool.
PER-PIXEL-LINKED-LISTS(fragments, C0)- 1
head[q] ← NULL for every pixel q; counter ← 0 - 2
idx ← ATOMIC-ADD(counter, 1) ▷ for each fragment (q, c, α, z), in parallel - 3
if idx ≥ n then drop the fragment and stop - 4
node[idx].(c, α, z) ← (c, α, z) - 5
node[idx].next ← ATOMIC-EXCHANGE(head[q], idx) - 6
a ← empty; i ← head[q] ▷ for each pixel q, after a barrier - 7
while i ≠ NULL: append node[i] to a; i ← node[i].next - 8
INSERTION-SORT(a) by z, nearest first - 9
C ← C0[q]; for j from |a| down to 1: C ← c_j + (1 - α_j) C - 10
out[q] ← C
The pool (lines L2 to L4). The node buffer is one large array shared by all pixels, and the counter is a fetch-and-add allocator over it, as in a memory pool that never frees. Each fragment gets a distinct index, so the writes of line L4 never collide.
The link (line L5). The exchange puts the new node at the head of the list and returns the old head, which becomes the next field of the new node. This is the push of a linked list stack, made safe for many writers by doing the read and the write of the head as one atomic step. No thread ever reads the next field during the build, so no lock and no compare-and-swap loop is needed.
The resolve (lines L6 to L10). The list is read into a local array of a fixed size, often 8 to 64 entries. Insertion sort is the usual choice, because the lists are short and the code is small. The fold of line L9 is the over operator of alpha blending from back to front.
Memory. A node holds the color, the opacity, the depth and the next index, for example 4 bytes of RGBA8, 4 bytes of depth and 4 bytes of index: 12 bytes. The head image holds one 32-bit index per pixel.
Example
Two pixels and a pool of 3 nodes. Four fragments arrive: green at pixel 0 with , , ; red at pixel 0 with , , ; blue at pixel 1 with , , ; and blue again at pixel 0 with . Say the threads run in this order without overlap.
| step | counter after | idx | head[0] | head[1] | next[idx] |
|---|---|---|---|---|---|
| green at 0 | 1 | 0 | 0 | NULL | NULL |
| red at 0 | 2 | 1 | 1 | NULL | 0 |
| blue at 1 | 3 | 2 | 1 | 2 | NULL |
| blue at 0 | 4 | 3 | dropped |
The pool is full, so the last fragment is lost. Pixel 0 walks , which is red then green, sorts them to red (), green (), and over black gives green , then red over it: . With a pool of 4 nodes, the blue fragment would also be in the list of pixel 0, and the result would be . In another interleaving, a different fragment could win the last node, so with overflow the image depends on the timing.
Correctness
The proofs are in the proofs folder, under the assumption that the atomic operations are linearizable and that the resolve starts after the build has finished. The counter gives the values to distinct threads, so the kept fragments have distinct nodes. Fix a pixel. Its exchanges happen in some total order, and each returns the node of the one before it, or NULL for the first. Each thread writes that value into the next field of its own node. So after the build, the list of the pixel runs through all its kept nodes in the reverse order of the exchanges and ends at NULL, with no node twice. The resolve then sorts the fragments by depth and folds the over operator, which is the definition of the composite. So the result is exact for every interleaving when the pool does not overflow and depths are distinct. With overflow, the result is the exact composite of the kept fragments. The tests run the build under many random interleavings of the atomic steps, in exact rational arithmetic, and check all three claims.
Proof: The lists hold every kept fragment once, and the resolve is exactfull
Setting. A frame has transparent fragments, each with a pixel , and a pool of nodes. The atomic operations are linearizable: every ATOMIC-ADD on the counter and every ATOMIC-EXCHANGE on a head pointer takes effect at one point in time, and all of them form one total order consistent with each thread. Other writes of a thread (lines L4 and the write of the next field in line L5) touch only the node that the thread owns. At the start, the counter is 0 and every head is NULL (line L1). The resolve pass starts after every thread of the build pass has finished; on a GPU this is the barrier between the two passes.
Lemma 1 (distinct nodes). The ATOMIC-ADD calls return the values , each to exactly one thread. A fragment is kept if and only if its value is below , so exactly fragments are kept, each in its own node.
Proof. The calls are totally ordered. The -th call in this order reads and writes , by induction on , because no other operation writes the counter. Line L3 drops a fragment exactly when its value is at least .
Lemma 2 (shape of one list). Fix a pixel . Let be the exchanges on in their total order, with the node values . Then returns , with . After the build pass, (or NULL if ), and for every .
Proof. Only exchanges at write , and it starts as NULL. By induction, just before the head holds , and returns this value and writes . The thread that owns node writes the returned value into , and no other thread writes that field, because the nodes are distinct by Lemma 1. When all threads have finished, every one of these writes has happened.
Theorem 1 (the lists are complete). After the build pass, the walk from visits and stops. So it visits exactly the kept fragments of pixel , each once, in the reverse order of their exchanges.
Proof. By Lemma 2 the walk starts at and follows down to , where line L7 stops. The values are distinct, so no node is visited twice. Every kept fragment of does one exchange at , and dropped fragments do none.
The order of a list depends on the interleaving. The set of its nodes does not, when nothing is dropped.
Theorem 2 (the resolve is exact). If the pool is large enough () and the depths of the fragments of each pixel are distinct, the resolve of pixel returns the composite in depth order of all fragments of , for every interleaving of the build.
Proof. By Lemma 1 and Theorem 1, the walk collects all fragments of . Insertion sort (line L8) puts them in increasing depth, which is unique because the depths are distinct. Line L9 folds from the farthest to the nearest, starting at , which unrolls to the sum above.
With equal depths, the stable insertion sort keeps the list order, which depends on the timing, so the result for ties can change from frame to frame.
Theorem 3 (overflow). If , the resolve returns, for each pixel, the exact composite of the kept fragments of that pixel. The kept fragments are those that won the first values of the counter, which depends on the interleaving.
Proof. Theorem 1 and the proof of Theorem 2 apply to the kept fragments. Lemma 1 says which they are.
Theorem 4 (cost). The build does work and at most atomic operations. The resolve of a pixel with fragments does comparisons in the worst case and blends. The memory is head pointers, one counter and nodes.
Proof. Each thread does a constant number of steps. Insertion sort on items does at most comparisons and moves.
Complexity
The model is the word RAM with atomic fetch-and-add and exchange. The build does work and at most two atomic operations per fragment, in total. The resolve reads every list once, , and sorts each list of fragments in , which sums to at most with the longest list. The memory is head pointers and nodes. At 1920 by 1080 pixels with an average of 4 transparent fragments per pixel and 12-byte nodes, the pool needs bytes, about 94.9 MiB, plus 7.9 MiB of heads.
On a GPU, all fragments of the frame contend on one counter. The hardware merges atomic increments within a warp, but the counter is still a hot spot. The resolve diverges when neighboring pixels have lists of very different length.
Properties
- Exact when the pool is large enough. Every fragment is kept and sorted.
- One geometry pass. Unlike depth peeling, the scene is drawn once.
- Unbounded memory. The pool must be sized for the worst frame, or fragments are dropped.
- Nondeterministic order. The order of a list depends on timing. The image does not, unless the pool overflows or two depths are equal.
- Lock-free. No thread waits for another. Each fragment finishes in a fixed number of steps.
- Local array limit. The resolve can hold only a fixed number of fragments per pixel. Longer lists must be truncated or merged.
Variants and improvements
- Per-pixel arrays. Count the fragments of each pixel in a first pass, compute offsets with a prefix sum, and write the fragments into a packed array in a second pass. The memory is exact but the geometry is drawn twice.
- Fixed-size arrays per pixel. Reserve slots per pixel and an atomic counter per pixel. There is no shared pool, but the memory is and long lists overflow.
- Insertion during the build. Keep each list sorted by inserting new fragments in depth order with compare-and-swap. The resolve need not sort, but the build is slower and contended.
- Keep the nearest . Merge fragments behind the first into one approximate layer, as in the k-buffer.
- Sorting networks. For a fixed local array size, a sorting network has no branches and can be faster than insertion sort on SIMT hardware.
- MSAA. Store a coverage mask in each node, as the A-buffer does.
When to use it
Use it when the transparent content needs exact order, such as overlapping colored glass, scientific visualization with many layers, or reference images to test approximate methods against. It needs a memory budget for the worst depth complexity. For particles and smoke with very many layers and similar colors, weighted blended OIT is cheaper and has fixed memory.
Pitfalls
- Pool overflow. A full pool drops fragments silently and the image changes with the timing. Check the counter after the frame and grow the pool, or fall back to an approximate method.
- Local array overflow. Lists longer than the local array of the resolve lose fragments. Clamp and report it.
- No barrier. The resolve must start after all writes of the build are visible. Use a memory barrier between the passes.
- Early depth test. Without the opaque depth test, fragments behind opaque surfaces fill the pool.
- Resetting. The head image must be set to NULL and the counter to 0 each frame. A stale head points to nodes of the previous frame.
- Ties. Coplanar transparent surfaces give equal depths, and the result then flickers with the timing. Break ties by a primitive id.
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/per-pixel-linked-lists/. The authors are listed in prov/XK6ZQN.jsonl.
"""Per-pixel linked lists for order-independent transparency.
The build pass appends each fragment to a list per pixel with two atomic
operations: a fetch-and-add on a global counter, which gives the fragment a
node in a shared pool, and an exchange on the head pointer of its pixel. The
resolve pass walks each list, sorts it by depth and blends back to front.
GPU threads are modeled as Python generators. Each `yield` ends one atomic
step, and a scheduler interleaves the steps of many threads at random, so the
tests can check the build for many interleavings. A fragment is (c, alpha, z)
with a premultiplied color c, an opacity alpha and a view depth z (smaller is
nearer). The arithmetic works on floats or fractions.Fraction values.
"""
import random
from typing import Iterator, List, Optional, Sequence, Tuple
NULL = -1
Fragment = tuple # (c, alpha, z)
class FragmentLists:
"""The head pointer image, the atomic counter and the node pool."""
def __init__(self, num_pixels: int, capacity: int) -> None:
self.capacity = capacity
self.head = [NULL] * num_pixels # @line L1
self.counter = 0
self.frag: List[Optional[Fragment]] = [None] * capacity
self.next = [NULL] * capacity
self.exchange_log: List[Tuple[int, int]] = [] # (pixel, node), for the tests
def atomic_add(self) -> int:
old = self.counter
self.counter = old + 1
return old
def atomic_exchange(self, q: int, value: int) -> int:
old = self.head[q]
self.head[q] = value
self.exchange_log.append((q, value))
return old
def insert(store: FragmentLists, q: int, fragment: Fragment) -> Iterator[None]:
"""One fragment-shader thread. The generator returns the node index, or
NULL if the pool was full and the fragment was dropped."""
idx = store.atomic_add() # @line L2
yield
if idx >= store.capacity: # @line L3
return NULL
store.frag[idx] = fragment # @line L4
yield
old = store.atomic_exchange(q, idx) # @line L5
yield
store.next[idx] = old
return idx
def run_interleaved(threads: Sequence[Iterator[None]], rng: random.Random) -> list:
"""Run the threads to the end, one atomic step at a time, choosing the
next thread at random. Returns the return value of each thread."""
results = [None] * len(threads)
live = list(range(len(threads)))
while live:
k = rng.randrange(len(live))
t = live[k]
try:
next(threads[t])
except StopIteration as stop:
results[t] = stop.value
live[k] = live[-1]
live.pop()
return results
def build(num_pixels: int, capacity: int, fragments: Sequence[Tuple[int, Fragment]], rng: random.Random):
"""Build the lists for (pixel, fragment) pairs with a random interleaving."""
store = FragmentLists(num_pixels, capacity)
threads = [insert(store, q, f) for q, f in fragments]
nodes = run_interleaved(threads, rng)
return store, nodes
def walk(store: FragmentLists, q: int) -> List[int]:
out = []
i = store.head[q] # @line L6
while i != NULL: # @line L7
out.append(i)
i = store.next[i]
return out
def insertion_sort_by_depth(frags: List[Fragment]) -> List[Fragment]:
a = list(frags)
for i in range(1, len(a)): # @line L8
x = a[i]
j = i - 1
while j >= 0 and a[j][2] > x[2]:
a[j + 1] = a[j]
j -= 1
a[j + 1] = x
return a
def resolve_pixel(store: FragmentLists, q: int, background: tuple) -> tuple:
a = insertion_sort_by_depth([store.frag[i] for i in walk(store, q)])
result = tuple(background)
for c, alpha, _ in reversed(a): # @line L9
result = tuple(ci + (1 - alpha) * ri for ci, ri in zip(c, result))
return result # @line L10
def resolve(store: FragmentLists, background: tuple) -> list:
return [resolve_pixel(store, q, background) for q in range(len(store.head))]
def over_composite(frags: Sequence[Fragment], background: tuple) -> tuple:
"""The reference: Python's sort, then the over operator back to front."""
result = tuple(background)
for c, alpha, _ in sorted(frags, key=lambda f: f[2], reverse=True):
result = tuple(ci + (1 - alpha) * ri for ci, ri in zip(c, result))
return result
test_per_pixel_linked_lists.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/per-pixel-linked-lists/. The authors are listed in prov/XK6ZQN.jsonl.
"""Per-pixel linked lists: the build under random interleavings and the resolve."""
import random
from fractions import Fraction as F
from per_pixel_linked_lists import (
NULL,
build,
insertion_sort_by_depth,
over_composite,
resolve,
walk,
)
BG = (F(1, 10), F(2, 10), F(3, 10))
def random_scene(rng: random.Random, num_pixels: int, count: int):
depths = rng.sample(range(1, 10 * count + 10), count)
pairs = []
for z in depths:
q = rng.randrange(num_pixels)
a = F(rng.randint(1, 20), 20)
col = tuple(a * F(rng.randint(0, 10), 10) for _ in range(3))
pairs.append((q, (col, a, F(z))))
return pairs
def per_pixel(pairs, num_pixels, keep=None):
lists = [[] for _ in range(num_pixels)]
for t, (q, f) in enumerate(pairs):
if keep is None or t in keep:
lists[q].append(f)
return lists
def test_exact_when_the_pool_is_large_enough() -> None:
rng = random.Random(51)
for _ in range(20):
p = rng.randint(1, 6)
pairs = random_scene(rng, p, rng.randint(0, 25))
store, nodes = build(p, len(pairs) + rng.randint(0, 3), pairs, rng)
assert NULL not in nodes
assert sorted(nodes) == list(range(len(pairs)))
expect = per_pixel(pairs, p)
for q in range(p):
got = sorted(store.frag[i][2] for i in walk(store, q))
assert got == sorted(f[2] for f in expect[q])
assert resolve(store, BG) == [over_composite(expect[q], BG) for q in range(p)]
def test_image_does_not_depend_on_the_interleaving() -> None:
rng = random.Random(52)
p = 4
pairs = random_scene(rng, p, 30)
images = set()
lists = set()
for seed in range(15):
store, _ = build(p, 40, pairs, random.Random(seed))
images.add(tuple(resolve(store, BG)))
lists.add(tuple(tuple(walk(store, q)) for q in range(p)))
assert len(images) == 1
assert len(lists) > 1 # the lists themselves do depend on the timing
def test_list_is_the_reverse_of_the_exchange_order() -> None:
rng = random.Random(53)
for _ in range(20):
p = rng.randint(1, 5)
pairs = random_scene(rng, p, rng.randint(1, 20))
store, _ = build(p, len(pairs), pairs, rng)
for q in range(p):
order = [i for qq, i in store.exchange_log if qq == q]
assert walk(store, q) == order[::-1]
def test_overflow_keeps_the_first_n_counter_values() -> None:
rng = random.Random(54)
differs = 0
for _ in range(20):
p = rng.randint(1, 4)
pairs = random_scene(rng, p, rng.randint(5, 25))
cap = rng.randint(0, len(pairs) - 1)
store, nodes = build(p, cap, pairs, rng)
kept = {t for t, i in enumerate(nodes) if i != NULL}
assert len(kept) == cap
assert sorted(nodes[t] for t in kept) == list(range(cap))
assert store.counter == len(pairs)
img = resolve(store, BG)
assert img == [over_composite(fs, BG) for fs in per_pixel(pairs, p, kept)]
if img != [over_composite(fs, BG) for fs in per_pixel(pairs, p)]:
differs += 1
assert differs > 0 # dropped fragments change the image
def test_insertion_sort_is_stable_and_sorted() -> None:
rng = random.Random(55)
for _ in range(50):
a = [((rng.randint(0, 3),), F(1, 2), rng.randint(0, 5)) for _ in range(rng.randint(0, 12))]
assert insertion_sort_by_depth(a) == sorted(a, key=lambda f: f[2])
def test_worked_example() -> None:
red = ((F(1, 2), F(0), F(0)), F(1, 2), F(1))
blue = ((F(0), F(0), F(1, 2)), F(1, 2), F(2))
green = ((F(0), F(1, 4), F(0)), F(1, 4), F(3))
pairs = [(0, green), (0, red), (1, blue), (0, blue)]
store, nodes = build(2, 3, pairs, random.Random(7))
kept = [t for t, i in enumerate(nodes) if i != NULL]
assert len(kept) == 3 and store.counter == 4
black = (F(0), F(0), F(0))
full = over_composite([red, blue, green], black)
assert full == (F(1, 2), F(1, 16), F(1, 4))
History
The A-buffer of Carpenter (1984) kept a list of fragments per pixel in a software renderer, and depth peeling made exact transparency possible on GPUs without such lists, at one geometry pass per layer. When GPUs gained atomic operations and writes to arbitrary buffers from the fragment shader, Yang, Hensley, Grün and Thibieroz (2010) built the lists on the GPU in one pass with a global counter and an atomic exchange on a head pointer per pixel, and sorted and blended each list in a second pass. The method became a common reference for exact order-independent transparency, and later work on bounded memory, such as weighted blended OIT, compares against it.
References
- Jason C. Yang, Justin Hensley, Holger Grün and Nicolas Thibieroz, Real-time concurrent linked list construction on the GPU, Computer Graphics Forum 29(4) (EGSR 2010), 1297-1304, the head pointer buffer, the node buffer with an atomic counter, the atomic exchange that links a new node, and the sort and blend of each list in a second pass
- Morgan McGuire and Louis Bavoil, Weighted blended order-independent transparency, Journal of Computer Graphics Techniques 2(2), 122-141, 2013, the review of exact methods with unbounded memory per pixel, and their cost compared with one-pass approximations
- Thomas Porter and Tom Duff, Compositing digital images, SIGGRAPH 1984, Computer Graphics 18(3), 253-259, the over operator used by the resolve pass
- 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 5.5, Transparency, Alpha, and Compositing (the part on per-pixel lists of fragments)
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 XK6ZQN Edit this page History Report an error Markdown