Lesson 6 of 10 · GLSL shaders for beginners

The center

The origin point of every shader.

In “The gradient” p went from 0 (corner) to 1 (opposite corner), which works for painting from one side to the other. Centered things, like the circle in “The glow”, need 0 in the middle of the screen. That is what this lesson does.

(0, 0). Ground zero. Everything is measured from here.

There is a formula that almost every shader uses at the start.

The center formulavec2 p = (2.*gl_FragCoord.xy - R) / min(R.x, R.y);

What it does: the center of the screen is now (0,0). The short side goes from -1 to 1. On a 16:9 wide screen, x reaches 1.78. And it works whether the screen is square or wide, no distortion.

2.*gl_FragCoord.xy - R moves 0 to the center, with negatives to the left and bottom and positives to the right and top. Dividing by min(R.x, R.y), the short side of the screen, puts that side between -1 and 1, which is why a circle comes out round even on a wide screen. You do not need to memorize it. It is the first line of almost every shader you write.

Reading the codep.x * 0.5 + 0.5: brings the position from -1…1 back to 0…1 to use it as color.
0.4: the center’s fixed blue. It is the Blue slider.
0.9 + 0.1 * (1.0 - length(p)): darkens the edges by 10%. length(p) is the distance to the center; you open it in “The glow”.
You know these: hueShift (03 · Mixing).
Next: from here on, every lesson starts with this line.
TryChange 0.4 (blue) to 0.9 and the center turns lavender. Swap p.x for p.y on the first color line and the gradient flips.

The code

void main(){
  vec2 p = (2.*gl_FragCoord.xy - R) / min(R.x, R.y);
  vec3 col = vec3(p.x * 0.5 + 0.5, p.y * 0.5 + 0.5, 0.4);
  col *= 0.9 + 0.1 * (1.0 - length(p));
  col = hueShift(col, 0.0);
  gl_FragColor = vec4(col, 1.);
}