Algorithm Search⌘K

Data structurecore

G-buffer

Also called geometry buffer.

A set of screen-sized images that stores, per pixel, the depth and the surface attributes of the nearest surface, such as the normal, the base color and the roughness, for a later shading pass.

Time
Θ(p m b) clearO(1) read · write
Space
Θ(p m b) total
Where
b = the number of bytes per pixel; m = the number of samples per pixel; p = the number of pixels
Properties
not concurrentnot externalnot persistent
Origin
Takafumi Saito, Tokiichiro Takahashi, 1990

A G-buffer is a group of screen-sized images, written in one geometry pass, that keeps for each pixel the depth and the surface attributes of the nearest surface: for example the normal, the base color, the roughness and the metallic value. Later passes read it instead of the triangles. It is the data structure under deferred shading, which shades each pixel once from these values, and under screen-space effects such as screen-space ambient occlusion. A visibility buffer is a smaller relative: it stores only a triangle id per pixel and computes the attributes again. Saito and Takahashi named the G-buffer in 1990. This page gives one layout as an example and the octahedral encoding of the normal, which is the most common way to store a normal in 32 bits.

In plain words

When the renderer draws the scene, it does not compute the light yet. For each pixel it only writes down facts about the surface that is closest to the camera: how far away it is, which way it faces, what color it is and how rough it is. These notes fill a few images of the same size as the screen. A later pass reads the notes for each pixel and computes the light from them, without going back to the triangles. The notes must be small, because there is one set for every pixel, so each value is packed into few bits. A direction, for example, is stored as two short numbers instead of three long ones.

The abstract type

A G-buffer of width WW and height HH holds p=WHp = W H records, one per pixel, or pmp m records with mm samples per pixel. Each record has the same fixed fields. The operations are:

  • clear: set every record to the value of the background (the far depth and no surface).
  • write(pixel, record): store the record of a fragment that passes the depth test. The geometry pass calls it, and the z-buffer test decides which fragment is kept.
  • read(pixel): return the record. Lighting and screen-space passes call it.

After the geometry pass, the record of each pixel is the record of the fragment with the smallest depth at that pixel, which is the depth test invariant. The buffer holds one surface per pixel and sample. It cannot hold a second, partly hidden surface, so it has no place for transparent fragments.

Representation

Each field is a channel of one of a few render targets, and the GPU writes all targets of a pixel in one fragment shader call. The layout below is an example, not a standard. Engines differ in the fields, the formats and the number of targets.

target format content bytes
depth 32-bit float the depth of the nearest surface 4
RT0 RGBA, 8 bits unorm each base color (sRGB) and metallic 4
RT1 RG, 16 bits snorm each normal, octahedral code 4
RT2 RGBA, 8 bits unorm each roughness and 3 spare channels 4

This layout uses b=16b = 16 bytes per pixel. The view-space position is not stored: the shading pass computes it from the depth and the pixel position.

The octahedral normal. A unit normal n=(x,y,z)n = (x, y, z) has two degrees of freedom, so three floats waste space. The octahedral map of Cigolle, Donow, Evangelakos, Mara, McGuire and Meyer (2014) divides nn by s=∣x∣+∣y∣+∣z∣s = |x| + |y| + |z|, which puts it on the octahedron ∣x∣+∣y∣+∣z∣=1|x| + |y| + |z| = 1. The upper half (z≥0z \ge 0) projects straight down onto the diamond ∣u∣+∣v∣≤1|u| + |v| \le 1. The lower half is folded out over the four corners of the square [−1,1]2[-1, 1]^2. The square is then stored as two signed normalized integers of bb bits. The survey compares this map with many other unit-vector codes and finds it among the best in error for its size, at a low cost of encode and decode. That ranking is a measurement.

Operations

