Step - Shaping Functions - Shader Learning

Shaping Functions

Step

Task

Write a shader that splits the screen into two parts: the left half should be black and the right half should be red. The shader should work for any screen resolution. To achieve this, consider using the uv coordinates to control the position of the split.


Requirements


The shader should avoid using branching or conditional statements in its code, and instead rely on the step function to determine the color of each pixel.

Hint 1

Compute the normalized coordinates first: vec2 uv = gl_FragCoord.xy / iResolution.xy; (HLSL: input.position.xy / iResolution). uv.x goes from 0.0 at the left edge to 1.0 at the right edge.

Hint 2

step(0.5, uv.x) is 0.0 on the left half and 1.0 on the right half. Use it as the red channel of the output color.

Theory

step is the simplest way to draw a hard edge: everything on one side becomes 0.0, everything on the other side becomes 1.0.

float step(float edge, float x)
  • x < edge → 0.0
  • x >= edge → 1.0

On the screen:

vec2 uv = gl_FragCoord.xy / iResolution.xy;
float mask = step(0.5, uv.x); // 0.0 on the left half, 1.0 on the right half

mask works like a stencil: multiply a color by it and the color shows only where the mask is 1.0.


Watch out: the edge comes first. step(uv.x, 0.5) compares the other way around and gives the opposite picture.


Move the edge and watch the jump follow it:

::plot[f="step(edge, x)", edge=0.5 0..1]