Game Development Reference
What is a shader?
Shaders come in different forms and use different languages, depending on their API but,
ultimately, a shader is a program which executes on the GPU. And, as with any program, a
shader requires an input and produces an output. The input and output of a shader depends
on the shader's type. We will only cover the shader types that are supported by the Shader
class in SFML and make sense in a 2D sprite-based context, the Vertex and Fragment
(Pixel) shaders. We can visualize the graphics pipeline from the moment we want to render
something to the actual writing on the render target with the following diagram:
Each time that we call the RenderTarget::draw() method, OpenGL goes through
the steps described in the preceding diagram. Firstly, we pack all the vertices (position, col-
or, texture coordinate) in a package and send it over to be stored in GPU memory. When
we consider a sprite, there are four vertices for the four corners of the rectangle. After get-
ting the vertices in GPU memory, OpenGL runs the Vertex shader program on each of
those vertices. We can then manipulate any of them in any way we like. More often though,
a common shader is used where it just transforms each vertex with the Model, View, and
Projection matrices. Those matrices represent the transformation (position, rotation, and
scale) of the model, the position and orientation of the camera, and the camera's projection.
After we transform each vertex, OpenGL calculates which fragments have to be painted on
the target. This process is called as rasterization . Looking at the sprite example again, a
16x16 sprite with a scale of (1, 1) and a zero angle rotation has exactly 16x16 = 256 pixels.
After OpenGL calculates all the pixels (or fragments), it calls our Pixel (Fragment) shader
on each of them. The result of that shader is a color, which can be placed in the relevant
fragment on the render target.
That ends the introduction section on the topic of shaders. Next we will talk about loading
and using shaders.