GameCrew AIEarly access
Sign in
Godot 4lightingRevision 1 · Compile-verified pattern

WebGL 2 2D Radiance Cascades Global Illumination in Godot 4.7 (Compatibility)

Updated

Noise-free, real-time 2D/top-down Radiance Cascades global illumination in Godot 4.7 Compatibility (WebGL 2) using a zero-lag 2-SubViewport cascade chain (64-ray far cascade merged 16x into 4-ray near probes), gamma-2.0 HDR RGBA8 packing, half-texel tile clamping, and a 3D arena floor lightmap.

  • radiance-cascades
  • gi
  • global-illumination
  • penumbra
  • shadows
  • lighting
  • subviewport
  • shader
  • compatibility
  • webgl2

No demo.

When to Use (and When Not To)

Top-down dungeons, stealth courtyards, isometric roguelites, and neon arenas often need dozens of simultaneous colored light sources casting smooth soft penumbras — far beyond what Compatibility-mode OmniLight3D shadow maps allow in WebGL 2. 2D Radiance Cascades computes noise-free colored global illumination at constant $O(1)$ cost independent of light count, with zero temporal ghosting and zero compute shaders:

  • Use this technique when gameplay occurs on a primary ground plane or arena floor with glowing pylons, torches, lasers, portals, and vertical shadow-casting walls/pillars.
  • Skip this technique for vertical multi-story indoor towers where floor-level occlusion does not approximate upper walkways — pair standard directional shadows or height-masked layers there.

Mathematical & Algorithmic Core

  1. Zero-Lag 2-Cascade Spatial/Angular Split (256×256 Atlas):
  • Cascade 1 (Far, [5..205 px]): 8×8 = 64 angular rays per probe at 32×32 spatial probe density (50 fixed raymarch steps, hitting every pillar cleanly with zero tunneling).
  • Cascade 0 (Near, [0..5 px]): 2×2 = 4 angular quadrants at 128×128 spatial probe density (6 fine contact steps), merging 16 child sub-angles from Cascade 1 whenever a near ray misses.
  • Using two SubViewports (c = 1 added before c = 0) eliminates multi-frame viewport-chain lag and cuts VRAM in half compared to 4-pass chains.
  1. Gamma-2.0 HDR Packing Inside Standard RGBA8 SubViewports:
  • WebGL 2 Compatibility SubViewports store RGBA8, which would clip bright emissive pylons to 1.0 and crush distant penumbras after angular averaging.
  • Encoding sqrt(clamp(radiance / 8.0, 0.0, 1.0)) on write and decoding enc * enc * 8.0 on read preserves [0..8.0] HDR range with 4× higher precision in soft shadow penumbras.
  1. Half-Texel Tile Clamping:
  • Clamp bilinear lookups inside each direction tile (clamp(probe_uv * probes, vec2(0.5), vec2(probes - 0.5))) so adjacent angular tiles never bleed across tile borders.

Engine Implementation

1. Cascade Interval Raymarch & HDR Merge Shader (Assets/Game/Shaders/rc_cascade.gdshader)

shader_type canvas_item;
render_mode blend_disabled, unshaded;

uniform sampler2D scene_tex : filter_nearest, repeat_disable;
uniform sampler2D upper_tex : filter_linear, repeat_disable;
uniform int cascade_index = 0;
uniform int atlas_size = 256;
uniform int has_upper = 0;
uniform float near_span = 5.0;
uniform float far_span = 205.0;
uniform float emission_boost = 6.5;
uniform vec3 ambient_sky = vec3(0.03, 0.04, 0.08);

const float TAU_VAL = 6.28318530718;
const float MAX_RAD = 8.0;

vec3 encode_hdr(vec3 rad) {
	return sqrt(clamp(rad / MAX_RAD, vec3(0.0), vec3(1.0)));
}

vec3 decode_hdr(vec3 enc) {
	return enc * enc * MAX_RAD;
}

vec3 sample_upper_probe(vec2 probe_uv, int upper_dir_idx, int upper_grid_side, float upper_probe_count) {
	float tile_x = float(upper_dir_idx % upper_grid_side);
	float tile_y = floor(float(upper_dir_idx) / float(upper_grid_side));
	vec2 local_px = clamp(probe_uv * upper_probe_count, vec2(0.5), vec2(upper_probe_count - 0.5));
	vec2 atlas_uv = (vec2(tile_x, tile_y) * upper_probe_count + local_px) / float(atlas_size);
	return decode_hdr(textureLod(upper_tex, atlas_uv, 0.0).rgb);
}

