Skip to content

Shaders

mattdesl edited this page Dec 11, 2012 · 35 revisions
start » Shaders

Contents

  • Intro
  • Lesson 1 covers the basics of writing your own vertex and fragment shaders.
  • Lesson 2 covers texture sampling and basic image processing (inverting a texture).
  • Lesson 3 covers vignettes, circles, grayscale, and sepia effects.
  • Lesson 4 (WIP) will cover multiple texture units, blending, and texture splatting. For now, see here.
  • Lesson 5 (WIP) will cover blurring images.
  • Lesson 6 (WIP) will cover normal map lighting for 2D games. See here for now.
  • Lesson 7 (WIP) will cover light scattering, aka "god rays".
## Intro

GLSL stands for OpenGL Shading Language. Shaders are like small scripts that let us interact with the graphics processor more closely. They are an essential aspect of graphics programming, and can be used for a variety of effects and visuals in your 2D and 3D games. For now, there are two types of shaders you should familiarize yourself with:

Vertex Shaders

As discussed in the Textures article, a vertex is a point in space with some attributes attached to it, like position (xyz), colour (rgba), texture coordinates (st). A “vertex shader” allows you to interact with this vertex information before sending it along the graphics pipeline to be rendered.

Vertex shaders are often more applicable in 3D graphics programming -- e.g. applying a noise displacement to the vertices of a 3D mesh -- but they are still essential to understand even for 2D games.

Fragment Shaders

Often called “pixel shaders,” these allow us to modify individual pixels before they are sent along the graphics pipeline. These shaders “output” a RGBA colour. Think of it like a return statement: if we rendered a sprite with a fragment shader that only returned the colour red (R=1, G=0, B=0, A=1) – the result would be a red box!

Basic Shaders

Vertex and fragment shaders both require a main() method. Vertex shaders typically pass the position of the vertex on to GL, like so:

//the position of the vertex as specified by our renderer
attribute vec3 Position;

void main() {
    //pass along the position
    gl_Position = vec4(Position, 1.0);
}

Whereas fragment shaders typically pass the frag color (i.e. "pixel" color) along, like so:

void main() {
    //pass along the color red
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}

Further Reading

The best way to learn GLSL is through experimentation and practice. Once you've finished the lessons, check out some online GLSL effects to see how they were achieved:

If you're feeling comfortable with GLSL, you could also try making your own shader-based sprite batcher (see here and here) in order to have a better grasp of how it all comes together.