Lighting, Shadows & Post-Processing
Classic Lighting
Material::Lit surfaces under LightingModel::Classic (default) evaluate Lambert diffuse and Blinn-Phong specular in encoded colour space:
colour * (ambient + sum(light * falloff * shadow * max(N·L, 0)))
+ sum(light * falloff * shadow * specular * max(N·H, 0)^shininess)
+ emissive- Falloff — Point and spot lights use
(1 - (d / range)^2)^2, reaching zero atrange. Spot lights multiply by a smoothstep between outer and inner half-angle cosines. Directional and ambient lights have no falloff. - Limits — Up to
MAX_LIGHTS(16) primary directional, point, and spot lights per camera (ambient lights sum separately). Directional lights take priority, then brightest/largest-range lights (LightSet::droppedcounts overflow). - Clustered local lights — Up to
MAX_CLUSTERED_LIGHTS(1024) additional non-shadow-casting local lights bin into a16 × 9 × 16screen-tile/depth grid (LightSet::clustered), so dense torch-lit scenes evaluate only the lights reaching each pixel. - Normal maps — Lit sprites and tangent-bearing meshes sample tangent-space normal maps (+Y up / along bitangent; sprite flips mirror normals).
Physically Based Lighting (PBR)
Setting Camera::lighting = LightingModel::Pbr shades lit surfaces with Burley diffuse and GGX specular in photometric units (shaders/stage_pbr.slang), matching Bevy's StandardMaterial conventions:
- Material parameters —
MeshMaterialprovides perceptualroughness(default0.5),metallic(0.0), andreflectance(0.5). Sprites and tilemaps shade as fully rough dielectrics (reflectance = 0.5). - BRDF —
F0 = mix(0.16 * reflectance^2, base, metallic),alpha = clamp(roughness, 0.089, 1)^2, Burley diffuse, GGXDwith correlated Smith visibility, Schlick Fresnel, and multiscatter compensation via polynomialF_ab. - Light units — Point and spot intensities are in lumens (
÷ 4πto candela), directional in lux, withwindow^2 / max(d^2, 0.0001)falloff and optional spherical area radius (Light::radius, Karis representative point). - Exposure & linear light —
Camera::exposure_ev100(default9.7) scales direct, ambient, and emissive radiance by2^-ev100 / 1.2. UseDynamic::Hdron PBR cameras so lighting and blending run in linear RGBA16F before final sRGB encoding.
Shadows
Lights with cast_shadow render reverse-Z depth tiles into a transient shadow atlas (up to MAX_SHADOW_TILES = 16 tiles per camera, default 512×512 texels) when at least one visible lit surface receives shadows and a caster lies within reach:
- Directional — One orthographic tile fitted to the camera frustum's bounding sphere (capped by
rangeif positive), snapped in whole texels to eliminate shimmer. - Spot — One perspective tile covering the cone.
- Point — Six cube-face tiles; the fragment shader selects the dominant offset axis.
Filtered Shadows
Light::with_filtered_shadows(depth_bias, normal_bias) (e.g. 0.08, 0.6) and with_shadow_size(texels) (up to 2048) enable world-space normal/depth biasing and Gaussian PCF filtering: Castano's 9-tap hardware comparison filter (4×4 footprint) for directional and spot lights, and an 8-tap orthonormal-basis filter for point lights.
HDR Post-Processing
An Sdr camera draws straight into its target with zero float textures or post passes (StageRenderer::post_report reports zeros). Setting Camera::dynamic = Dynamic::Hdr renders into a linear RGBA16F texture (decoding sRGB textures/tints to linear before lighting and blending) and runs an ordered PostChain:
Exposure(multiplier)BloomTonemap—Clamp,Reinhard,Aces(Narkowicz fit, default), orFilmic(the engine's highlight-rolling filmic curve)Grade— Lift, gamma, gain, and saturation in linear spaceCustomsteps anywhere in the chain
Adjacent built-ins fuse into one composite pass. A trailing custom step followed only by exposure/tonemap/grade also fuses into the final composite (postFragmentFused), eliminating an intermediate float texture and pass.
Bloom
Bloom::default()— Fast tight blur: half-size first level, 2×2 box downsamples, 4-tap additive upsamples.Bloom::natural()— Resolution-independent physically motivated bloom (Jimenez 2014):Height(512)first level, 13-tap Karis-weighted downsample, 3×3 tent upsample, curved level weights, and energy-conserving blend (intensity = 0.15).
Temporal Anti-Aliasing & Upscaling
Camera::temporal(Temporal { feedback }) — Applies an 8-sample Halton(2, 3)sub-pixel projection jitter and resolves against depth-reprojected YCoCg-clamped history (postTemporal) using alternating per-camera float histories.- Temporal upscaling — Combining
temporalwithrender_scale < 1.0resolves and upscales in one pass (postTemporalUpscale), accumulating sub-pixel detail across frames.
Native MetalFX & Ray-Traced Shadows (macOS)
- MetalFX (
metalfxfeature) —StageRenderer::set_metalfx(true)routes temporal upscaling through Apple's MetalFX temporal scaler via a graph native node when supported by the GPU (falling back to the stage's own resolve otherwise). - Ray-traced shadows (
ray-tracingfeature) —StageRenderer::set_ray_traced_shadows(Some(strength))traces sun occlusion for static meshes on HDR perspective cameras viaengine_render::ray_tracing, respecting alpha-tested and alpha-blended casters.
Custom Materials & Post Steps
Custom Surface Materials (shaders/stage_material.slang)
Implement struct CustomMaterial : IStageMaterial with MaterialOutput evaluate(MaterialInput):
MaterialInputprovidesworld,normal,tangent,uv,colour,view,time,frontFacing,emissive, plus helpersparam(i),sampleColour(slot, uv),sampleData(slot, uv),scene,worldNormal, anddefaultOutput.MaterialOutputreturnscolour,alpha,emissive, world-spacenormal,specular, andshininess.- Register with
StageRenderer::register_material(up to 4 textures, 8 float4 param rows) orregister_wide_material(up to 8 textures, 128 param rows). SetMaterialDesc::litto join the stage's lighting and shadow loop (shaders/stage_light.slang). - Create instances with
Stage::create_material_instance, configure viaset_material_params/set_material_texture, and attach toSprite::customorMeshMaterial::custom.
Custom Post Steps (shaders/stage_post_custom.slang)
Implement struct CustomPost : IStagePost with float4 evaluate(PostInput) (uv, pixel, size, colour, time, param(i), sampleSource(uv), sampleExtra(slot, uv), and sampleDepth(pixel) when PostDesc::depth is enabled). Register with register_post (up to 128 param rows and 4 extra textures) and add PostEffect::Custom(...) to a camera's PostChain.
Building Host Shaders
Compile host .slang materials and post steps into Rust modules and Metal/WGSL shader payloads with build/stage-materials.ts:
bun build/stage-materials.ts \
--out build/stage-shaders \
--material shaders/water.slang \
--post shaders/fade.slang \
[--ios] [--web]Include the generated .rs file in the host crate (include!(concat!(env!("STAGE_SHADERS"), "/water.rs"))) and pass the generated shader descriptor to MaterialDesc or PostDesc. Passing --ios embeds cfg-selected metal/, metal-iphonesimulator/, and metal-iphoneos/ libraries automatically.