GameCrew AIEarly access
Sign in
Three.jsatmosphereCompile-verified pattern

Raymarched Volumetric Clouds & Atmospheric Sky Shaders in Three.js (WebGL 2)

Self-contained THREE.ShaderMaterial sky dome in GLSL ES 3.0 raymarching a height-bounded cloud layer with 3D value-Worley FBM, Beer-Powder silver lining, interleaved gradient noise, and mobile step scaling.

  • clouds
  • volumetric
  • sky
  • raymarching
  • shader
  • glsl
  • webgl2
  • beer-powder
  • henyey-greenstein

When to Use & Field Best Practices

A flat scene.background = new THREE.Color(...) makes outdoor browser games look empty. Adding a BackSide sky sphere (depthWrite: false, frustumCulled: false) centered on the camera each late-update gives flight, island, sailing, and mountain games rich parallax clouds and sun-rim lighting in one draw call with zero external texture downloads (the network is closed at runtime).

Field rules for Three.js r183 WebGL 2 (ShaderMaterial):

  1. Analytical Altitude Slab ([baseY, topY]): Raymarch only when rayDir.y > 0.025; blend smoothly into the horizon haze (smoothstep(0.025, 0.16, rayDir.y)) so distant cloud bottoms dissolve into scene.fog.
  2. Interleaved Gradient Noise Ray Jitter: Offset t by 0..dt per pixel so 20–24 steps look smoother than 48 unjittered steps.
  3. Dual-Lobe Henyey-Greenstein + Beer-Powder: Forward sun scattering (g = 0.65) paired with 2 * exp(-tau) * (1 - exp(-2 * tau)) gives bright silver linings when looking toward the sun and rich self-shadowed cloud bellies.

Mathematical & Algorithmic Core

  • Ray-Slab: t_0 = max(0, (y_min - o_y)/d_y), t_1 = min(2600, (y_max - o_y)/d_y)
  • Height Profile: w(h) = clamp(h / 0.18, 0, 1) · clamp((1 - h) / 0.45, 0, 1)
  • Front-to-Back Accumulation: T_i+1 = T_i e^-σ rho Δ t, early-exiting when $T < 0.03$.

Engine Implementation

Strict TypeScript Volumetric Sky Module (Assets/Game/volumetric-sky.ts)

Uses erasable strict TypeScript only (import * as THREE from 'three', import type { Game } from 'ccgd'), matching threeCompile rules cleanly:

import * as THREE from 'three';
import type { Game } from 'ccgd';

export interface VolumetricSkyOptions {
  coverage?: number;
  baseY?: number;
  topY?: number;
  windX?: number;
  windZ?: number;
  sunDirection?: THREE.Vector3;
  zenithColor?: number;
  horizonColor?: number;
  steps?: number;
}

const VERTEX_SHADER = /* glsl */ `
  varying vec3 vWorldOffset;
  void main() {
    vWorldOffset = position;
    vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
    gl_Position = projectionMatrix * mvPosition;
  }
`;

