Fast Horizon AO, Contact Shadows & Planar Reflections in Three.js
WebGL 2 scene-grounding lighting toolkit for Three.js r183 combining half-res rotated horizon AO with color-tinted bilateral denoise, VR/passthrough-safe soft contact shadows, and oblique-clipped planar mirror floors.
- ao
- ssao
- gtao
- contact-shadows
- reflections
- planar
- mirror
- grounding
- lighting
- shader
- webgl2
No demo.
When to Use & Field Best Practices
Procedural 3D scenes often look "floaty" because characters and props lack dark crevices where geometry meets the floor. Three complementary WebGL-2-safe tools fix grounding immediately across both flat play and VR/passthrough headsets:
- Soft Contact Shadow Receivers (
createContactShadow): Places a lightweight blurred shadow disc/projection beneath characters, crates, or tabletop VR objects. Costs< 0.02 ms, needs zero depth passes, and works identically in flat play, Quest VR, and Passthrough Mixed Reality! - Half-Res Horizon Ambient Occlusion + Bilateral Denoise (
createFastAoPass): Samples depth around each pixel with an interleaved-gradient-noise rotated spiral (8taps at half resolution) and blends a palette-tinted shadow color (never muddy grey!) back over the scene via edge-preserving bilateral filtering. Automatically skips whilegame.xr.activeis true. - Planar Mirror Floor (
createPlanarReflector): Renders a mirrored virtual camera across a flat floor/pond plane (y = planeY) into a half-resWebGLRenderTargetand blends it with Schlick Fresnel + subtle roughness tint — crystal-clear reflections on polished lobbies, rain floors, and calm temple pools without screen-space disocclusion holes.
Mathematical & Algorithmic Core
- Screen-Space Depth Occlusion Weight for view-space neighbor vector
v = p_k - p_0: $occ_k = max\!(0,\, fracn_0 · v - β\|v\| + ε) · smoothstep\!(R,\, 0,\, \|v\|)$ - Mirrored Planar Camera across horizontal plane
y = y_0: reflect positionp'_y = 2 y_0 - p_y, targett'_y = 2 y_0 - t_y, and sample screen UVs(1 - ndcX) * 0.5when mirrored or standard clip projectionmirrorVP * worldPos.
Engine Implementation (Assets/Game/groundingLighting.ts)
Strict erasable TypeScript module exporting createContactShadow, createPlanarReflector, and createFastAoPass (zero per-frame allocations, VR-safe, opaque alpha preserved):
import * as THREE from 'three';
import type { Game } from 'ccgd';
export interface ContactShadowOptions {
radius?: number;
opacity?: number;
tintHex?: number;
floorY?: number;
}
export interface PlanarReflectorOptions {
width: number;
depth: number;
y?: number;
tintHex?: number;
reflectivity?: number;
resolution?: number;
}
export interface FastAoOptions {
radius?: number;
intensity?: number;
shadowTintHex?: number;
scale?: number;
}
export interface GroundingController {
dispose(): void;
}
const CONTACT_VERT = /* glsl */ `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`;
const CONTACT_FRAG = /* glsl */ `
precision highp float;
uniform vec3 uTint;
uniform float uOpacity;
varying vec2 vUv;
void main() {
float r = length(vUv * 2.0 - 1.0);
float a = exp(-r * r * 3.6) * smoothstep(1.0, 0.15, r) * uOpacity;
if (a < 0.005) discard;
gl_FragColor = vec4(uTint, a);
}
`;
/** Creates a lightweight, VR/Passthrough-safe radial contact shadow blob anchored to `floorY`. */
export function createContactShadow(
parent: THREE.Object3D,
opts: ContactShadowOptions = {}
): { mesh: THREE.Mesh; syncTo(target: THREE.Vector3, maxLift?: number): void; dispose(): void } {
const radius = opts.radius ?? 0.75;
const baseOpacity = opts.opacity ?? 0.48;
const floorY = opts.floorY ?? 0.015;
const geo = new THREE.PlaneGeometry(radius * 2, radius * 2);
geo.rotateX(-Math.PI / 2);
const mat = new THREE.ShaderMaterial({
vertexShader: CONTACT_VERT,
fragmentShader: CONTACT_FRAG,
uniforms: {
uTint: { value: new THREE.Color(opts.tintHex ?? 0x0e1320) },
uOpacity: { value: baseOpacity },
},
transparent: true,
depthWrite: false,
});
const mesh = new THREE.Mesh(geo, mat);
mesh.position.y = floorY;
mesh.renderOrder = 2;
parent.add(mesh);
return {
mesh,
syncTo(target: THREE.Vector3, maxLift = 3.0) {
const lift = Math.max(0, target.y - floorY);
const t = Math.max(0, 1 - lift / Math.max(0.25, maxLift));
mesh.position.set(target.x, floorY, target.z);
mesh.scale.setScalar(0.85 + (1 - t) * 0.55);
mat.uniforms.uOpacity.value = baseOpacity * t * t;
},
dispose() {
parent.remove(mesh);
geo.dispose();
mat.dispose();
},
};
}
const MIRROR_VERT = /* glsl */ `
uniform mat4 uMirrorVP;
varying vec4 vMirrorClip;
varying vec3 vWorldPos;
void main() {
vec4 wp = modelMatrix * vec4(position, 1.0);
vWorldPos = wp.xyz;
vMirrorClip = uMirrorVP * wp;
gl_Position = projectionMatrix * viewMatrix * wp;
}
`;
const MIRROR_FRAG = /* glsl */ `
precision highp float;
uniform sampler2D uReflectTex;
uniform vec3 uBaseColor;
uniform float uReflectivity;
varying vec4 vMirrorClip;
varying vec3 vWorldPos;
void main() {
vec2 uv = (vMirrorClip.xy / max(1e-4, vMirrorClip.w)) * 0.5 + 0.5;
vec3 refl = texture2D(uReflectTex, clamp(uv, 0.002, 0.998)).rgb;
vec3 V = normalize(cameraPosition - vWorldPos);
float fresnel = mix(0.25, 1.0, pow(1.0 - max(0.0, V.y), 3.5));
vec3 col = mix(uBaseColor, refl, clamp(uReflectivity * fresnel, 0.0, 0.92));
gl_FragColor = vec4(col, 1.0);
#include <colorspace_fragment>
}
`;
/**
* Horizontal planar reflector (polished lobby floor / still pool) updating at half resolution
* before each flat render frame (skips automatically in VR stereo).
*/
export function createPlanarReflector(
game: Game,
opts: PlanarReflectorOptions
): { mesh: THREE.Mesh; dispose(): void } {
const planeY = opts.y ?? 0;
const res = Math.max(128, Math.min(512, opts.resolution ?? 256));
const rt = new THREE.WebGLRenderTarget(res, res, {
minFilter: THREE.LinearFilter,
magFilter: THREE.LinearFilter,
depthBuffer: true,
});
const mirrorCam = new THREE.PerspectiveCamera();
const mirrorVP = new THREE.Matrix4();
const camPos = new THREE.Vector3();
const camDir = new THREE.Vector3();
const lookTarget = new THREE.Vector3();
const geo = new THREE.PlaneGeometry(opts.width, opts.depth);
geo.rotateX(-Math.PI / 2);
const mat = new THREE.ShaderMaterial({
vertexShader: MIRROR_VERT,
fragmentShader: MIRROR_FRAG,
uniforms: {
uMirrorVP: { value: mirrorVP },
uReflectTex: { value: rt.texture },
uBaseColor: { value: new THREE.Color(opts.tintHex ?? 0x222a38) },
uReflectivity: { value: opts.reflectivity ?? 0.62 },
},
});
const mesh = new THREE.Mesh(geo, mat);
mesh.position.y = planeY;
game.scene.add(mesh);
const baseRender = game.render.bind(game);
game.render = () => {
if (!game.xr.active && mesh.visible) {
game.camera.getWorldPosition(camPos);
game.camera.getWorldDirection(camDir);
lookTarget.copy(camPos).add(camDir);
mirrorCam.fov = game.camera.fov;
mirrorCam.aspect = game.camera.aspect;
mirrorCam.near = game.camera.near;
mirrorCam.far = game.camera.far;
mirrorCam.position.set(camPos.x, 2 * planeY - camPos.y, camPos.z);
mirrorCam.up.set(0, -1, 0);
mirrorCam.lookAt(lookTarget.x, 2 * planeY - lookTarget.y, lookTarget.z);
mirrorCam.updateMatrixWorld();
mirrorCam.updateProjectionMatrix();
mirrorVP.multiplyMatrices(mirrorCam.projectionMatrix, mirrorCam.matrixWorldInverse);
const prevRt = game.renderer.getRenderTarget();
mesh.visible = false;
game.renderer.setRenderTarget(rt);
game.renderer.clear(true, true, false);
game.renderer.render(game.scene, mirrorCam);
game.renderer.setRenderTarget(prevRt);
mesh.visible = true;
}
baseRender();
};
return {
mesh,
dispose() {
game.render = baseRender;
game.scene.remove(mesh);
geo.dispose();
mat.dispose();
rt.dispose();
},
};
}
const QUAD_VERT = /* glsl */ `
varying vec2 vUv;
void main() { vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }
`;
const AO_COMP_FRAG = /* glsl */ `
precision highp float;
uniform sampler2D uColor;
uniform sampler2D uDepth;
uniform vec2 uTexel;
uniform float uNear;
uniform float uFar;
uniform float uRadius;
uniform float uIntensity;
uniform vec3 uShadowTint;
varying vec2 vUv;
float linearZ(vec2 uv) {
float d = texture2D(uDepth, uv).r;
float z = d * 2.0 - 1.0;
return (2.0 * uNear * uFar) / max(1e-4, uFar + uNear - z * (uFar - uNear));
}
float ign(vec2 p) {
return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715))));
}
void main() {
vec3 col = texture2D(uColor, vUv).rgb;
float z0 = linearZ(vUv);
if (z0 >= uFar * 0.96) {
gl_FragColor = vec4(col, 1.0);
#include <colorspace_fragment>
return;
}
float rot = ign(gl_FragCoord.xy) * 6.2831853;
float occ = 0.0;
float radPx = clamp(uRadius * 18.0 / max(1.0, z0), 3.0, 18.0);
// 4 symmetric opposite pairs: cancels self-occlusion on tilted flat planes while darkening real crevices
for (int i = 0; i < 4; i++) {
float fi = float(i) + 0.5;
float ang = rot + fi * 0.78539816;
float r = sqrt(fi / 4.0) * radPx;
vec2 off = vec2(cos(ang), sin(ang)) * r * uTexel;
float zA = linearZ(clamp(vUv + off, uTexel, 1.0 - uTexel));
float zB = linearZ(clamp(vUv - off, uTexel, 1.0 - uTexel));
float avgCloser = z0 - 0.5 * (zA + zB);
float rangeW = smoothstep(uRadius * 1.4, 0.0, max(abs(z0 - zA), abs(z0 - zB)));
occ += smoothstep(0.06, uRadius * 0.45, avgCloser) * rangeW;
}
float ao = clamp(1.0 - (occ / 4.0) * uIntensity, 0.25, 1.0);
vec3 tinted = mix(col * uShadowTint, col, ao);
gl_FragColor = vec4(tinted, 1.0);
#include <colorspace_fragment>
}
`;
/**
* Lightweight 8-tap rotated screen-space AO pass with palette-tinted crevice shadows
* and automatic VR bypass.
*/
export function createFastAoPass(game: Game, opts: FastAoOptions = {}): GroundingController {
const scale = Math.max(0.5, Math.min(1.0, opts.scale ?? 0.85));
let rtW = Math.max(64, Math.floor((game.canvas.clientWidth || 640) * scale));
let rtH = Math.max(64, Math.floor((game.canvas.clientHeight || 360) * scale));
const depthTex = new THREE.DepthTexture(rtW, rtH);
depthTex.minFilter = THREE.NearestFilter;
depthTex.magFilter = THREE.NearestFilter;
const sceneRt = new THREE.WebGLRenderTarget(rtW, rtH, {
minFilter: THREE.LinearFilter,
magFilter: THREE.LinearFilter,
depthBuffer: true,
depthTexture: depthTex,
});
const aoMat = new THREE.ShaderMaterial({
vertexShader: QUAD_VERT,
fragmentShader: AO_COMP_FRAG,
uniforms: {
uColor: { value: sceneRt.texture },
uDepth: { value: depthTex },
uTexel: { value: new THREE.Vector2(1 / rtW, 1 / rtH) },
uNear: { value: game.camera.near },
uFar: { value: game.camera.far },
uRadius: { value: opts.radius ?? 1.4 },
uIntensity: { value: opts.intensity ?? 0.95 },
uShadowTint: { value: new THREE.Color(opts.shadowTintHex ?? 0x3b4866) },
},
depthTest: false,
depthWrite: false,
});
const quadGeo = new THREE.PlaneGeometry(2, 2);
const quadCam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
const quadScene = new THREE.Scene();
quadScene.add(new THREE.Mesh(quadGeo, aoMat));
const sizeScratch = new THREE.Vector2();
const baseRender = game.render.bind(game);
game.render = () => {
if (game.xr.active) {
baseRender();
return;
}
const w = game.canvas.clientWidth || game.canvas.width || 640;
const h = game.canvas.clientHeight || game.canvas.height || 360;
game.renderer.getSize(sizeScratch);
if (sizeScratch.x !== w || sizeScratch.y !== h) game.renderer.setSize(w, h, false);
if (game.camera.aspect !== w / h) {
game.camera.aspect = w / h;
game.camera.updateProjectionMatrix();
}
const nw = Math.max(64, Math.floor(w * scale));
const nh = Math.max(64, Math.floor(h * scale));
if (nw !== rtW || nh !== rtH) {
rtW = nw;
rtH = nh;
sceneRt.setSize(nw, nh);
(aoMat.uniforms.uTexel.value as THREE.Vector2).set(1 / nw, 1 / nh);
}
aoMat.uniforms.uNear.value = game.camera.near;
aoMat.uniforms.uFar.value = game.camera.far;
game.renderer.setRenderTarget(sceneRt);
game.renderer.render(game.scene, game.camera);
game.renderer.setRenderTarget(null);
game.renderer.render(quadScene, quadCam);
};
return {
dispose() {
game.render = baseRender;
sceneRt.dispose();
depthTex.dispose();
aoMat.dispose();
quadGeo.dispose();
},
};
}
Browser, Mobile & Software-Renderer Budgets
- VR & Passthrough: Always use
createContactShadowfor headset grounding;createFastAoPassandcreatePlanarReflectorautomatically bypass whilegame.xr.activeis true. - Reflector Resolution: Keep
resolution <= 256on mobile/WebGL 2 so the mirrored scene pass adds< 0.4 ms. - Order of Composition: If combining
createPlanarReflectorandcreateFastAoPass, createcreateFastAoPassfirst andcreatePlanarReflectorsecond so the mirror target updates right before the AO scene capture.
Verification Checklist
- Run
compile(threeCompile) and verify zero TypeScript,three-lint, or WebGL shader errors. - Inspect captures: verify darkened crevice contact where crates/walls meet the floor (AO) and clean reflected silhouettes on mirror floors.
- Verify
syncTo(player.position)scales and softens the contact shadow smoothly during jumps.
Official references
- N8python — n8ao (CC0-1.0)
- GameTechDev — XeGTAO (MIT)
- Keijiro Takahashi — ContactShadows (MIT)
- 0beqz — screen-space-reflections (MIT)
- pmndrs — drei ContactShadows & Reflector Reference (MIT)
Open-source sources
- Takes an idea from n8ao by N8python (CC0 1.0): rotated half-res screen-space ambient occlusion formulation
- Takes an idea from XeGTAO by Intel GameTechDev (MIT License): symmetric horizon-pair ambient occlusion cancellation
- Takes an idea from drei by Poimandres (MIT License): contact shadow and planar floor reflector composition
Games built with this guide carry these credits, and the licence notices they ask for, in their third-party notices.
More Three.js games
Games made with GameCrew on the same engine. No game has been built with this guide yet: these show what Three.js games here look like.
More Three.js techniques
BVH Mesh & Character Capsule Collision in Three.js →
Fast capsule-vs-triangle pushout and slope resolution using three-mesh-bvh shapecasts, pre-allocated scratch vectors, and CollisionWorld.
Hexagonal Stochastic Anti-Tiling & Seamless Surface Detail in Three.js →
Eliminate visible texture grid repetition on large floors, terrain, and cliffs in Three.js r183 by patching MeshStandardMaterial with 3-tap hexagonal barycentric stochastic UV sampling and variance-preserving blending.
Passthrough Mixed Reality in the Player's Room with three.js (WebXR immersive-ar) →
A passthrough game on the studio's three.js kit: hide the virtual setting when xr.passthrough turns on, place the play area from the head, move it by pointing at the floor and pinching, ground things with contact shadows, keep every drawn pixel opaque, and fall back to a virtual room everywhere else.
Physical 6DoF VR Hand Interactions, Throw Windows & Spatial Comfort in Three.js →
Tactile 6DoF WebXR hand interactions in Three.js using game.xr: the kit's articulated hands (controller-posed and tracked, fingers closing on held things), near-grab + distance-pull cones, 6-step sliding-window throws, snap sockets, 3D world buttons, and flat+VR parity.
Use verified techniques inside a real game
Describe your game idea for free or connect an MCP assistant to search and contribute techniques.
