Lesson 9 of 10 · GLSL shaders for beginners

The glow

Distance to center. exp() does the rest.

In “The center” you put 0 in the middle of the screen. A circle needs one more fact: how far is each frag from that center?

Far from center: darkness. Close: light explodes.

The function length(p) tells you. If the frag is at the center, it returns 0. If it is in a corner, it returns something like 1.4.

If you take that distance and say "frags closer than 0.5 are white, the rest are black", you have a perfect circle.

smoothstep()Makes a smooth transition between two values. smoothstep(r, r - 0.02, d), with r = 0.35, says: when d is 0.35, give 0. When it is 0.33, give 1. And in between, a smooth curve. Without this, the circle edge looks jagged. With it, buttery smooth.
exp()exp(-d * 2.5) is 1 at the center and falls toward 0 as you move away, never reaching it. That is the halo. With a number bigger than 2.5 the halo hugs the center; with a smaller one it spreads.
Reading the codefloat d = length(p);: the frag’s distance to the center. 0 in the middle, 1 at the top edge.
r = 0.35 + 0.05 * sin(T * 1.2): the radius beats between 0.30 and 0.40.
smoothstep(r, r - 0.02, d): 1 inside the circle, 0 outside, with a soft 0.02 edge.
col += … and mix(col, core, circ): background, wide halo (1.2), close halo (2.5), and the circle on top last.
You know these: p (06 · The center), sin(T) (07 · The clock).
Next: in “The tunnel” the distance is flipped and rings appear.
TryChange 0.35 to 0.6 and the circle grows. To 0.2 and it shrinks. Change T * 1.2 (the pulse) to T * 5. and the circle beats nervous. To T * 0.3 and it breathes slow.

The code

void main(){
  vec2 p = (2.*gl_FragCoord.xy - R) / min(R.x, R.y);
  float d = length(p);
  float r = 0.35 + 0.05 * sin(T * 1.2);
  float circ = smoothstep(r, r - 0.02, d);
  float glow = exp(-d * 2.5) * 0.7;
  float outerGlow = exp(-d * 1.2) * 0.15;
  vec3 core = vec3(0.3, 0.95, 0.9);
  vec3 halo = vec3(0.15, 0.65, 0.6);
  vec3 outer = vec3(0.08, 0.25, 0.25);
  vec3 bg = vec3(0.015, 0.04, 0.05);
  vec3 col = bg;
  col += outer * outerGlow;
  col += halo * glow;
  col = mix(col, core, circ);
  gl_FragColor = vec4(col, 1.);
}