# 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.

- **Canonical page:** https://gamecrew.ai/techniques/godot/staggered-shadow-reflection-budget
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Godot 4
- **Category:** optimization
- **Tags:** `shadows`, `staggered`, `time-sliced`, `subviewport`, `reflections`, `optimization`, `budget`, `hysteresis`, `webgl2`, `compatibility`
- **Verification:** Compile-verified pattern
- **Revision:** 1 (2026-11-30)
- **Demo:** No demo

## When to Use (and When Not To)

Enabling `shadow_enabled = true` on `6–12` `OmniLight3D` torches plus an `UPDATE_ALWAYS` reflection `SubViewport` quickly doubles or triples draw calls in Godot 4.7 Compatibility (WebGL 2), choking mobile browsers, headsets, and software renderers. **Staggered-Wave Shadow & Reflection Scheduling** keeps visual richness while enforcing a strict per-frame GPU budget:

- **Use this technique** in torch-lit interiors, lantern pavilions, dungeons, or waterfront plazas with many dynamic lights and secondary reflection/portal `SubViewport`s.
- **Skip this technique** when a scene has only a single directional light and zero secondary render targets — simply tighten `directional_shadow_max_distance` and `SHADOW_PARALLEL_2_SPLITS`.

## Mathematical & Algorithmic Core

1. **Distance-Hysteresis Local Shadow Budgeting**:
   - Rank every registered `OmniLight3D` / `SpotLight3D` by camera distance, subtracting a sticky hysteresis margin ($h = 1.5\text{ m}$) from lights that are *already* casting shadows:
     $$\text{score}_i = \|\mathbf{p}_i - \mathbf{c}\| - h \cdot \mathbb{I}(i \in \mathcal{A}_{\text{prev}})$$
   - Keep only the top `max_active_local_shadows` (`2` on WebGL 2 / mobile, `4` on desktop). The hysteresis band stops lights near the rank boundary from flickering on/off when the player strafes.
   - Ramp `light.shadow_opacity` smoothly toward `1.0` or `0.0` via `move_toward(opacity, target, delta * fade_speed)` and disable `shadow_enabled` once `shadow_opacity <= 0.02`, eliminating harsh shadow popping.
2. **Time-Sliced `SubViewport.UPDATE_ONCE` Reflections with Cut Detection**:
   - Instead of `SubViewport.UPDATE_ALWAYS`, fire `reflection_viewport.render_target_update_mode = SubViewport.UPDATE_ONCE` on frame 1 and every `reflection_stride`-th tick (e.g., stride `3` cuts reflection render passes by **66%**).
   - Detect camera teleports or rapid cuts ($\|\mathbf{c}_t - \mathbf{c}_{t-1}\|^2 > 4.0$ or $\hat{\mathbf{f}}_t \cdot \hat{\mathbf{f}}_{t-1} < 0.94$) and trigger an immediate `UPDATE_ONCE` so multi-view captures and camera switches never show a stale reflection frame.

## Engine Implementation

### 1. Deterministic Shadow & Reflection Wave Scheduler (`Assets/Game/Scripts/gameplay/shadow_wave_scheduler.gd`)

