Min - Rectangle - Shaping Functions - Shader Learning

Shaping Functions

Min - Rectangle

Task

Draw a rectangle with the color (1.0, 0.3, 0.3) on a black background. In uv coordinates the rectangle goes from x = 0.2 to x = 0.8 and from y = 0.3 to y = 0.7.


Requirements


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

Hint 1

Make one mask per side of the rectangle, each 1.0 on the inner side of its edge. step already works this way for the left and bottom sides; for the right and top sides you need the inverted mask from Step - Invert.

Hint 2

min takes only two values. Combine the four masks in pairs, then combine the two results.

Hint 3

The final mask is 1.0 only inside the rectangle. Multiply the color by it.

Theory

min is the twin of max: it returns the smaller of two values.

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

min(x, k) never goes above k - it works like a ceiling:

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


Intersection of masks


With masks that are only 0.0 or 1.0, max works like OR (union), and min works like AND (intersection): the result is 1.0 only where both masks are 1.0.


a b max(a, b) - OR min(a, b) - AND
0 0 0 0
0 1 1 0
1 0 1 0
1 1 1 1

For such masks min(a, b) gives the same result as a * b. The difference shows up with soft values, between 0 and 1: min(0.5, 0.5) is 0.5, while 0.5 * 0.5 is 0.25.


A rectangle


A rectangle is the area that is at the same time:

  • right of its left side: step(left, uv.x),
  • left of its right side: 1.0 - step(right, uv.x),
  • above its bottom side: step(bottom, uv.y),
  • below its top side: 1.0 - step(top, uv.y).

Each line is a mask for a half of the screen. Their intersection is the rectangle. min takes two values, so combine four of them in pairs: min(min(a, b), min(c, d)).


In HLSL the function is also called min.