Lines L1 to L4 encode and lines L5 to L7 decode a normal. sgn⁡(x)\operatorname{sgn}(x) is +1+1 for x≥0x \ge 0 and −1-1 for x<0x < 0. The assignment in L3 and L6 is simultaneous: both new values use the old uu and vv. Lines L8 and L9 store a value of [−1,1][-1, 1] in bb bits with m=2b−1−1m = 2^{b-1} - 1. Lines L10 to L15 write and read one texel of the example layout.

  1. OCT-ENCODE(n)
  2. 1s ← |n.x| + |n.y| + |n.z|
  3. 2(u, v) ← (n.x / s, n.y / s)
  4. 3if n.z < 0 then (u, v) ← ((1 - |v|) sgn(u), (1 - |u|) sgn(v)) ▷ fold the lower half
  5. 4return (u, v)
  6. OCT-DECODE(u, v)
  7. 5z ← 1 - |u| - |v|
  8. 6if z < 0 then (u, v) ← ((1 - |v|) sgn(u), (1 - |u|) sgn(v)) ▷ unfold
  9. 7return (u, v, z) / ‖(u, v, z)‖
  10. QUANTIZE(x, b) and DEQUANTIZE(q, b)
  11. 8q ← round(x · m)
  12. 9x ← max(-1, q / m)
  13. PACK-TEXEL(c, n, r, k) ▷ base color c, normal n, roughness r, metallic k
  14. 10word0 ← unorm8(c.r) | unorm8(c.g) << 8 | unorm8(c.b) << 16 | unorm8(k) << 24
  15. 11word1 ← the two 16-bit codes QUANTIZE(OCT-ENCODE(n), 16), low half first
  16. 12word2 ← unorm8(r)
  17. UNPACK-TEXEL(word0, word1, word2)
  18. 13c ← the low three bytes of word0 / 255; k ← the high byte / 255
  19. 14n ← OCT-DECODE(DEQUANTIZE of the two signed halves of word1)
  20. 15return (c, n, word2 / 255, k)

The sign rule sgn⁡(0)=+1\operatorname{sgn}(0) = +1 matters. With the usual sign function, which is 0 at 0, a normal in the plane x=0x = 0 or y=0y = 0 with z<0z < 0 folds to a wrong point. The clamp in L9 is there because the integer −2b−1-2^{b-1} has no partner; it maps to −1-1 like −m-m.

Precise encoding. Rounding uu and vv separately does not always give the code that decodes closest to nn. The survey also gives an encoder that tries the four integer points around (um,vm)(u m, v m) and keeps the one with the smallest angle error. It costs four decodes and helps when the normal is written once and read many times.

Example

Encode and decode. Take n=(0.6,0,−0.8)n = (0.6, 0, -0.8). Line L1 gives s=1.4s = 1.4 and line L2 gives (u,v)=(0.428571,0)(u, v) = (0.428571, 0). Since z<0z < 0, line L3 folds: u←(1−0)⋅(+1)=1u \leftarrow (1 - 0) \cdot (+1) = 1 and v←(1−0.428571)⋅sgn⁡(0)=0.571429v \leftarrow (1 - 0.428571) \cdot \operatorname{sgn}(0) = 0.571429. The code is (1,0.571429)(1, 0.571429), a point on the right edge of the square.

To decode, line L5 gives z=1−1−0.571429=−0.571429z = 1 - 1 - 0.571429 = -0.571429, which is negative, so line L6 unfolds to (0.428571,0)(0.428571, 0). Line L7 normalizes (0.428571,0,−0.571429)(0.428571, 0, -0.571429), whose length is 0.7142860.714286, and returns (0.6,0,−0.8)(0.6, 0, -0.8).

With 8 bits. m=127m = 127, so the code becomes the integers (127,73)(127, 73), because 0.571429⋅127=72.570.571429 \cdot 127 = 72.57. Decoding gives 73/127=0.57480373 / 127 = 0.574803, then (0.425197,0,−0.574803)(0.425197, 0, -0.574803) after the unfold, and (0.594701,0,−0.803947)(0.594701, 0, -0.803947) after normalizing. The angle error is 0.3790.379 degrees. With 16 bits (m=32767m = 32767) the code is (32767,18724)(32767, 18724), and since 18724/32767=4/718724 / 32767 = 4/7 exactly, this normal decodes without error.

