Ternary Operator - Shader Basics - Shader Learning

Shader Basics

Ternary Operator

Task

The input color (HLSL: input.color): color.r grows from left to right, color.g from bottom to top.


Without if, using only the ternary operator, build the output color:

  • red is 1.0 where color.r is greater than 0.5, otherwise 0.0;
  • green is 1.0 where color.g is greater than 0.5, otherwise 0.0;
  • blue is 0.0, alpha is 1.0.

You'll get four squares: black, red, green and yellow.

Hint 1

Each channel is a separate choice between 1.0 and 0.0, so you need one ternary per channel.

Hint 2

The condition goes before ?, the value for "true" after it, the value for "false" after :. Compare with the example in the theory.

Theory

When an if / else only chooses between two values, there's a one-line form:

condition ? valueIfTrue : valueIfFalse

These two pieces of code do the same thing:

float red;
if (color.r > 0.5) {
    red = 1.0;
} else {
    red = 0.0;
}
float red = color.r > 0.5 ? 1.0 : 0.0;

It's called ternary because it takes three parts. Unlike if, it gives back a value, so you can use it right inside an expression:

gl_FragColor = vec4(color.r > 0.5 ? 1.0 : 0.0, 0.0, 0.0, 1.0);

In HLSL it looks exactly the same.