And / Or - Shader Basics - Shader Learning

Shader Basics

And / Or

Task

The input color (HLSL: input.color) is a gradient in two directions: color.r grows from 0.0 to 1.0 from left to right, color.g grows from 0.0 to 1.0 from bottom to top.


Paint:

  • a white rectangle (1.0, 1.0, 1.0) where color.r is between 0.25 and 0.75 and color.g is between 0.25 and 0.75;
  • red (1.0, 0.0, 0.0) stripes where color.r is below 0.1 or above 0.9;
  • everything else black.

Alpha is 1.0 everywhere. Use "between" as strictly greater / less than (> and <).

Hint 1

Inside the rectangle, color.r has to be in a range and color.g has to be in a range. A range has two edges, so that's four comparisons that all must be true.

Hint 2

The stripes are "near the left edge or near the right edge": one || between two comparisons.

Hint 3

Start with black and paint the two colored areas with if / else if. They don't overlap, so their order doesn't matter.

Theory

Sometimes one comparison isn't enough. Combine several with logical operators:


Operator Meaning true when
&& AND both sides are true
|| OR at least one side is true
! NOT the value after it is false

// x is between 0.25 and 0.75
if (x > 0.25 && x < 0.75) { ... }

// x is near the left or the right edge
if (x < 0.1 || x > 0.9) { ... }

// the same as x >= 0.5
if (!(x < 0.5)) { ... }

You can't write 0.25 < x < 0.75 like in math: split it into two comparisons joined with &&.


In HLSL the operators are the same.