void fragment() {
	float f_atlas = float(atlas_size);
	int grid_side = (cascade_index == 0) ? 2 : 8;
	int probe_count = atlas_size / grid_side;
	float f_probes = float(probe_count);

	vec2 px = floor(UV * f_atlas);
	vec2 tile = floor(px / f_probes);
	vec2 probe_px = mod(px, f_probes);
	vec2 probe_uv = (probe_px + vec2(0.5)) / f_probes;

	int dir_idx = int(tile.y) * grid_side + int(tile.x);
	int total_dirs = grid_side * grid_side;
	float angle = (float(dir_idx) + 0.5) * TAU_VAL / float(total_dirs);
	vec2 ray_dir = vec2(cos(angle), sin(angle));

	float t_min = (cascade_index == 0) ? 0.0 : near_span;
	float t_max = (cascade_index == 0) ? near_span : far_span;
	int step_count = (cascade_index == 0) ? 6 : 50;
	float dt = (t_max - t_min) / float(step_count);
	vec2 inv_res = vec2(1.0 / f_atlas);

	vec3 radiance = vec3(0.0);
	float visibility = 1.0;

	for (int i = 0; i < 50; i++) {
		if (i >= step_count) {
			break;
		}
		float dist = t_min + (float(i) + 0.5) * dt;
		vec2 sample_uv = probe_uv + ray_dir * dist * inv_res;
		if (sample_uv.x < 0.0 || sample_uv.x > 1.0 || sample_uv.y < 0.0 || sample_uv.y > 1.0) {
			break;
		}
		vec4 hit = textureLod(scene_tex, sample_uv, 0.0);
		if (hit.a > 0.5) {
			float falloff = 1.0 / (1.0 + dist * 0.011);
			radiance = hit.rgb * emission_boost * falloff;
			visibility = 0.0;
			break;
		}
	}

	if (visibility > 0.5) {
		if (has_upper == 1) {
			int upper_grid_side = 8;
			float upper_probes = f_atlas / 8.0;
			vec3 merged = vec3(0.0);
			int base_dir = dir_idx * 16;
			for (int k = 0; k < 16; k++) {
				merged += sample_upper_probe(probe_uv, base_dir + k, upper_grid_side, upper_probes);
			}
			radiance += merged * 0.0625;
		} else {
			radiance += ambient_sky;
		}
	}

	COLOR = vec4(encode_hdr(radiance), visibility);
}

2. 3D Floor Irradiance Display Shader (Assets/Game/Shaders/rc_floor.gdshader)

shader_type spatial;
render_mode unshaded, cull_disabled;

uniform sampler2D cascade0_tex : filter_linear, repeat_disable;
uniform float atlas_size = 256.0;
uniform vec3 floor_albedo = vec3(0.32, 0.35, 0.42);
uniform float gi_exposure = 2.6;

const float MAX_RAD = 8.0;

vec3 sample_quadrant(vec2 uv, vec2 tile) {
	float probes = atlas_size * 0.5;
	vec2 local_px = clamp(uv * probes, vec2(0.5), vec2(probes - 0.5));
	vec2 atlas_uv = (tile * probes + local_px) / atlas_size;
	vec3 enc = textureLod(cascade0_tex, atlas_uv, 0.0).rgb;
	return enc * enc * MAX_RAD;
}

void fragment() {
	vec3 irrad = (
		sample_quadrant(UV, vec2(0.0, 0.0)) +
		sample_quadrant(UV, vec2(1.0, 0.0)) +
		sample_quadrant(UV, vec2(0.0, 1.0)) +
		sample_quadrant(UV, vec2(1.0, 1.0))
	) * 0.25;

	vec2 tile_uv = fract(UV * 16.0);
	float seam = smoothstep(0.02, 0.06, tile_uv.x) * smoothstep(0.02, 0.06, tile_uv.y);
	vec3 stone = floor_albedo * mix(0.68, 1.04, seam);

	vec3 lit = stone * (vec3(0.08, 0.10, 0.16) + irrad * gi_exposure) + irrad * 0.55;
	vec3 mapped = (lit * (2.51 * lit + 0.03)) / (lit * (2.43 * lit + 0.59) + 0.14);
	ALBEDO = pow(clamp(mapped, vec3(0.0), vec3(1.0)), vec3(1.0 / 2.2));
}

3. Typed GDScript Cascade Pipeline & Scene Stamper (Assets/Game/Scripts/gameplay/radiance_cascades_2d.gd)

class_name RadianceCascades2D
extends RefCounted

const CASCADE_COUNT: int = 2
const NEAR_SPAN: float = 5.0
const FAR_SPAN: float = 205.0

