Packed Slope/Normal Flat-Panel Volumetric Clouds in Three.js (WebGL 2)
Render volumetric-looking backlit clouds in ~0.2 ms on mobile, VR headsets, and WebGL 2 without raymarching by baking a tileable RGBA8 density/slope/thickness atlas and evaluating Beer-Powder transmittance and Henyey-Greenstein silver lining analytically across curved parallax canopy layers.
- clouds
- volumetric
- flat-panel
- slope-normal
- atmosphere
- sky
- mobile
- quest
- silver-lining
- shader
- webgl2
- optimization
No demo.
When to Use (and When Not To)
Full 3D raymarched cloud domes look rich on desktop GPUs, but 24–64 per-pixel raymarch steps quickly blow frame budgets on phones, standalone VR headsets, and software WebGL renderers. Packed Slope/Normal Flat-Panel Volumetric Clouds replace per-pixel raymarching with a constant-time 2-fetch fragment pass over 2–3 gently curved parallax sky layers:
- Use this technique when the player stays below (or views from a lookout toward) the cloud deck and you need rich golden-hour billows, sunlit tops, cool shaded undersides, and bright forward-scattered silver lining under a strict
< 0.5 msmobile/WebXR budget. - Skip this technique when the player flies *through* thick 3D cloud canyons at eye level — use a full 3D raymarched or baked volume cloud sea instead.
Mathematical & Algorithmic Core
- Tileable 4-Channel Packed Cloud Atlas (
RGBA8, linearTHREE.NoColorSpace):
- Synthesize periodic tileable multi-octave value noise blended with periodic Worley billow domes (
u, vwrapped on an integer lattice so0meets1seamlessly). - Compute central finite-difference slopes
∂ h/∂ uand∂ h/∂ vtoroidally and normalize into a pseudo-3D billow normalN = normalize(-s_u, 1, -s_v). - Pack into one
256×256RGBA8DataTexture: R: multi-octave billow coverage / densityrho ∈ [0, 1]G: X-slope normalN_x · 0.5 + 0.5B: Z-slope normalN_z · 0.5 + 0.5A: vertical optical dome thicknessτ ∈ [0, 1]
- Counter-Drifting Dual-Octave Fetch:
- Sample the atlas twice per layer at different UV scales and wind vectors to break repeating tile scroll while keeping texture bandwidth fixed at 2 bilinear taps per layer.
- Analytic Volumetric Illumination:
- Beer–Powder Transmittance:
T = e^-τ σ·(0.65 + 0.75(1 - e^-3.1τ)), modulated by wrapped directional slope lightingN·L_sunso cloud puffs brighten on their sun-facing flanks and darken on their leeward sides. - Dual-Lobe Henyey–Greenstein Silver Lining: $
P(θ) = mix\!(P_HG(cosθ, g_1),\, P_HG(cosθ, g_2),\, 0.28), g_1 = 0.68,\; g_2 = -0.22$ weighted toward semi-transparent cloud rims so backlit edges glow crisply near the solar disc. - Curved Canopy & Radial Horizon Haze: Gently droop canopy vertices quadratically (
y = -r^2 d) and blend outer rings intouHorizonColorso the cloud deck merges smoothly into sky fog.
Engine Implementation (Assets/Game/flatPanelClouds.ts)
import * as THREE from 'three';
export interface FlatPanelCloudConfig {
/** Tileable packed cloud atlas resolution (power of two, 64..512). */
resolution: number;
/** Deterministic PRNG seed for tileable billow synthesis. */
seed: number;
/** Base cloud sky coverage in [0.15..0.85]. */
coverage: number;
/** Edge feather softness in [0.05..0.45]. */
softness: number;
/** Forward-scattering silver-lining boost around the sun. */
silverLining: number;
/** Number of curved canopy planes stacked for parallax depth (1..4). */
layers: number;
/** Lowest cloud canopy altitude above ground (world units). */
altitudeMin: number;
/** Highest cloud canopy altitude above ground (world units). */
altitudeMax: number;
/** Canopy disc radius (world units). */
radius: number;
/** Wind drift speed in UV units per second. */
windSpeed: number;
}
export interface PackedCloudAtlas {
texture: THREE.DataTexture;
width: number;
height: number;
data: Uint8Array;
}
export interface PackedCloudSample {
density: number;
normalX: number;
normalZ: number;
thickness: number;
}
export interface FlatPanelCloudDeck {
group: THREE.Group;
atlas: PackedCloudAtlas;
layers: THREE.Mesh[];
uniforms: {
uCloudMap: { value: THREE.DataTexture };
uSunDir: { value: THREE.Vector3 };
uSunColor: { value: THREE.Color };
uAmbientTop: { value: THREE.Color };
uShadowBottom: { value: THREE.Color };
uHorizonColor: { value: THREE.Color };
uTime: { value: number };
uCoverage: { value: number };
uSoftness: { value: number };
uSilverLining: { value: number };
uWindSpeed: { value: number };
uRadius: { value: number };
};
setSunDirection: (dir: THREE.Vector3) => void;
setCoverage: (coverage: number) => void;
setPalette: (sunHex: number, ambientTopHex: number, shadowBottomHex: number, horizonHex: number) => void;
update: (dt: number, anchorX?: number, anchorZ?: number) => void;
dispose: () => void;
}
const DEFAULT_CONFIG: FlatPanelCloudConfig = {
resolution: 256,
seed: 202608,
coverage: 0.56,
softness: 0.18,
silverLining: 1.35,
layers: 3,
altitudeMin: 17.5,
altitudeMax: 24.5,
radius: 135,
windSpeed: 0.014,
};
function hash2Periodic(ix: number, iy: number, period: number, seed: number): number {
const x = ((ix % period) + period) % period;
const y = ((iy % period) + period) % period;
let h = (x * 374761393 + y * 668265263 + seed * 1442695041) | 0;
h = Math.imul(h ^ (h >>> 13), 1274126177);
return ((h ^ (h >>> 16)) >>> 0) / 4294967295;
}
function periodicValueNoise(u: number, v: number, period: number, seed: number): number {
const fx = u * period;
const fy = v * period;
const x0 = Math.floor(fx);
const y0 = Math.floor(fy);
const tx = fx - x0;
const ty = fy - y0;
const sx = tx * tx * (3 - 2 * tx);
const sy = ty * ty * (3 - 2 * ty);
const n00 = hash2Periodic(x0, y0, period, seed);
const n10 = hash2Periodic(x0 + 1, y0, period, seed);
const n01 = hash2Periodic(x0, y0 + 1, period, seed);
const n11 = hash2Periodic(x0 + 1, y0 + 1, period, seed);
const nx0 = n00 + (n10 - n00) * sx;
const nx1 = n01 + (n11 - n01) * sx;
return nx0 + (nx1 - nx0) * sy;
}
function periodicWorleyBillow(u: number, v: number, cells: number, seed: number): number {
const fx = u * cells;
const fy = v * cells;
const cx = Math.floor(fx);
const cy = Math.floor(fy);
let minDistSq = 4.0;
for (let dy = -1; dy <= 1; dy++) {
for (let dx = -1; dx <= 1; dx++) {
const gx = cx + dx;
const gy = cy + dy;
const rx = hash2Periodic(gx, gy, cells, seed + 17);
const ry = hash2Periodic(gx, gy, cells, seed + 53);
const px = gx + rx - fx;
const py = gy + ry - fy;
const d2 = px * px + py * py;
if (d2 < minDistSq) minDistSq = d2;
}
}
return Math.max(0, 1.0 - Math.sqrt(minDistSq));
}
/**
* Deterministically bakes a tileable 4-channel cloud map:
* R = billow coverage/density, G = X slope normal, B = Z slope normal, A = vertical dome thickness.
*/
export function bakePackedCloudAtlas(resolution = 256, seed = 202608): PackedCloudAtlas {
const size = Math.max(64, Math.min(512, Math.round(resolution)));
const densityField = new Float32Array(size * size);
const heightField = new Float32Array(size * size);
let minD = 1e9;
let maxD = -1e9;
for (let y = 0; y < size; y++) {
const v = y / size;
for (let x = 0; x < size; x++) {
const u = x / size;
const fbm =
0.50 * periodicValueNoise(u, v, 4, seed + 1) +
0.27 * periodicValueNoise(u, v, 8, seed + 2) +
0.15 * periodicValueNoise(u, v, 16, seed + 3) +
0.08 * periodicValueNoise(u, v, 32, seed + 4);
const billow =
0.65 * periodicWorleyBillow(u, v, 5, seed + 11) +
0.35 * periodicWorleyBillow(u, v, 10, seed + 23);
const d = fbm * 0.62 + billow * 0.38;
const idx = y * size + x;
densityField[idx] = d;
heightField[idx] = Math.pow(Math.max(0, d), 1.35) * 0.72 + billow * 0.28;
if (d < minD) minD = d;
if (d > maxD) maxD = d;
}
}
const span = Math.max(1e-5, maxD - minD);
for (let i = 0; i < densityField.length; i++) {
densityField[i] = (densityField[i] - minD) / span;
}
const data = new Uint8Array(size * size * 4);
const slopeGain = size * 0.19;
for (let y = 0; y < size; y++) {
const ym = (y - 1 + size) % size;
const yp = (y + 1) % size;
for (let x = 0; x < size; x++) {
const xm = (x - 1 + size) % size;
const xp = (x + 1) % size;
const idx = y * size + x;
const d = densityField[idx];
const dhdx = (heightField[y * size + xp] - heightField[y * size + xm]) * slopeGain;
const dhdz = (heightField[yp * size + x] - heightField[ym * size + x]) * slopeGain;
const invLen = 1.0 / Math.hypot(dhdx, 1.0, dhdz);
const nx = -dhdx * invLen;
const nz = -dhdz * invLen;
const thickness = Math.min(1, Math.max(0, heightField[idx] * 1.15));
const p = idx * 4;
data[p] = Math.round(Math.min(1, Math.max(0, d)) * 255);
data[p + 1] = Math.round((nx * 0.5 + 0.5) * 255);
data[p + 2] = Math.round((nz * 0.5 + 0.5) * 255);
data[p + 3] = Math.round(thickness * 255);
}
}
const texture = new THREE.DataTexture(data, size, size, THREE.RGBAFormat);
texture.colorSpace = THREE.NoColorSpace;
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.magFilter = THREE.LinearFilter;
texture.minFilter = THREE.LinearMipmapLinearFilter;
texture.generateMipmaps = true;
texture.needsUpdate = true;
return { texture, width: size, height: size, data };
}
/** Reads a single decoded texel from the packed RGBA8 cloud atlas (useful in unit tests). */
export function evaluatePackedCloudTexel(atlas: PackedCloudAtlas, x: number, y: number): PackedCloudSample {
const ix = ((x % atlas.width) + atlas.width) % atlas.width;
const iy = ((y % atlas.height) + atlas.height) % atlas.height;
const p = (iy * atlas.width + ix) * 4;
return {
density: atlas.data[p] / 255,
normalX: (atlas.data[p + 1] / 255) * 2 - 1,
normalZ: (atlas.data[p + 2] / 255) * 2 - 1,
thickness: atlas.data[p + 3] / 255,
};
}
function buildCurvedCanopyGeometry(radius: number, droop: number, segments = 32): THREE.BufferGeometry {
const geo = new THREE.PlaneGeometry(radius * 2, radius * 2, segments, segments);
geo.rotateX(Math.PI / 2);
const pos = geo.attributes.position as THREE.BufferAttribute;
for (let i = 0; i < pos.count; i++) {
const x = pos.getX(i);
const z = pos.getZ(i);
const r = Math.min(1.0, Math.hypot(x, z) / radius);
pos.setY(i, -r * r * droop);
}
pos.needsUpdate = true;
geo.computeVertexNormals();
return geo;
}
const VERTEX_SHADER = /* glsl */ `
varying vec3 vWorldPos;
varying vec2 vUv;
void main() {
vUv = uv;
vec4 wp = modelMatrix * vec4(position, 1.0);
vWorldPos = wp.xyz;
gl_Position = projectionMatrix * viewMatrix * wp;
}
`;
const FRAGMENT_SHADER = /* glsl */ `
precision highp float;
uniform sampler2D uCloudMap;
uniform vec3 uSunDir;
uniform vec3 uSunColor;
uniform vec3 uAmbientTop;
uniform vec3 uShadowBottom;
uniform vec3 uHorizonColor;
uniform float uTime;
uniform float uCoverage;
uniform float uSoftness;
uniform float uSilverLining;
uniform float uWindSpeed;
uniform float uRadius;
uniform float uLayerT;
uniform float uUvScale;
uniform vec2 uUvOffset;
varying vec3 vWorldPos;
varying vec2 vUv;
float hgPhase(float cosTheta, float g) {
float g2 = g * g;
return (1.0 - g2) / (4.0 * 3.14159265 * pow(max(0.05, 1.0 + g2 - 2.0 * g * cosTheta), 1.5));
}
void main() {
vec2 centered = (vUv - 0.5) * 2.0;
float radial = length(centered);
if (radial > 1.0) discard;
vec2 driftA = vec2(uTime * uWindSpeed, uTime * uWindSpeed * 0.42);
vec2 driftB = vec2(-uTime * uWindSpeed * 0.55, uTime * uWindSpeed * 0.78);
vec2 uvA = vUv * uUvScale + uUvOffset + driftA;
vec2 uvB = vUv * (uUvScale * 2.15) - uUvOffset * 1.3 + driftB;
vec4 baseSample = texture2D(uCloudMap, uvA);
vec4 detailSample = texture2D(uCloudMap, uvB);
float combinedDensity = baseSample.r * 0.78 + detailSample.r * 0.22;
float threshold = 1.0 - clamp(uCoverage - uLayerT * 0.08, 0.12, 0.88);
float alpha = smoothstep(threshold - uSoftness, threshold + uSoftness, combinedDensity);
float horizonFade = 1.0 - smoothstep(0.56, 0.98, radial);
alpha *= horizonFade;
if (alpha < 0.015) discard;
// Reconstruct packed billow normal (flip Y downward for undersides while keeping sun-side rim response)
vec2 slopeXZ = (baseSample.gb * 2.0 - 1.0) * 0.78 + (detailSample.gb * 2.0 - 1.0) * 0.22;
float ny = sqrt(max(0.08, 1.0 - dot(slopeXZ, slopeXZ)));
vec3 billowNormal = normalize(vec3(slopeXZ.x, ny * 0.65, slopeXZ.y));
vec3 sunDir = normalize(uSunDir);
vec3 viewDir = normalize(vWorldPos - cameraPosition);
// Directional slope-normal lighting + Beer-Lambert optical thickness transmittance
float ndl = clamp(dot(billowNormal, sunDir) * 0.62 + 0.38, 0.0, 1.0);
float thickness = mix(baseSample.a, detailSample.a, 0.25) * (0.65 + 0.55 * alpha);
float beer = exp(-thickness * (1.85 - 0.45 * uLayerT));
float powder = 1.0 - exp(-thickness * 3.1);
float directTerm = mix(beer, beer * (0.65 + 0.75 * powder), 0.5) * (0.35 + 0.65 * ndl);
// Dual-lobe Henyey-Greenstein forward-scattering silver lining near the sun
float cosTheta = dot(viewDir, sunDir);
float phase = mix(hgPhase(cosTheta, 0.68), hgPhase(cosTheta, -0.22), 0.28);
float edgeMask = (1.0 - alpha * 0.62) * smoothstep(0.05, 0.45, alpha);
float silver = clamp(phase * 1.45, 0.0, 2.2) * uSilverLining * edgeMask;
// Vertical ambient stratification: warmer lit upper decks, cooler shadowed bases
float heightMix = clamp(uLayerT * 0.55 + baseSample.a * 0.45, 0.0, 1.0);
vec3 ambient = mix(uShadowBottom, uAmbientTop, heightMix);
vec3 lit = ambient + uSunColor * (directTerm * 1.15 + silver * 0.85);
// Blend gently into horizon haze so edges never cut harshly against the sky dome
float haze = smoothstep(0.42, 0.96, radial) * 0.68;
vec3 finalColor = mix(lit, uHorizonColor, haze);
gl_FragColor = vec4(finalColor, alpha * mix(0.86, 0.62, uLayerT));
}
`;
/**
* Builds a multi-layer curved flat-panel cloud deck driven by a packed RGBA8 slope/normal/thickness atlas.
* Zero raymarching loops: runs in constant time (~0.2 ms) on mobile WebGL 2, headsets, and software renderers.
*/
export function createFlatPanelCloudDeck(config?: Partial<FlatPanelCloudConfig>): FlatPanelCloudDeck {
const cfg: FlatPanelCloudConfig = { ...DEFAULT_CONFIG, ...config };
const layerCount = Math.max(1, Math.min(4, Math.round(cfg.layers)));
const atlas = bakePackedCloudAtlas(cfg.resolution, cfg.seed);
const uniforms = {
uCloudMap: { value: atlas.texture },
uSunDir: { value: new THREE.Vector3(0.58, 0.28, 0.76).normalize() },
uSunColor: { value: new THREE.Color(0xffdfa8) },
uAmbientTop: { value: new THREE.Color(0xdce9f7) },
uShadowBottom: { value: new THREE.Color(0x5d6e8c) },
uHorizonColor: { value: new THREE.Color(0xf2c89c) },
uTime: { value: 0 },
uCoverage: { value: cfg.coverage },
uSoftness: { value: cfg.softness },
uSilverLining: { value: cfg.silverLining },
uWindSpeed: { value: cfg.windSpeed },
uRadius: { value: cfg.radius },
};
const group = new THREE.Group();
group.name = 'FlatPanelCloudDeck';
const sharedGeo = buildCurvedCanopyGeometry(cfg.radius, cfg.altitudeMin * 0.52, 28);
const layers: THREE.Mesh[] = [];
const materials: THREE.ShaderMaterial[] = [];
for (let i = 0; i < layerCount; i++) {
const t = layerCount === 1 ? 0.5 : i / (layerCount - 1);
const mat = new THREE.ShaderMaterial({
uniforms: {
...uniforms,
uLayerT: { value: t },
uUvScale: { value: 2.35 + i * 0.55 },
uUvOffset: { value: new THREE.Vector2(i * 0.31, i * 0.19) },
},
vertexShader: VERTEX_SHADER,
fragmentShader: FRAGMENT_SHADER,
transparent: true,
depthWrite: false,
side: THREE.DoubleSide,
});
const mesh = new THREE.Mesh(sharedGeo, mat);
mesh.position.y = cfg.altitudeMin + (cfg.altitudeMax - cfg.altitudeMin) * t;
mesh.renderOrder = 2 + i;
mesh.frustumCulled = false;
group.add(mesh);
layers.push(mesh);
materials.push(mat);
}
return {
group,
atlas,
layers,
uniforms,
setSunDirection(dir: THREE.Vector3) {
uniforms.uSunDir.value.copy(dir).normalize();
},
setCoverage(coverage: number) {
uniforms.uCoverage.value = Math.min(0.88, Math.max(0.12, coverage));
},
setPalette(sunHex: number, ambientTopHex: number, shadowBottomHex: number, horizonHex: number) {
uniforms.uSunColor.value.setHex(sunHex);
uniforms.uAmbientTop.value.setHex(ambientTopHex);
uniforms.uShadowBottom.value.setHex(shadowBottomHex);
uniforms.uHorizonColor.value.setHex(horizonHex);
},
update(dt: number, anchorX = 0, anchorZ = 0) {
uniforms.uTime.value += dt;
group.position.x = anchorX;
group.position.z = anchorZ;
},
dispose() {
sharedGeo.dispose();
atlas.texture.dispose();
for (const m of materials) m.dispose();
},
};
}
Performance, Browser & Software-Renderer Budgets
- Zero raymarching loops: Each layer performs exactly 2
texture2Dfetches and analytic vector math, keeping shader compile time< 20 msand GPU cost~0.2 mseven on mobile GPUs and standalone VR headsets. - Keep
colorSpace = THREE.NoColorSpace: Treating the packed slope/normal atlas as sRGB corrupts the0.5zero-slope midpoint and skews directional highlights. - Layer count budget: Use
3layers on desktop (~24–32vertices per axis) and2layers on low-end mobile/VR tiers (resolution: 128bakes in< 8 mson CPU startup). - No per-frame allocations:
update(dt, anchorX, anchorZ)only updates uniform scalars and group XZ position so the cloud deck follows the camera seamlessly without GC churn.
Integration & Verification Checklist
- Anchor
cloudDeck.update(dt, camera.position.x, camera.position.z)ingame.onUpdateand matchuHorizonColortoscene.fog.colorand your sky dome's horizon tint. - Unit-test
bakePackedCloudAtlasto confirm toroidal wrap continuity (x=0vs.x=width-1), non-trivial slope relief, and clear-sky gaps alongside dense peaks. - Capture horizon and low-angle sky views and inspect the PNGs to verify backlit silver-lining rims near the solar disc and smooth horizon falloff without hard plane cutoffs.
Official references
- Andrew Schneider & Nathan Vos (SIGGRAPH 2015 — Real-Time Volumetric Cloudscapes, Beer-Powder & Dual-Lobe Henyey-Greenstein)
- Graphics Programming Flat-Panel Volumetric Cloud Approximation (2026)
- Three.js r183 DataTexture & ShaderMaterial Reference
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
Mobile-First Adaptive Quality Tiers, Dynamic Resolution Scaling & GPU Watchdog Safety in Three.js →
Keep Three.js r183 browser games smooth and crash-free on mid-range Android and iOS phones via measured 3-tier quality presets with boot-crash auto-step-down, hysteresis dynamic resolution scaling, chunked load-time baking, iOS RGBA16F 65504 NaN clamping, and live pass-isolation profiling.
Isolated-PRNG Seeded Worlds, Procedural Foliage Atlas, Drifting Weather & Canopy Light Shafts in Three.js →
Generate deterministic forests and worlds where each system (terrain, trees, rocks, water, cabins) owns an isolated PRNG stream so edits never shift existing placements, paired with a procedural canvas foliage atlas, drifting 4-state weather, and half-float-safe volumetric canopy light shafts.
Stylized Water, Cel-Shading Ramps & Outlines in Three.js (r183) →
Three.js r183 NearestFilter DataTexture cel-shading ramps, BackSide normal-extruded outlines, and analytical Gerstner wave water ShaderMaterial with cellular foam.
Instanced Wind Foliage, Object-Pooled Particles & Spring Feel in Three.js →
Single-draw-call THREE.InstancedMesh wind foliage with player bend, zero-GC pooled burst particles, and dt-invariant second-order springs that keep 60 Hz steps under 2 ms.
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.
