Else If - Shader Basics - Shader Learning

Shader Basics

Else If

Task

The input color (HLSL: input.color) is the same gradient: color.r grows from 0.0 at the left edge to 1.0 at the right edge.


Use if / else if / else to paint a flag with three vertical stripes:

  • where color.r is below 0.33, paint blue (0.0, 0.0, 1.0);
  • where it is from 0.33 up to 0.66, paint white (1.0, 1.0, 1.0);
  • everywhere else, paint red (1.0, 0.0, 0.0).

Alpha is 1.0 everywhere.

Hint 1

Three stripes are three cases: if, else if and else. Write the checks in the order the stripes go, from left to right.

Hint 2

The second check doesn't need to repeat the first one: if the pixel got there, you already know color.r is at least 0.33. What's left to check is only the other edge of the white stripe.

Theory

if / else chooses between two options. For more, chain the checks with else if:

if (x < 0.25) {
    // x is below 0.25
} else if (x < 0.75) {
    // x is from 0.25 up to 0.75
} else {
    // x is 0.75 or more
}

The conditions are checked from top to bottom, and only the first true branch runs. The rest are skipped.


That's why the second check doesn't need to repeat x >= 0.25: if x were smaller, the first branch would already have run. It also means the order matters: put x < 0.75 first, and it would catch every x below 0.25 too.


You can chain as many else if as you need. In HLSL it looks exactly the same.