```gdscript
class_name ShadowWaveScheduler
extends RefCounted

const MIRROR_LAYER_BIT: int = 1 << 19

var staggered_enabled: bool = true
var max_active_local_shadows: int = 2
var hysteresis_distance: float = 1.5
var shadow_fade_speed: float = 6.0
var reflection_stride: int = 3

var local_lights: Array[Light3D] = []
var active_shadow_ids: Dictionary = {}
var reflection_viewport: SubViewport
var reflection_camera: Camera3D
var mirror_mesh: MeshInstance3D
var plane_y: float = 0.0

var tick_count: int = 0
var reflection_updates: int = 0
var last_cam_pos: Vector3 = Vector3(1e9, 1e9, 1e9)
var last_cam_fwd: Vector3 = Vector3(0.0, 0.0, -1.0)
var _pause_sync: Node


class _PauseReflectionSync extends Node:
	var owner_ref: ShadowWaveScheduler

	func _process(_delta: float) -> void:
		if owner_ref == null or not get_tree().paused:
			return
		var cam := get_viewport().get_camera_3d()
		if cam != null:
			owner_ref.sync_reflection_immediate(cam)


func register_local_light(light: Light3D) -> void:
	if light == null or local_lights.has(light):
		return
	light.shadow_enabled = false
	light.shadow_opacity = 0.0
	local_lights.append(light)


func setup_reflection_basin(parent: Node3D, mirror_shader: Shader, size: Vector2, p_plane_y: float = 0.0, res: int = 256) -> MeshInstance3D:
	plane_y = p_plane_y
	var clamped_res: int = clampi(res, 128, 512)
	reflection_viewport = SubViewport.new()
	reflection_viewport.name = "StaggeredReflectionVP"
	reflection_viewport.size = Vector2i(clamped_res, clamped_res)
	reflection_viewport.msaa_3d = Viewport.MSAA_DISABLED
	reflection_viewport.render_target_clear_mode = SubViewport.CLEAR_MODE_ALWAYS
	reflection_viewport.render_target_update_mode = SubViewport.UPDATE_ONCE
	parent.add_child(reflection_viewport)

	reflection_camera = Camera3D.new()
	reflection_camera.name = "StaggeredReflectionCam"
	reflection_camera.cull_mask = 0xFFFFF & (~MIRROR_LAYER_BIT)
	reflection_viewport.add_child(reflection_camera)

	var plane := PlaneMesh.new()
	plane.size = size
	var mat := ShaderMaterial.new()
	mat.shader = mirror_shader
	mat.set_shader_parameter("mirror_tex", reflection_viewport.get_texture())

	mirror_mesh = MeshInstance3D.new()
	mirror_mesh.name = "ReflectionBasin"
	mirror_mesh.mesh = plane
	mirror_mesh.material_override = mat
	mirror_mesh.position = Vector3(0.0, plane_y, 0.0)
	mirror_mesh.layers = MIRROR_LAYER_BIT
	mirror_mesh.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
	parent.add_child(mirror_mesh)

	var sync_node := _PauseReflectionSync.new()
	sync_node.name = "PauseReflectionSync"
	sync_node.process_mode = Node.PROCESS_MODE_ALWAYS
	sync_node.owner_ref = self
	parent.add_child(sync_node)
	_pause_sync = sync_node
	return mirror_mesh


func set_staggered(enabled: bool) -> void:
	staggered_enabled = enabled


func sync_reflection_immediate(main_cam: Camera3D) -> void:
	if reflection_viewport == null or reflection_camera == null or main_cam == null:
		return
	var cam_pos := main_cam.global_position
	var cam_fwd := -main_cam.global_transform.basis.z
	var refl_pos := Vector3(cam_pos.x, 2.0 * plane_y - cam_pos.y, cam_pos.z)
	var refl_target := refl_pos + Vector3(cam_fwd.x, -cam_fwd.y, cam_fwd.z)
	reflection_camera.fov = main_cam.fov
	reflection_camera.near = main_cam.near
	reflection_camera.far = main_cam.far
	reflection_camera.global_position = refl_pos
	reflection_camera.look_at(refl_target, Vector3.UP)
	reflection_viewport.render_target_update_mode = SubViewport.UPDATE_ONCE
	last_cam_pos = cam_pos
	last_cam_fwd = cam_fwd


func compute_active_shadow_indices(cam_pos: Vector3) -> Array[int]:
	if not staggered_enabled:
		var all_idx: Array[int] = []
		for i in range(local_lights.size()):
			all_idx.append(i)
		return all_idx

	var scored: Array = []
	for i in range(local_lights.size()):
		var light := local_lights[i]
		var dist: float = cam_pos.distance_to(light.global_position)
		var score: float = dist - (hysteresis_distance if active_shadow_ids.has(i) else 0.0)
		scored.append({"idx": i, "score": score})

	scored.sort_custom(func(a: Dictionary, b: Dictionary) -> bool: return float(a["score"]) < float(b["score"]))
	var limit: int = mini(max_active_local_shadows, scored.size())
	var chosen: Array[int] = []
	for k in range(limit):
		chosen.append(int(scored[k]["idx"]))
	return chosen


func tick(main_cam: Camera3D, delta: float) -> Dictionary:
	tick_count += 1
	var cam_pos := main_cam.global_position if main_cam != null else Vector3.ZERO
	var cam_fwd := (-main_cam.global_transform.basis.z) if main_cam != null else Vector3(0.0, 0.0, -1.0)

	var chosen := compute_active_shadow_indices(cam_pos)
	var next_active: Dictionary = {}
	for idx in chosen:
		next_active[idx] = true
	active_shadow_ids = next_active

	var active_count: int = 0
	for i in range(local_lights.size()):
		var light := local_lights[i]
		var want: bool = active_shadow_ids.has(i)
		var target_opacity: float = 1.0 if want else 0.0
		var next_opacity: float = move_toward(light.shadow_opacity, target_opacity, delta * shadow_fade_speed)
		if tick_count == 1:
			next_opacity = target_opacity
		light.shadow_opacity = next_opacity
		light.shadow_enabled = next_opacity > 0.02
		if light.shadow_enabled:
			active_count += 1

	var refl_updated: bool = false
	if reflection_viewport != null and reflection_camera != null and main_cam != null:
		var camera_snapped: bool = cam_pos.distance_squared_to(last_cam_pos) > 4.0 or cam_fwd.dot(last_cam_fwd) < 0.94
		var stride: int = maxi(1, reflection_stride) if staggered_enabled else 1
		var should_update: bool = (tick_count == 1) or camera_snapped or ((tick_count - 1) % stride == 0)
		if should_update:
			sync_reflection_immediate(main_cam)
			reflection_updates += 1
			refl_updated = true

	return {
		"tick": tick_count,
		"active_local_shadows": active_count,
		"reflection_updated": refl_updated,
		"reflection_updates": reflection_updates,
		"staggered_enabled": staggered_enabled,
	}
```