One texel. The base color (0.5,0.25,1)(0.5, 0.25, 1), metallic 0, the normal above and roughness 0.40.4 give the three words 0x00FF4080 (the bytes 128, 64, 255 and 0, low byte first), 0x49247FFF (the codes 32767 and 18724) and 0x00000066 (102, which is 0.4⋅2550.4 \cdot 255).

Memory. At 1920 by 1080 pixels, p=2 073 600p = 2\,073\,600, and the 16 bytes of the layout take 33 177 60033\,177\,600 bytes, about 31.6 MiB. With 4 samples per pixel for multisample antialiasing, every sample needs its own record, and the size is 126.6 MiB. These numbers are the reason for tight packing.

Correctness

The proofs are in the proofs folder. With sgn⁡(0)=+1\operatorname{sgn}(0) = +1 and exact arithmetic:

  • OCT-ENCODE maps every nonzero vector into [−1,1]2[-1, 1]^2, and OCT-DECODE(OCT-ENCODE(n)(n)) =n/∥n∥= n / \lVert n \rVert. The proof splits on the sign of zz and shows that the unfold undoes the fold, because the fold keeps the signs of uu and vv.
  • On the open square (−1,1)2(-1, 1)^2 the map is also one to one in the other direction: OCT-ENCODE(OCT-DECODE(u,v)(u, v)) =(u,v)= (u, v). On the border, (1,t)(1, t) and (1,−t)(1, -t) decode to the same vector, and the four corners all decode to (0,0,−1)(0, 0, -1).
  • Quantization moves each coordinate by at most 1/(2m)1 / (2m). The angle error after decoding is not proved here. The values in the tests are measurements on 4000 random directions: below 1 degree with 8 bits and below 0.005 degrees with 16 bits, and the precise encoding is never worse.
  • The texel pack and unpack return each 8-bit value to within 1/5101/510 and give the normal of the 16-bit code.

The depth test invariant of the abstract type is a property of the z-buffer, see its page.

Proof: The octahedral normal encoding is a round tripfull

Setting. sgn⁡(x)=1\operatorname{sgn}(x) = 1 for x≥0x \ge 0 and −1-1 for x<0x < 0, so that sgn⁡(0)=1\operatorname{sgn}(0) = 1. The fold is F(u,v)=((1−∣v∣)sgn⁡(u),(1−∣u∣)sgn⁡(v))F(u, v) = ((1 - |v|) \operatorname{sgn}(u), (1 - |u|) \operatorname{sgn}(v)). OCT-ENCODE (lines L1 to L4) maps a nonzero vector n=(x,y,z)n = (x, y, z) to (x/s,y/s)(x / s, y / s) with s=∣x∣+∣y∣+∣z∣s = |x| + |y| + |z| if z≥0z \ge 0, and to F(x/s,y/s)F(x / s, y / s) if z<0z < 0. OCT-DECODE (lines L5 to L7) maps (u,v)∈[−1,1]2(u, v) \in [-1, 1]^2 to the normalized vector of (u,v,1−∣u∣−∣v∣)(u, v, 1 - |u| - |v|) if ∣u∣+∣v∣≤1|u| + |v| \le 1, and of (F(u,v),1−∣u∣−∣v∣)(F(u, v), 1 - |u| - |v|) otherwise. The claims are in exact arithmetic.

Lemma 1 (the image is in the square). For every nonzero nn, OCT-ENCODE(n)∈[−1,1]2(n) \in [-1, 1]^2.

Proof. ∣x/s∣+∣y/s∣≤1|x / s| + |y / s| \le 1, so both coordinates are in [−1,1][-1, 1]. The fold keeps them there, because 1−∣v∣1 - |v| and 1−∣u∣1 - |u| are in [0,1][0, 1] when ∣u∣,∣v∣≤1|u|, |v| \le 1. □\square

