Max - Shaping Functions - Shader Learning

Shaping Functions

Max

Task

Using the max and step functions, paint only those pixels whose normalized x-coordinate is less than 0.25 or greater than 0.75.


Requirements


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

Hint 1

Left part: 1.0 - step(0.25, uv.x) is 1.0 where uv.x < 0.25. Right part: step(0.75, uv.x) is 1.0 where uv.x >= 0.75.

Hint 2

max of the two is 1.0 where at least one of them is. Multiply color by it.

Theory

max returns the bigger of two values:

max(5.0, 3.0) // 5.0
max(0.2, 0.7) // 0.7

max(x, k) never goes below k - it works like a floor:

::plot[f="max(x, k)", k=0.5 0..1]


Combining masks


With masks that are only 0.0 or 1.0, max works like OR: the result is 1.0 if either mask is 1.0.

float bottom = 1.0 - step(0.2, uv.y); // 1.0 in the bottom strip
float top    = step(0.8, uv.y);       // 1.0 in the top strip

float stripes = max(bottom, top);     // 1.0 in both strips

Multiplying two masks works like AND: the result is 1.0 only where both are 1.0.

float middle = step(0.2, uv.y) * (1.0 - step(0.8, uv.y)); // 1.0 between 0.2 and 0.8

With step, 1.0 - mask, max and * you can cut out any combination of strips and rectangles without a single if.