With the rise of more advanced 3D graphics came the introduction of graphical pipelines, one of the most popular being
openGL. This allows you to create complex 3D worlds on almost all devices, even in your browser using an openGL variant:
webGL. One of the most interesting parts of using 3D are
pixel shaders. Pixel shaders are programs which compute a color for each pixel in an outputted image or animation.
OpenGL has its own shading language: GLSL (openGL Shading Language). GLSL can be a little overwhelming and there are not alot of really basic 'get to know' GLSL out there, this article will help you grasp some of the fundamental concepts of this wonderfull language.
All the examples you see are interactive, you can play with the code and everything gets compiled on the run, have fun!
GLSL treats integers and floats very differently. Mixing the two or forgetting to add a dot to a number will bring you alot of late night bug hunting nights. GLSL tends to interpret values mostly as fractional amounts, so in most cases you'll type
1.0 instead of
GLSL uses a state attribute
precision to determine how much precision the GPU uses to calculate floats. You can choose between
lowp. Most systems support
highp can bring some performance complications.
A good rule of thumb:
highp for vertex positions,
mediump for texture coordinates,
lowp for colors.
Let's start by creating a solid color shader. Colors are a combination of red, green, blue and alpha. Every values has a scale from
Next up we can create a simple gradient. We use the resolution global variable in combination with the
gl_FragCoord to calculate the current pixel position that is being calculated by our GPU. We then use this value to map it between
1.0 by deviding it by the total resolution (
resolution.x = width,
resolution.y = height) of our shader.
As you probably noted GLSL has global variables that have an underlying function/value already assigned to them. Example
gl_Position. A list of built-in variables can be found on the official site: http://www.opengl.org/wiki/Built-in_Variable_(GLSL).
time a simple counting value in my main openGL (or webGL) program like this:
gl.uniform1f( currentProgram.uniformsCache[ 'time' ], parameters.time / 1000 );
Another example is the mouse X and Y position, this is also passed on by your main program like this:
gl.uniform2f( currentProgram.uniformsCache[ 'mouse' ], parameters.mouseX, parameters.mouseY );
You can then play around with them and create cool interactive experiments like this:
That should get you started to make cool stuff with GLSL! If you have any questions/remarks or just want to show me what you've made, poke me on twitter!