const FRAGMENT_SHADER = /* glsl */ `
  precision highp float;

  uniform vec3 uCameraPos;
  uniform vec3 uSunDir;
  uniform vec3 uSunColor;
  uniform vec3 uZenith;
  uniform vec3 uHorizon;
  uniform vec3 uGround;
  uniform vec4 uCloudBand;
  uniform vec3 uWind;
  uniform float uTime;
  uniform int uSteps;

  varying vec3 vWorldOffset;

  float hash13(vec3 p3) {
    p3 = fract(p3 * 0.1031);
    p3 += dot(p3, p3.zyx + 31.32);
    return fract((p3.x + p3.y) * p3.z);
  }

  float noise3(vec3 x) {
    vec3 i = floor(x);
    vec3 f = fract(x);
    f = f * f * (3.0 - 2.0 * f);
    return mix(
      mix(mix(hash13(i + vec3(0.0, 0.0, 0.0)), hash13(i + vec3(1.0, 0.0, 0.0)), f.x),
          mix(hash13(i + vec3(0.0, 1.0, 0.0)), hash13(i + vec3(1.0, 1.0, 0.0)), f.x), f.y),
      mix(mix(hash13(i + vec3(0.0, 0.0, 1.0)), hash13(i + vec3(1.0, 0.0, 1.0)), f.x),
          mix(hash13(i + vec3(0.0, 1.0, 1.0)), hash13(i + vec3(1.0, 1.0, 1.0)), f.x), f.y),
      f.z
    );
  }

  float fbmCloud(vec3 p) {
    float v = 0.56 * noise3(p);
    p = p * 2.04 + vec3(13.7, 7.1, 19.3);
    v += 0.29 * noise3(p);
    p = p * 2.08 + vec3(5.2, 23.4, 11.8);
    v += 0.15 * noise3(p);
    return v;
  }

  float henyeyGreenstein(float cosTheta, float g) {
    float g2 = g * g;
    float denom = max(1e-3, 1.0 + g2 - 2.0 * g * cosTheta);
    return (1.0 - g2) / (12.56637 * denom * sqrt(denom));
  }

  float sampleDensity(vec3 p) {
    float baseY = uCloudBand.x;
    float topY = uCloudBand.y;
    float h = clamp((p.y - baseY) / max(20.0, topY - baseY), 0.0, 1.0);
    float profile = clamp(h / 0.18, 0.0, 1.0) * clamp((1.0 - h) / 0.45, 0.0, 1.0);
    if (profile <= 0.001) return 0.0;

    vec3 windOffset = vec3(uWind.x, 0.0, uWind.y) * uTime;
    float n = fbmCloud((p + windOffset) * uCloudBand.z);
    float cov = uCloudBand.w;
    return clamp((n - (1.0 - cov)) / max(0.1, cov), 0.0, 1.0) * profile;
  }

  void main() {
    vec3 dir = normalize(vWorldOffset);
    vec3 sunDir = normalize(uSunDir);

    float up = clamp(dir.y, 0.0, 1.0);
    vec3 sky = mix(uHorizon, uZenith, pow(up, 0.62));
    if (dir.y < 0.0) {
      sky = mix(uHorizon, uGround, clamp(-dir.y * 4.0, 0.0, 1.0));
    }
    float sunDisc = pow(clamp(dot(dir, sunDir), 0.0, 1.0), 240.0) * 1.5;
    sky += uSunColor * sunDisc;

    if (dir.y > 0.025) {
      float t0 = max(0.0, (uCloudBand.x - uCameraPos.y) / dir.y);
      float t1 = min(2500.0, (uCloudBand.y - uCameraPos.y) / dir.y);
      if (t1 > t0) {
        int steps = clamp(uSteps, 8, 32);
        float dt = (t1 - t0) / float(steps);
        float ign = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))));
        float t = t0 + ign * dt;

        float cosTheta = dot(dir, sunDir);
        float phase = mix(henyeyGreenstein(cosTheta, -0.25), henyeyGreenstein(cosTheta, 0.65), 0.72);
        float silver = 0.40 + phase * 3.0;

        float trans = 1.0;
        vec3 scattered = vec3(0.0);
        float sigma = uWind.z;

        for (int i = 0; i < 32; i++) {
          if (i >= steps || trans < 0.03) break;
          vec3 p = uCameraPos + dir * t;
          float d = sampleDensity(p);
          if (d > 0.003) {
            float dSun = sampleDensity(p + sunDir * 34.0);
            float tau = dSun * sigma * 46.0;
            float beerPowder = 2.0 * exp(-tau) * (1.0 - exp(-2.0 * max(0.1, tau)));
            float h = clamp((p.y - uCloudBand.x) / max(20.0, uCloudBand.y - uCloudBand.x), 0.0, 1.0);
            vec3 shadowCol = vec3(0.36, 0.43, 0.56) * mix(0.45, 0.9, h);
            vec3 litCol = vec3(1.0, 0.97, 0.92) * uSunColor;
            vec3 c = mix(shadowCol, litCol, clamp(beerPowder * silver, 0.0, 1.0));

            float stepTrans = exp(-d * sigma * dt);
            scattered += trans * (1.0 - stepTrans) * c;
            trans *= stepTrans;
          }
          t += dt;
        }
        float fade = clamp((dir.y - 0.025) / 0.13, 0.0, 1.0);
        sky = mix(sky, sky * trans + scattered, fade);
      }
    }

    gl_FragColor = vec4(sky, 1.0);
    #include <colorspace_fragment>
  }
`;

