Three.js Screen-Space Global Illumination (SSGI)

One-bounce screen-space global illumination in Three.js that gathers light reflected by nearby visible pixels from color, depth and normal buffers, with temporal accumulation and visible color bleeding in a Cornell box.

Key topics: three.js ssgi, global illumination, color bleeding, screen space, indirect lighting, cornell box

What this code does

- G-Buffers: the lit scene with a depth texture, plus view-space normals from a `MeshNormalMaterial` override pass.
- Gather: each pixel samples a golden-angle spiral of nearby pixels, reconstructs their positions from depth and treats them as small emitters.
- Form Factor: weights use both normals, (n·ω)(n'·−ω)/(1 + d²), so only surfaces facing each other exchange light.
- Color Bleeding: the red and green walls tint the white box and sphere, the hallmark of indirect light.
- Temporal Accumulation: half-resolution GI blends with the previous frame to hide the per-pixel noise.
- Limits: off-screen and hidden surfaces contribute nothing, the classic screen-space tradeoff.
- Controls: view (direct+GI, direct, indirect), GI strength, radius, samples, accumulation and moving sphere.

Continue Learning

JavaScript Implementation

ES6+
// Screen-space GI gather (fragment shader excerpt): nearby visible pixels act as tiny light sources
const ssgi = `
  vec3 p = viewPos(vUv);                         // reconstructed from the depth buffer
  vec3 n = normalize(texture2D(uNormal, vUv).xyz * 2.0 - 1.0);
  vec3 gi = vec3(0.0);
  for (int i = 0; i < 16; i++) {
    vec2 suv = vUv + spiralOffset(i) * radius / -p.z;
    vec3 d = viewPos(suv) - p;
    vec3 dir = normalize(d);
    vec3 nq = normalize(texture2D(uNormal, suv).xyz * 2.0 - 1.0);
    float w = max(dot(n, dir), 0.0) * max(dot(nq, -dir), 0.0) / (1.0 + dot(d, d));
    gi += texture2D(uColor, suv).rgb * w;        // light reflected by the sample point
  }
  gl_FragColor = vec4(direct + gi / 16.0 * strength, 1.0);`