One of my favourite little shader techniques is to take continuous linear values, and turn them into oscillating triangle waves.
Oscillation is useful in all kinds of cases. It can create repetition in space, or repeating animation over time. The most common way to generate oscillation is with the trigonometry function sin, which creates the well known smooth sine wave shape.
But sin can sometimes be a little expensive, and other times that smoothness and non-linearity is not exactly what you want. In those cases, a triangle wave might be worth a look.
From line to triangle
We start out with a value - in this case called y - which increases at a constant rate. This could be a coordinate which changes from pixel to pixel, or a time value.
The first part of this trick is take only the fractional part of y. That already converts y into an oscillating value, but it is discontinuous. Every time the original value exceeds one, it wraps around to zero again.
Next we multiply - scale - the value by two, so that it oscillates between zero and two.
Now we subtract one, making it oscillate between minus one and plus one.
The final step of the trick is to take the absolute value. Now the negative parts of the wave are reflected, and the function becomes continuous again.
That’s it. Now you can make a triangle wave from any continuous value.