Shaders From Zero · Episode 12

Glass & Refraction

Glass & Refraction is Episode 12 of Shaders From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 12 · Shaders From Zero

Glass is the trickiest non-effect in shaders — non-effect because most of what makes it look like glass is what you can see through it. We build a stylized glass shader without an HDR file or a complex BRDF: we use a procedural sky that returns a color for any direction, and we fake refraction with a few extra refract() calls.

By the end you have a glass shader that works on any mesh, in any scene, without loading a single texture. Trade-off: it's stylized, not photoreal. For photoreal, you'd load an HDR environment map; the math is identical.

0 fps
SphereGeometry · refract / reflect
Layer 1: tinted transparency. Looks like colored cellophane.

The procedural sky

Instead of sampling a cube map, we use a function that returns a color for any 3D direction. The sky has three regions: bright zenith (overhead), warm horizon, dark nadir (underfoot). Plus a sun disc in a fixed direction.

vec3 proceduralSky(vec3 dir) {
  float t = clamp(dir.y * 0.5 + 0.5, 0.0, 1.0);
  vec3 zenith  = vec3(0.15, 0.35, 0.7);
  vec3 horizon = vec3(0.9, 0.7, 0.45);
  vec3 nadir   = vec3(0.05, 0.04, 0.06);
  vec3 col = mix(nadir, horizon, smoothstep(0.0, 0.5, t));
  col = mix(col, zenith, smoothstep(0.5, 1.0, t));
  // sun
  float sun = pow(max(dot(dir, normalize(vec3(0.5, 0.8, 0.3))), 0.0), 64.0);
  col += vec3(1.5, 1.2, 0.9) * sun;
  return col;
}

Any direction in — color out. That's all we need for reflection and refraction sampling. No textures, no extra loads.

Layer 1 — Tinted transparency

void main() {
  gl_FragColor = vec4(uTint, 0.3);
}

With material.transparent = true, you get colored cellophane. Stage 1 in the demo. Looks like a candy wrapper. Not glass.

Layer 2 — Fresnel

Same fresnel pattern from Episode 09. Now used to modulate opacity — edges more opaque, center barely visible.

varying vec3 vNormal;
varying vec3 vViewDir;

float NdotV = max(dot(normalize(vNormal), normalize(vViewDir)), 0.0);
float fresnel = pow(1.0 - NdotV, 5.0);
float alpha = mix(0.1, 0.9, fresnel);

gl_FragColor = vec4(uTint, alpha);

Already starts looking glassy. The thin center + visible rim is a strong "glass" cue.

Layer 3 — Reflection

For every fragment, compute the reflection direction and sample the procedural sky:

vec3 N = normalize(vNormal);
vec3 V = normalize(vViewDir);          // from surface to camera
vec3 R = reflect(-V, N);               // reflection direction
vec3 reflColor = proceduralSky(R);

// Mix tint with reflection by fresnel
vec3 col = mix(uTint * 0.5, reflColor, fresnel);
gl_FragColor = vec4(col, alpha);

reflect() takes the incoming direction (from camera toward surface) and the surface normal, returns the reflected direction. We negate V because we want the direction from surface AWAY into the world, and our V points from surface TO camera.

The fresnel multiplier means edges show more reflection (mirror-like) and the center shows more tint (transparent).

Layer 4 — Refraction + chromatic aberration

Light entering glass bends. Different wavelengths bend by different amounts — that's how a prism makes a rainbow. We fake it: sample the sky at three slightly different refraction angles, one per RGB channel.

vec3 N = normalize(vNormal);
vec3 V = normalize(vViewDir);

float ior = 1.5;
float chromatic = 0.02;

vec3 Tr = refract(-V, N, 1.0 / (ior - chromatic));
vec3 Tg = refract(-V, N, 1.0 / ior);
vec3 Tb = refract(-V, N, 1.0 / (ior + chromatic));

vec3 refrColor = vec3(
  proceduralSky(Tr).r,
  proceduralSky(Tg).g,
  proceduralSky(Tb).b
);

vec3 R = reflect(-V, N);
vec3 reflColor = proceduralSky(R);

// Mix refraction (center) with reflection (edges)
vec3 col = mix(refrColor * uTint, reflColor, fresnel);
gl_FragColor = vec4(col, 1.0);

Notice the alpha is now 1.0 — once we have refraction, we don't need transparency. The "transparent" look comes from the refracted scene visible through the glass.

refract() returns vec3(0.0) when total internal reflection happens (the ray would have to bend backwards). Real glass shaders detect this and fall back to reflection. We ignore it here — for stylized glass, the degenerate case rarely shows.

Layer 5 — Frosted blur

Frosted glass scatters light. Instead of sampling the sky once per direction, we sample it many times around the direction and average. That's expensive.

The cheap version: jitter the refraction direction by a hash, sample once.

float hash(vec2 p) {
  return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
}

// jitter refraction direction by uRoughness
vec3 jitter = (vec3(
  hash(gl_FragCoord.xy + 0.0),
  hash(gl_FragCoord.xy + 11.0),
  hash(gl_FragCoord.xy + 22.0)
) - 0.5) * uRoughness;

vec3 Tg = refract(-V, normalize(N + jitter), 1.0 / ior);
// ...

Jittering the NORMAL (not just the direction) gives the diffused look. Real frosted glass micro-roughness scatters in many directions; our hash approximates one random direction per pixel — which under temporal accumulation (the eye's persistence of vision) reads as scatter.

For sharper frosting, do this multiple times in a loop and average. For real- time, one sample per pixel is enough.

Common pitfalls

  • Forgot transparent = true on Layer 1-2. Looks opaque. Set it.
  • Used DoubleSide on glass. Wrong for refraction — only the outer surface should refract. Use side: THREE.FrontSide (the default).
  • Confused V sign. refract() wants the INCOMING direction (from camera toward surface). If your vViewDir points from surface to camera, negate it before passing to refract.
  • Sun too bright. The procedural sky has a sun disc. If your reflection samples it directly, the highlight overwhelms everything. Either dim the sun coefficient (we use 1.5×) or tonemap.

Exercises

  1. Tint the refraction with a colored absorption — multiply refrColor by vec3(0.8, 0.95, 0.95) for slightly-green glass.
  2. Animate ior with a slow sine — the glass appears to "breathe."
  3. Replace the procedural sky with RoomEnvironment from Three.js's addons. Use PMREMGenerator to build a cube map, sample it via texture2D(envMap, equirectUv(dir)) in the shader.

What's next

Episode 13 — Procedural Galaxy. First use of THREE.Points in the series. 80,000 particles in a 3-arm spiral, colored by distance, rotated by the vertex shader.