Theorem 1 (round trip). For every nonzero nn, OCT-DECODE(OCT-ENCODE(n)(n)) =n/∥n∥= n / \lVert n \rVert.

Proof. Let u=x/su = x / s, v=y/sv = y / s, w=z/sw = z / s. Then ∣u∣+∣v∣+∣w∣=1|u| + |v| + |w| = 1, so (u,v,w)(u, v, w) is nn scaled by the positive number 1/s1 / s.

Case z≥0z \ge 0. The encoder returns (u,v)(u, v). The decoder computes 1−∣u∣−∣v∣=∣w∣=w1 - |u| - |v| = |w| = w, which is not negative, so it does not fold. It returns the normalized vector of (u,v,w)(u, v, w), which is n/∥n∥n / \lVert n \rVert.

Case z<0z < 0. Then ∣w∣>0|w| > 0, so ∣u∣<1|u| < 1 and ∣v∣<1|v| < 1. The encoder returns (u′,v′)=F(u,v)(u', v') = F(u, v), with ∣u′∣=1−∣v∣>0|u'| = 1 - |v| > 0 and ∣v′∣=1−∣u∣>0|v'| = 1 - |u| > 0. So sgn⁡(u′)=sgn⁡(u)\operatorname{sgn}(u') = \operatorname{sgn}(u) and sgn⁡(v′)=sgn⁡(v)\operatorname{sgn}(v') = \operatorname{sgn}(v); this needs sgn⁡(0)=1\operatorname{sgn}(0) = 1 when uu or vv is 0. The decoder computes 1−∣u′∣−∣v′∣=∣u∣+∣v∣−1=−∣w∣=w<01 - |u'| - |v'| = |u| + |v| - 1 = -|w| = w < 0, so it folds:

F(u′,v′)=((1−∣v′∣)sgn⁡(u′),(1−∣u′∣)sgn⁡(v′))=(∣u∣sgn⁡(u),∣v∣sgn⁡(v))=(u,v).F(u', v') = ((1 - |v'|) \operatorname{sgn}(u'), (1 - |u'|) \operatorname{sgn}(v')) = (|u| \operatorname{sgn}(u), |v| \operatorname{sgn}(v)) = (u, v).

It returns the normalized vector of (u,v,w)(u, v, w), which is again n/∥n∥n / \lVert n \rVert. □\square

Theorem 2 (the other direction). For every (u,v)(u, v) in the open square (−1,1)2(-1, 1)^2, OCT-ENCODE(OCT-DECODE(u,v)(u, v)) =(u,v)= (u, v).

Proof. The decoder computes a vector mm proportional to (a,b,c)(a, b, c) with ∣a∣+∣b∣+∣c∣=1|a| + |b| + |c| = 1: for ∣u∣+∣v∣≤1|u| + |v| \le 1, (a,b,c)=(u,v,1−∣u∣−∣v∣)(a, b, c) = (u, v, 1 - |u| - |v|) with c≥0c \ge 0; otherwise (a,b)=F(u,v)(a, b) = F(u, v) and c=1−∣u∣−∣v∣<0c = 1 - |u| - |v| < 0, and ∣a∣+∣b∣=2−∣u∣−∣v∣=1−c=1+∣c∣|a| + |b| = 2 - |u| - |v| = 1 - c = 1 + |c|. So m=(a,b,c)/λm = (a, b, c) / \lambda with λ=∥(a,b,c)∥\lambda = \lVert (a, b, c) \rVert, the encoder computes s=1/λs = 1 / \lambda, and it gets (mx/s,my/s)=(a,b)(m_x / s, m_y / s) = (a, b), with the sign of mzm_z equal to the sign of cc. In the first case it returns (a,b)=(u,v)(a, b) = (u, v). In the second case it returns F(a,b)F(a, b). Here ∣u∣,∣v∣<1|u|, |v| < 1, so ∣a∣=1−∣v∣>0|a| = 1 - |v| > 0 and ∣b∣=1−∣u∣>0|b| = 1 - |u| > 0, the signs are kept, and F(a,b)=(u,v)F(a, b) = (u, v) as in Theorem 1. □\square

