Ever heard of a shader but too afraid to ask what it even means at this point?
Lets fuck around and find out 👇
First, we need to understand the difference between a CPU and GPU and why we need a separate unit just to draw graphics anyway.
(Don't worry, it's not going to be too technical.)
The thing that makes a CPU great is that it can perform a wide variety of tasks relatively quickly.
But the limitation is that each CPU core is optimised to do one thing at a time and so tasks are largely performed sequentially.
This isn't ideal for rendering. Drawing something 30+ times a second starts to occupy a lot of CPU capacity.
For high-res graphics changing in real time the CPU on it's own will struggle to keep up - plus it's got other CPU shit to do.
The GPU by contrast is specifically designed to render graphics by being able to do thousands of things at once.
Picture it as thousands of tiny units all strapped together, each just figuring out the colour of a pixel.
This parallel processing is really, really fast.
But the consequence of parallelism is that each separate thread has no idea what the others are doing - making programming tricky.
You can't change one pixel value based on the result of a separate pixel.
In fact, not only does each thread have no idea what the other threads are doing, they have no idea what they have just done.
They are memoryless, so you can't compute an input based on a previous output.
This is kinda what shaders are - code designed to produce graphics on the GPU within these constraints.
We call a 2D shader a fragment (or pixel) shader because it's a piece of code that calculates the colour of a single fragment of the screen - often a single pixel.
So with all these constraints, how do you actually do anything useful in a shader?
Well, you can do a lot with a little. Just knowing the fragment position and the resolution of the canvas can get you quite far.
Here's a simple example on a 40x40 grid.
If we take the fragment position and divide it by the resolution of the whole canvas we can then render a different colour at every fragment.
It creates this gradient across the canvas.
If you add time as a variable you can start to animate the gradient.
And if you throw some more maths at it you can create some really amazing shit.
shadertoy.com/view/XslGRr
So why am I telling you about this specialised graphics programming?
Well they are starting to be used more on the web, thanks to improvements in hardware and web technology.
This animated gradient on stripe.com is a shader.
Most of this was taken from the amazing resource:
The Book of Shaders by @patriciogv and @_jenlowe_.
It's the best place to get started with programming shaders.
thebookofshaders.com/