### 2. Reflecting Basin Shader (`Assets/Game/Shaders/basin_mirror.gdshader`)

```glsl
shader_type spatial;
render_mode unshaded, cull_back;

uniform sampler2D mirror_tex : filter_linear, repeat_disable;
uniform vec3 water_tint = vec3(0.08, 0.14, 0.22);
uniform float reflectivity = 0.82;
uniform float ripple_strength = 0.004;

void fragment() {
	vec2 screen_uv = vec2(SCREEN_UV.x, 1.0 - SCREEN_UV.y);
	float wave = sin(UV.x * 26.0 + TIME * 1.8) * cos(UV.y * 22.0 - TIME * 1.4);
	vec2 sample_uv = clamp(screen_uv + vec2(wave, wave * 0.7) * ripple_strength, vec2(0.005), vec2(0.995));
	vec3 refl = textureLod(mirror_tex, sample_uv, 0.0).rgb;
	float fresnel = pow(1.0 - clamp(dot(normalize(NORMAL), normalize(VIEW)), 0.0, 1.0), 2.0);
	float mix_amt = clamp(reflectivity * (0.58 + 0.42 * fresnel), 0.35, 0.94);
	ALBEDO = mix(water_tint, refl, mix_amt);
}
```

## Performance, Browser & Software-Renderer Budgets

- **WebGL 2 OmniLight3D shadow cap**: Each shadow-casting `OmniLight3D` renders 6 cubemap faces in Compatibility mode. Capping active casters to `2` saves `24+` extra scene render passes per frame in a 6-lantern courtyard.
- **Tight hero directional shadow range**: Use `DirectionalLight3D.SHADOW_PARALLEL_2_SPLITS` with `directional_shadow_max_distance <= 36.0` instead of `4` splits across `150 m` so shadow texels stay crisp without blowing atlas resolution.
- **Disable MSAA on reflection `SubViewport`s**: Set `reflection_viewport.msaa_3d = Viewport.MSAA_DISABLED` and keep resolution at `256×256` with `UPDATE_ONCE` stride `3`.

## Integration & Verification Checklist

1. Register all secondary local lights via `scheduler.register_local_light(light)` and call `scheduler.tick(camera, delta)` once per `_process`.
2. Unit-test `ShadowWaveScheduler` to verify strict `max_active_local_shadows` enforcement and zero boundary flicker inside `hysteresis_distance`.
3. Capture overview and close angles to verify both crisp time-sliced basin reflections and warm lantern lighting without stale frames.

## Official references

- SIGGRAPH 2026 — Advances in Real-Time Rendering & Adaptive Shadow Scheduling
- Godot 4.7 Compatibility Shadow Atlas & SubViewport.UPDATE_ONCE Reference
- Real-Time Rendering (4th Ed.) — Shadow Map Partitioning & Budgeted Updates
