Three.js Tiled Forward+ Lighting (1024 Lights)

Tiled forward (Forward+) lighting in Three.js, where the CPU bins up to 1024 point lights into 32-pixel screen tiles each frame and fragments shade only their tile's lights, with a per-tile heatmap and a brute-force comparison.

Key topics: three.js forward plus, tiled lighting, clustered shading, light culling, many lights, heatmap

What this code does

- Light Data: positions (view space), radii and colors are packed into a float `DataTexture`.
- Binning: each light sphere is projected to a conservative screen rectangle and appended to every overlapped tile's list.
- Tile Lists: a second float texture stores [count, indices…] per tile, read with `texelFetch`.
- Shading: fragments find their tile from gl_FragCoord and loop only that tile's lights, usually a handful instead of 1024.
- Heatmap: shows light counts per tile; dense clusters glow red where tiles approach their capacity.
- Brute Force: the same shader looping all lights shows the cost tiling avoids.
- Controls: shading mode, light count, radius, speed and bulb visibility.

Continue Learning

JavaScript Implementation

ES6+
// Tiled light culling (CPU) → per-tile index lists in a float texture
for (const light of lights) {
  const rect = projectSphereToScreen(light.viewPos, light.radius) // conservative pixel bounds
  for (let ty = rect.y0; ty <= rect.y1; ty++) {
    for (let tx = rect.x0; tx <= rect.x1; tx++) {
      const base = (ty * tilesX + tx) * (PER_TILE + 1)
      const count = tileData[base]
      if (count < PER_TILE) { tileData[base + 1 + count] = light.index; tileData[base] = count + 1 }
    }
  }
}
// fragment shader: only loop the lights binned into this pixel's tile
const glsl = `
  int row = int(gl_FragCoord.y / tilePx) * tilesX + int(gl_FragCoord.x / tilePx);
  int count = int(texelFetch(uTiles, ivec2(0, row), 0).r);
  for (int k = 1; k <= 63; k++) { if (k > count) break; color += shade(int(texelFetch(uTiles, ivec2(k, row), 0).r)); }`