On the border of the square the map is not one to one: (1,t)(1, t) and (1,−t)(1, -t) decode to the same vector, and all four corners decode to (0,0,−1)(0, 0, -1). The encoder returns one of these points. This does not affect Theorem 1.

Theorem 3 (quantization). With bb bits per coordinate and m=2b−1−1m = 2^{b-1} - 1, QUANTIZE (line L8) followed by DEQUANTIZE (line L9) changes each coordinate in [−1,1][-1, 1] by at most 1/(2m)1 / (2m).

Proof. round⁡(xm)\operatorname{round}(x m) differs from xmx m by at most 1/21/2, and xm∈[−m,m]x m \in [-m, m], so the result is in [−m,m][-m, m] and the clamp in line L9 does not act on it. Dividing by mm gives the bound. □\square

The angle error that this coordinate error causes after decoding depends on where the point is in the square. The largest values on the page and in the tests (below 1 degree for 8 bits and below 0.005 degrees for 16 bits per coordinate) are measurements on random directions, not proved bounds.

Theorem 4 (the texel layout). UNPACK-TEXEL(PACK-TEXEL(c,n,r,k)(c, n, r, k)) returns each color channel, the roughness and the metallic value to within 1/5101 / 510 of the input, after clamping to [0,1][0, 1], and returns the normal of the 16-bit octahedral code of nn.

Proof. Each unorm8 value is round⁡(255x)∈[0,255]\operatorname{round}(255 x) \in [0, 255], so it fits in 8 bits, the shifts put the four values in disjoint bytes of word 0, and the masks in the unpack read them back unchanged. Division by 255 gives a value within 1/5101/510 of xx. The two 16-bit codes are stored as two's complement in the two halves of word 1 and read back with sign extension, so DECODE receives the same pair of integers. □\square

Complexity

The model is the real RAM with pp pixels, mm samples per pixel and bb bytes per record. A write and a read are O(1)O(1). A clear is Θ(pmb)\Theta(p m b) in bytes, though GPUs often clear with a fast metadata flag. The space is Θ(pmb)\Theta(p m b). The encode and decode of a normal take O(1)O(1) operations and one square root.

On a GPU the cost that matters is memory bandwidth. The geometry pass writes bb bytes for every fragment that passes the depth test, including fragments that a nearer fragment later overwrites, and each lighting or screen-space pass reads bb bytes per pixel. A layout with fewer bytes per pixel is often faster even when it needs more arithmetic to decode. This is the trade that the octahedral code makes, see memory coalescing.

Variants

  • Thin G-buffer. Only depth and normal, for a light pre-pass: the lights are accumulated into a light buffer, and a second geometry pass reads it to apply the materials.
  • Visibility buffer. Only the triangle id and the instance id. The visibility buffer page explains the trade.
  • Other normal codes. Spherical coordinates, a stored (x,y)(x, y) with zz computed from them (wrong for normals that face away from the camera, which occur with normal maps and perspective), and the sphere map code. The survey of Cigolle and coauthors compares them.
  • Material ids. Some layouts store a small material or shading model id per pixel, so that the shading pass can branch per pixel. This costs bits and can cause warp divergence.
  • Multisample G-buffer. One record per sample, with a resolve that shades edge pixels per sample and inner pixels once.

When to use it

Use a G-buffer when many lights or screen-space passes need the surface attributes of each pixel, and the cost of reading them back is lower than the cost of drawing the geometry again. Keep it as small as the materials allow. Use a visibility buffer when the G-buffer bandwidth is the limit, for example at high resolution or with many samples per pixel. Do not use it for transparent surfaces: draw them in a forward pass after the deferred pass.