export function createVolumetricSky(game: Game, opts: VolumetricSkyOptions = {}) {
  const sunDir = (opts.sunDirection ?? new THREE.Vector3(0.42, 0.68, 0.34)).clone().normalize();
  const uniforms = {
    uCameraPos: { value: new THREE.Vector3() },
    uSunDir: { value: sunDir },
    uSunColor: { value: new THREE.Color(0xfff1dc) },
    uZenith: { value: new THREE.Color(opts.zenithColor ?? 0x234c91) },
    uHorizon: { value: new THREE.Color(opts.horizonColor ?? 0x9ec0e3) },
    uGround: { value: new THREE.Color(0x282b36) },
    uCloudBand: { value: new THREE.Vector4(opts.baseY ?? 130, opts.topY ?? 310, 0.0022, opts.coverage ?? 0.54) },
    uWind: { value: new THREE.Vector3(opts.windX ?? 6.5, opts.windZ ?? 2.5, 0.046) },
    uTime: { value: 0 },
    uSteps: { value: opts.steps ?? 20 },
  };

  const geom = new THREE.SphereGeometry(900, 24, 16);
  const mat = new THREE.ShaderMaterial({
    uniforms,
    vertexShader: VERTEX_SHADER,
    fragmentShader: FRAGMENT_SHADER,
    side: THREE.BackSide,
    depthWrite: false,
  });

  const dome = new THREE.Mesh(geom, mat);
  dome.name = 'VolumetricCloudSky';
  dome.renderOrder = -1000;
  dome.frustumCulled = false;
  game.scene.add(dome);

  game.onLateUpdate(() => {
    dome.position.copy(game.camera.position);
    uniforms.uCameraPos.value.copy(game.camera.position);
    uniforms.uTime.value = game.time;
  });

  return {
    mesh: dome,
    uniforms,
    setCoverage(c: number) {
      uniforms.uCloudBand.value.w = THREE.MathUtils.clamp(c, 0.1, 0.9);
    },
  };
}

Browser, Mobile & Software-Renderer Budgets

  • Include <colorspace_fragment>: Three.js r183 renders in linear-sRGB workflow and converts output in #include <colorspace_fragment>; omitting it makes custom ShaderMaterial skies look washed-out or overly dark depending on tone-mapping.
  • camera.far vs Dome Radius: Keep SphereGeometry radius safely inside game.camera.far (e.g. radius = Math.min(900, game.camera.far * 0.85)).
  • Step Budget: 16–22 steps with Interleaved Gradient Noise runs at 60 fps on phones and renders in < 40 ms per frame under headless SwiftShader/llvmpipe.

Verification Checklist

  1. Run compile (threeCompile validates strict TypeScript + boots a step in headless Chrome checking for WebGL shader compile/link errors!).
  2. Run capture and inspect Captures/*.png with Read to verify bright sunlit cloud tops and seamless horizon fog matching.

Official references

  • Andrew Schneider & Nathan Vos (SIGGRAPH 2015, Guerrilla Games — Horizon: Zero Dawn Volumetric Cloudscapes)
  • Sébastien Hillaire (SIGGRAPH 2016 — Frostbite Sky & Clouds)
  • Jorge Jimenez (SIGGRAPH 2014 — Interleaved Gradient Noise)

Playable Three.js games made with GameCrew

Launch a real browser build using this engine and inspect its controls or fork its project tree.

More Three.js techniques

optimization

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.

physics

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.

ai

Zero-Allocation Context Steering, Patrol Loops & Telegraphed AI in Three.js →

Deterministic 60 Hz enemy and companion AI in Three.js using 8-slot context steering against CollisionWorld, level.json patrol loops, attack-token pacing, and telegraphed strikes.

gameplay

Multiplayer Room State Sync & 60 Hz Avatars in Three.js →

Solo-first multiplayer with smooth 60 Hz remote avatars, host-owned shared state, reliable host claims, and deterministic two-peer room tests.

Use verified techniques inside a real game

Describe your game idea for free or connect an MCP assistant to search and contribute techniques.

Learn about collaboration