var atlas_size: int = 256
var world_span: float = 16.0
var scene_image: Image
var scene_texture: ImageTexture
var viewports: Array[SubViewport] = []
var cascade_materials: Array[ShaderMaterial] = []
var floor_mesh: MeshInstance3D
var floor_material: ShaderMaterial


static func interval_bounds(cascade_index: int, near_span: float = NEAR_SPAN, far_span: float = FAR_SPAN) -> Vector2:
	if cascade_index <= 0:
		return Vector2(0.0, near_span)
	return Vector2(near_span, far_span)


func setup(parent: Node3D, cascade_shader: Shader, floor_shader: Shader, p_world_span: float = 16.0, p_atlas_size: int = 256) -> MeshInstance3D:
	atlas_size = clampi(p_atlas_size, 128, 256)
	world_span = p_world_span
	scene_image = Image.create(atlas_size, atlas_size, false, Image.FORMAT_RGBA8)
	scene_image.fill(Color(0.0, 0.0, 0.0, 0.0))
	scene_texture = ImageTexture.create_from_image(scene_image)

	viewports.clear()
	cascade_materials.clear()
	viewports.resize(CASCADE_COUNT)
	cascade_materials.resize(CASCADE_COUNT)

	for i in range(CASCADE_COUNT - 1, -1, -1):
		var vp := SubViewport.new()
		vp.name = "RadianceCascadeVP_%d" % i
		vp.size = Vector2i(atlas_size, atlas_size)
		vp.disable_3d = true
		vp.transparent_bg = false
		vp.render_target_update_mode = SubViewport.UPDATE_ALWAYS
		vp.canvas_item_default_texture_filter = Viewport.DEFAULT_CANVAS_ITEM_TEXTURE_FILTER_LINEAR

		var mat := ShaderMaterial.new()
		mat.shader = cascade_shader
		mat.set_shader_parameter("scene_tex", scene_texture)
		mat.set_shader_parameter("cascade_index", i)
		mat.set_shader_parameter("atlas_size", atlas_size)
		mat.set_shader_parameter("near_span", NEAR_SPAN)
		mat.set_shader_parameter("far_span", FAR_SPAN)
		mat.set_shader_parameter("emission_boost", 6.5)
		if i == 0:
			mat.set_shader_parameter("has_upper", 1)
			mat.set_shader_parameter("upper_tex", viewports[1].get_texture())
		else:
			mat.set_shader_parameter("has_upper", 0)

		var rect := ColorRect.new()
		rect.size = Vector2(float(atlas_size), float(atlas_size))
		rect.material = mat
		vp.add_child(rect)
		parent.add_child(vp)

		viewports[i] = vp
		cascade_materials[i] = mat

	var plane := PlaneMesh.new()
	plane.size = Vector2(world_span, world_span)
	floor_material = ShaderMaterial.new()
	floor_material.shader = floor_shader
	floor_material.set_shader_parameter("cascade0_tex", viewports[0].get_texture())
	floor_material.set_shader_parameter("atlas_size", float(atlas_size))

	floor_mesh = MeshInstance3D.new()
	floor_mesh.name = "RadianceCascadesFloor"
	floor_mesh.mesh = plane
	floor_mesh.material_override = floor_material
	floor_mesh.position = Vector3(0.0, 0.01, 0.0)
	floor_mesh.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
	parent.add_child(floor_mesh)
	return floor_mesh


func world_to_texel(world_xz: Vector2) -> Vector2i:
	var u: float = clampf(world_xz.x / world_span + 0.5, 0.0, 0.999)
	var v: float = clampf(world_xz.y / world_span + 0.5, 0.0, 0.999)
	return Vector2i(int(u * float(atlas_size)), int(v * float(atlas_size)))


func clear_scene() -> void:
	scene_image.fill(Color(0.0, 0.0, 0.0, 0.0))


func stamp_disc(world_xz: Vector2, radius_world: float, color: Color, occluder_alpha: float = 1.0) -> void:
	var center := world_to_texel(world_xz)
	var rad_px: int = maxi(1, int(ceilf((radius_world / world_span) * float(atlas_size))))
	var r2: int = rad_px * rad_px
	var px_col := Color(clampf(color.r, 0.0, 1.0), clampf(color.g, 0.0, 1.0), clampf(color.b, 0.0, 1.0), occluder_alpha)
	var x0: int = maxi(0, center.x - rad_px)
	var x1: int = mini(atlas_size - 1, center.x + rad_px)
	var y0: int = maxi(0, center.y - rad_px)
	var y1: int = mini(atlas_size - 1, center.y + rad_px)
	for y in range(y0, y1 + 1):
		var dy: int = y - center.y
		for x in range(x0, x1 + 1):
			var dx: int = x - center.x
			if dx * dx + dy * dy <= r2:
				scene_image.set_pixel(x, y, px_col)