Pitfalls

  • The sign of zero. Use a sign function with sgn⁡(0)=+1\operatorname{sgn}(0) = +1 in the fold, or normals with x=0x = 0 or y=0y = 0 in the lower half decode wrong.
  • The (x,y)(x, y) code with z≥0z \ge 0 assumed. View-space normals can point away from the camera, so the sign of zz must be stored.
  • Base color in the wrong space. Store the base color in an sRGB format, which the hardware converts, or in linear values with more bits. 8-bit linear values band in dark areas.
  • Interpolating codes. Do not filter the encoded normal across pixels: the code is not linear, and the fold edges give wrong values. Decode first.
  • Precision of depth. If the position is computed from the depth, the depth format sets its precision. A 24-bit depth with a standard projection loses precision far from the camera.
  • Bandwidth of MSAA. With mm samples per pixel the buffer is mm times larger.

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.

g_buffer.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/g-buffer/. The authors are listed in prov/P04D18.jsonl.

"""A G-buffer texel with an octahedral normal, after Cigolle et al. (2014).

The octahedral map projects a unit vector onto the octahedron
|x| + |y| + |z| = 1, keeps the upper half as it is, and folds the lower half
out over the four corners of the square [-1, 1]^2. The square is then stored
as two signed normalized integers of b bits each.

The texel layout is an example, not a standard: three 32-bit words, with the
base color and the metallic value in unorm8, the normal in two snorm16 values
and the roughness in unorm8. The depth is kept in the depth buffer.
"""

import math

Vec3 = tuple[float, float, float]


def sign_not_zero(x: float) -> float:
    """+1 for x >= 0 and -1 for x < 0. The fold needs sign(0) = +1."""
    return 1.0 if x >= 0.0 else -1.0


def normalize(v: Vec3) -> Vec3:
    length = math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2])
    return (v[0] / length, v[1] / length, v[2] / length)


def oct_encode(n: Vec3) -> tuple[float, float]:
    """Map a nonzero vector to a point of the square [-1, 1]^2."""
    s = abs(n[0]) + abs(n[1]) + abs(n[2])  # @line L1
    u, v = n[0] / s, n[1] / s  # @line L2
    if n[2] < 0.0:  # @line L3
        u, v = (1.0 - abs(v)) * sign_not_zero(u), (1.0 - abs(u)) * sign_not_zero(v)
    return u, v  # @line L4


def oct_decode(u: float, v: float) -> Vec3:
    """Map a point of the square back to a unit vector."""
    z = 1.0 - abs(u) - abs(v)  # @line L5
    if z < 0.0:  # @line L6
        u, v = (1.0 - abs(v)) * sign_not_zero(u), (1.0 - abs(u)) * sign_not_zero(v)
    return normalize((u, v, z))  # @line L7


def quantize_snorm(x: float, bits: int) -> int:
    """Store x in [-1, 1] as a signed integer of the given width."""
    m = (1 << (bits - 1)) - 1
    return round(max(-1.0, min(1.0, x)) * m)  # @line L8


def dequantize_snorm(q: int, bits: int) -> float:
    m = (1 << (bits - 1)) - 1
    return max(-1.0, q / m)  # @line L9


def encode_normal(n: Vec3, bits: int) -> tuple[int, int]:
    u, v = oct_encode(n)
    return quantize_snorm(u, bits), quantize_snorm(v, bits)


def decode_normal(q: tuple[int, int], bits: int) -> Vec3:
    return oct_decode(dequantize_snorm(q[0], bits), dequantize_snorm(q[1], bits))


def encode_normal_best(n: Vec3, bits: int) -> tuple[int, int]:
    """Try the four integer neighbors of the encoded point and keep the one
    that decodes closest to n. Cigolle et al. call this the precise encoding."""
    u, v = oct_encode(n)
    m = (1 << (bits - 1)) - 1
    best = None
    best_dot = -2.0
    for qu in (math.floor(u * m), math.floor(u * m) + 1):
        for qv in (math.floor(v * m), math.floor(v * m) + 1):
            q = (max(-m, min(m, qu)), max(-m, min(m, qv)))
            d = decode_normal(q, bits)
            dot = d[0] * n[0] + d[1] * n[1] + d[2] * n[2]
            if dot > best_dot:
                best, best_dot = q, dot
    return best


