Arrays
Task
The starter has a palette of 4 colors. Split the screen into 4 vertical stripes of equal width:
- in the bottom half of the screen, the stripes show the colors in order from left to right:
palette[0],palette[1],palette[2],palette[3]; - in the top half, the order is reversed:
palette[3]on the left, ...,palette[0]on the right.
Hint 1
Stretch uv.x so that every stripe is exactly one unit wide. Then int(...) of it is the stripe number, from 0 to 3.
Hint 2
The reversed order: stripe 0 needs color 3, stripe 3 needs color 0. Find the arithmetic that does it. It works with ints, so write 3, not 3.0.
Hint 3
Every pixel now has two candidate colors: in order and reversed. Choose between them by height: a one-line choice between two values is what the Ternary Operator task was about (an if works too).
Theory
An array is a numbered list of values of the same type. Instead of color0, color1, color2, ... you keep them all under one name and pick one by its number.
Declaring an array
vec3 palette[3] = vec3[3](
vec3(1.0, 0.0, 0.0),
vec3(0.0, 1.0, 0.0),
vec3(0.0, 0.0, 1.0)
);
vec3- the type of every element;palette- the name;[3]- how many elements it holds. The size is fixed: an array can't grow or shrink;vec3[3](...)- the values, in order.
Reading an element
Write the element's number (its index) in square brackets. Indices start at zero:
palette[0] // vec3(1.0, 0.0, 0.0) - the first element
palette[2] // vec3(0.0, 0.0, 1.0) - the last element of a 3-element array
Watch out: palette[3] doesn't exist. The compiler can't always catch it, and the GPU doesn't stop with an error: you get a garbage value. Keep the index from 0 to size - 1.
The index is an int
An index must be a whole number of type int: palette[1], not palette[1.0]. In shaders int and float don't mix on their own:
int i = 2;
int next = i + 1; // ok: int + int
float f = i + 1.0; // error: int + float
float g = float(i) + 1.0; // ok: convert first
To turn a float into an int, use int(...). It drops the part after the decimal point:
int(2.7) // 2
int(0.99) // 0
So int(uv.x * 3.0) is 0 on the left third of the screen, 1 in the middle third and 2 on the right third - a perfect index for a 3-color palette.
HLSL
HLSL declares arrays with curly braces. On this site, write the array inside the function that uses it (e.g. main):
float3 palette[3] = {
float3(1.0, 0.0, 0.0),
float3(0.0, 1.0, 0.0),
float3(0.0, 0.0, 1.0)
};
Indexing and int(...) work the same way.