func stamp_box(world_xz: Vector2, size_xz: Vector2, color: Color = Color(0.0, 0.0, 0.0, 1.0)) -> void:
	var p0 := world_to_texel(world_xz - size_xz * 0.5)
	var p1 := world_to_texel(world_xz + size_xz * 0.5)
	var x0: int = clampi(mini(p0.x, p1.x), 0, atlas_size - 1)
	var x1: int = clampi(maxi(p0.x, p1.x), 0, atlas_size - 1)
	var y0: int = clampi(mini(p0.y, p1.y), 0, atlas_size - 1)
	var y1: int = clampi(maxi(p0.y, p1.y), 0, atlas_size - 1)
	var px_col := Color(clampf(color.r, 0.0, 1.0), clampf(color.g, 0.0, 1.0), clampf(color.b, 0.0, 1.0), 1.0)
	for y in range(y0, y1 + 1):
		for x in range(x0, x1 + 1):
			scene_image.set_pixel(x, y, px_col)


func commit_scene() -> void:
	scene_texture.update(scene_image)

Performance, Browser & Software-Renderer Budgets

  • Constant WebGL 2 loop bounds: for (int i = 0; i < 50; i++) with textureLod(..., 0.0) compiles cleanly on WebGL 2 with no dynamic unroll stalls.
  • blend_disabled + Gamma-2.0 HDR packing: Leaving default alpha blending enabled inside rc_cascade.gdshader corrupts A = visibility, and omitting gamma-2.0 HDR packing clips bright emitters in RGBA8 SubViewports.
  • 512 KB total VRAM: Two 256×256 RGBA8 SubViewports run smoothly in browser WebGL 2 and headless software renderers; lower atlas_size to 128 for low-end phones.

Integration & Verification Checklist

  1. Stamp static walls once or rebuild scene_image only when moving emitters change (commit_scene() uploads one 256×256 RGBA8 texture).
  2. Unit-test RadianceCascades2D.interval_bounds(c) to confirm zero gaps between c = 0 and c = 1.
  3. Capture top-down and close courtyard angles to verify vibrant multi-colored GI bounce and smooth penumbra shadows behind every pillar.

Official references

  • Alexander Sannikov (2024 — Radiance Cascades: A Novel Approach to Calculating Global Illumination)
  • Rouli Freeman & Alexander Sannikov (2026 — Split Radiance Cascades: Real-Time Global Illumination via Sparse Radiance Probes)
  • Godot 4.7 Compatibility SubViewport & CanvasItem Shader Reference

More Godot 4 games

Games made with GameCrew on the same engine. No game has been built with this guide yet: these show what Godot 4 games here look like.

Fernlight — Raise a carved whistle to your lips in a fog-drowned forest, coax a glowing bird onto your open hand, and point to send it off to light the dark.
Plays in VR

Fernlight

Raise a carved whistle to your lips in a fog-drowned forest, coax a glowing bird onto your open hand, and point to send it off to light the dark.

More Godot 4 techniques

shaders

Cel-Shading, Shadow Ramps & Width-Compensated Outlines in Godot 4 Compatibility →

Godot 4.7 Compatibility cel-shading spatial shader using custom light() shadow ramps, colored shadow tints, sun-gated Fresnel rim highlights, and a next_pass clip-space width-compensated inverted-hull outline.

ai

Context Steering, Patrol Paths & Telegraphed Enemy Encounters in Godot 4 →

Typed GDScript 4 context steering, LevelData patrol-path following, line-of-sight perception with memory hysteresis, attack-token pacing, and telegraphed combat state machines.

optimization

Staggered-Wave Dynamic Shadows & Time-Sliced SubViewport Reflections in Godot 4.7 →

Keep multi-light courtyards and live planar reflections fast in Godot 4.7 Compatibility (WebGL 2) with a deterministic ShadowWaveScheduler that caps active local shadow casters via distance hysteresis, fades shadow_opacity smoothly, and time-slices reflection SubViewports with SubViewport.UPDATE_ONCE and cut detection.

water

Stylized Water, Gerstner Waves & Depth Shoreline Foam in Godot 4 Compatibility →

Godot 4.7 Compatibility spatial water shader using analytical Gerstner vertex waves, hint_depth_texture shoreline foam, Beer-Lambert depth absorption, and Fresnel horizon sheen.

Read via free MCP — or sign in to add techniques & beta test

Use /mcp/library free with no login to query guides, or connect via OAuth at /mcp to contribute technique guides and beta test cloud builds.

Connect via MCP