def unorm8(x: float) -> int:
    return round(max(0.0, min(1.0, x)) * 255.0)


def pack_texel(albedo: Vec3, normal: Vec3, roughness: float, metallic: float) -> tuple[int, int, int]:
    """The geometry pass writes one texel: three 32-bit words."""
    r, g, b = (unorm8(c) for c in albedo)
    word0 = r | (g << 8) | (b << 16) | (unorm8(metallic) << 24)  # @line L10
    qu, qv = encode_normal(normal, 16)
    word1 = (qu & 0xFFFF) | ((qv & 0xFFFF) << 16)  # @line L11
    word2 = unorm8(roughness)  # @line L12
    return word0, word1, word2


def to_signed16(x: int) -> int:
    return x - 0x10000 if x & 0x8000 else x


def unpack_texel(words: tuple[int, int, int]) -> tuple[Vec3, Vec3, float, float]:
    """The lighting pass reads the texel back."""
    word0, word1, word2 = words
    albedo = tuple((word0 >> s & 0xFF) / 255.0 for s in (0, 8, 16))  # @line L13
    metallic = (word0 >> 24 & 0xFF) / 255.0
    q = (to_signed16(word1 & 0xFFFF), to_signed16(word1 >> 16 & 0xFFFF))
    normal = decode_normal(q, 16)  # @line L14
    roughness = (word2 & 0xFF) / 255.0
    return albedo, normal, roughness, metallic  # @line L15
test_g_buffer.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/g-buffer/. The authors are listed in prov/P04D18.jsonl.

"""Tests of the octahedral normal encoding and of the example texel layout."""

import math
import random

from g_buffer import (
    decode_normal,
    encode_normal,
    encode_normal_best,
    normalize,
    oct_decode,
    oct_encode,
    pack_texel,
    unpack_texel,
)


def random_unit(rng: random.Random) -> tuple[float, float, float]:
    while True:
        v = (rng.gauss(0.0, 1.0), rng.gauss(0.0, 1.0), rng.gauss(0.0, 1.0))
        if v[0] * v[0] + v[1] * v[1] + v[2] * v[2] > 1e-6:
            return normalize(v)


def angle_deg(a, b) -> float:
    d = a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
    return math.degrees(math.acos(max(-1.0, min(1.0, d))))


def close(a, b, tol: float = 1e-12) -> bool:
    return all(abs(x - y) <= tol for x, y in zip(a, b))


def test_axes_and_corners() -> None:
    assert oct_encode((0.0, 0.0, 1.0)) == (0.0, 0.0)
    assert oct_encode((1.0, 0.0, 0.0)) == (1.0, 0.0)
    assert oct_encode((0.0, -1.0, 0.0)) == (0.0, -1.0)
    # The south pole goes to a corner; all four corners decode to it.
    assert oct_encode((0.0, 0.0, -1.0)) == (1.0, 1.0)
    for u, v in ((1.0, 1.0), (-1.0, 1.0), (1.0, -1.0), (-1.0, -1.0)):
        assert close(oct_decode(u, v), (0.0, 0.0, -1.0))


def test_round_trip_float() -> None:
    rng = random.Random(7)
    for _ in range(3000):
        n = random_unit(rng)
        u, v = oct_encode(n)
        assert -1.0 <= u <= 1.0 and -1.0 <= v <= 1.0
        assert close(oct_decode(u, v), n)


def test_round_trip_on_signed_zeros_and_equator() -> None:
    for n in ((0.0, 0.6, -0.8), (0.6, 0.0, -0.8), (-0.6, -0.0, -0.8), (0.6, 0.8, 0.0), (-0.8, 0.6, -0.0)):
        assert close(oct_decode(*oct_encode(n)), normalize(n))


