CPSC 314, September 2014
Fragment Shader Introduction

Vertex shaders and fragment shaders allow for the GPU (graphics processing unit) to perform fairly complex and efficient calculations for each vertex and each pixel "fragment" that is transformed and to be rendered. There are other types of shaders being introduced as well, such as the recently-introduced "tesselation shaders" in OpenGL 4.0 and Direct3D 11.

The main goal of a fragment shader (sometimes called a "pixel shader") is to compute the colour of a fragment. There are a variety of languages that can be used to program shaders. WebGL uses a version of GLSL, and that is what we shall also be using. The most basic shader simply assigns a fixed color to a single pixel using something like:
gl_FragColor = vec4(r,g,b,a); .

The easiest way to begin learn about fragment shaders is to begin to play with one, such as the one shown below. ShaderToy allows you to interactively edit shader code and see the result. For ShaderToy, consider that the entire screen to be covered by two large triangles, and therefore a call is made to the shader for every pixel on screen. If you wish to be able to save and post your shader, you may want to create an account, although for simply experimenting with some basic shaders, you need not bother.

Experiment on ShaderToy with the following, using the code below as your starting point:

vec4 backgroundColor = vec4(0.9, 0.99, 0.99, 1);
float sphereSize = 0.7;
vec4 sphereColor = vec4(0.5,0.4,0.3, 1);

void main(void)
{
    vec2 uv = gl_FragCoord.xy / iResolution.xy;
    vec2 p = uv * 2.0 - 1.0;
    p.x *= iResolution.x / iResolution.y;
//    sphereColor[1] = 0.5*(sin(iGlobalTime*3.0)+1.0);
    
    vec4 color = backgroundColor;
	float r = sqrt(dot(p, p));
    if (r < sphereSize) {
        color = sphereColor;
//        color = sphereColor*texture2D( iChannel0, vec2(uv.x,1.0-uv.y)).rgba;
//        color = texture2D( iChannel0, vec2(uv.x,1.0-uv.y)).rgba;
    }
    gl_FragColor = color;   
}