Step Union - Built-in functions - Shader Learning

Built-in functions

Step Union

Task

Create a shader program that draws a rectangular frame border around the screen. The border width is 50 pixels. Use uv coordinates as the frame border color.


Use the step function to draw each border separately. Next, combine the borders together to create a frame. To do this, you only need to compute the union of the test results.


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.

Theory

The union of step functions is a new function that returns 1 if a value is greater than the threshold value of at least one step function from the union. To use union, you can simply compute all the results of the step functions at a given point and take the maximum of them.


Implementation


Here's how you can implement this in GLSL:

float stepUnion(float x) {
    // check if the value is less than 0.25.
    float r0 = 1.0 - step(0.25, x);

    // check if the value is greater than 0.75.
    float r1 = step(0.75, x);

    // check if the value is less than 0.25 or greater than 0.75.
    return max(r0, r1);
}

The function returns 1 if x is less than 0.25 or greater than 0.75, and 0 otherwise.


Examples


Let's see how this function works with different input values:

stepUnion(0.1); // will be 1 since 0.1 is less than 0.25.
stepUnion(0.5); // will be 0 since 0.5 is greater than 0.25 and less than 0.75.
stepUnion(0.9); // will be 1 since 0.1 is greater than 0.75.

By using the maximum of the results, you can easily determine if a value falls outside a specified range.