def test_square_to_sphere_to_square() -> None:
    """On the open square the map is one to one, so encode(decode(p)) = p."""
    rng = random.Random(8)
    for _ in range(3000):
        u, v = rng.uniform(-0.999, 0.999), rng.uniform(-0.999, 0.999)
        p = oct_encode(oct_decode(u, v))
        assert abs(p[0] - u) < 1e-12 and abs(p[1] - v) < 1e-12


def test_decode_is_unit() -> None:
    rng = random.Random(9)
    for _ in range(2000):
        d = oct_decode(rng.uniform(-1.0, 1.0), rng.uniform(-1.0, 1.0))
        assert abs(d[0] ** 2 + d[1] ** 2 + d[2] ** 2 - 1.0) < 1e-12


def test_quantized_error_measured() -> None:
    """Measured largest angle errors on 4000 random directions. These are
    measurements on this sample, not proved bounds."""
    rng = random.Random(10)
    worst = {8: 0.0, 16: 0.0}
    worst_best = {8: 0.0, 16: 0.0}
    for _ in range(4000):
        n = random_unit(rng)
        for bits in (8, 16):
            worst[bits] = max(worst[bits], angle_deg(n, decode_normal(encode_normal(n, bits), bits)))
            worst_best[bits] = max(worst_best[bits], angle_deg(n, decode_normal(encode_normal_best(n, bits), bits)))
    assert worst[8] < 1.0 and worst[16] < 0.005
    assert worst_best[8] <= worst[8] and worst_best[16] <= worst[16]


def test_texel_round_trip() -> None:
    rng = random.Random(11)
    for _ in range(500):
        albedo = (rng.random(), rng.random(), rng.random())
        n = random_unit(rng)
        rough, metal = rng.random(), rng.random()
        words = pack_texel(albedo, n, rough, metal)
        assert all(0 <= w < 1 << 32 for w in words)
        a2, n2, r2, m2 = unpack_texel(words)
        assert all(abs(x - y) <= 0.5 / 255.0 + 1e-12 for x, y in zip(albedo, a2))
        assert abs(rough - r2) <= 0.5 / 255.0 + 1e-12
        assert abs(metal - m2) <= 0.5 / 255.0 + 1e-12
        assert angle_deg(n, n2) < 0.005
        again = pack_texel(a2, n2, r2, m2)
        assert again[0] == words[0] and again[2] == words[2]

History

Deering, Winner, Schediwy, Duffy and Hunt built a hardware pipeline in 1988 that found the visible surface first and then shaded each pixel from its stored normal. Saito and Takahashi (1990) gave the stored per-pixel geometry the name G-buffer, and used it for image-space operations: edges, contours and hatching for illustration. In games, deferred shading with a G-buffer became common in the late 2000s, when GPUs could write several render targets at once. The octahedral normal map was used in graphics before 2014; the survey by Cigolle, Donow, Evangelakos, Mara, McGuire and Meyer compared it with the other codes and made it a standard choice.

References

  1. Takafumi Saito and Tokiichiro Takahashi, Comprehensible rendering of 3-D shapes, SIGGRAPH 1990, Computer Graphics 24(4), 197-206, the geometric buffers (G-buffers) and the image-space operations on them
  2. Zina H. Cigolle, Sam Donow, Daniel Evangelakos, Michael Mara, Morgan McGuire and Quirin Meyer, A survey of efficient representations for independent unit vectors, Journal of Computer Graphics Techniques 3(2), 1-30, 2014, the octahedral representation, its encode and decode, and the precise encoding that tests the nearby integer codes
  3. Michael Deering, Stephanie Winner, Bic Schediwy, Chris Duffy and Neil Hunt, The triangle processor and normal vector shader: a VLSI system for high performance graphics, SIGGRAPH 1988, 21-30, the shading of each pixel from a stored normal after the visibility stage
  4. 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 deferred shading and G-buffer layouts)

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.clear
  • a full proof of time.read
  • a full proof of time.write
  • a full proof of space.total
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)
WritingW4 complete
  • a review of the text: no review record reviews/P04D18/text.yaml