Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 50 ยท WebGL and Real-Time Graphics

Shaders and GLSL Basics

Learn GLSL for WebGL: vertex and fragment shaders, attributes, uniforms, varyings, vector types, swizzling and built-in functions, with live editable shaders.

A shader is a small program that runs on the GPU. In the WebGL overview you treated the two shaders as a fixed recipe to copy. In this lesson you learn to write them yourself. The language is GLSL (OpenGL Shading Language): it looks like C, but it is built around vectors and matrices, it has no pointers, no recursion and no printing, and it is designed so the GPU can run the same function on thousands of items at once.

You will read and edit real shaders in this lesson. Changing a few numbers in a fragment shader and seeing the picture change is the quickest way to build an intuition for the GPU, which is why shader artists spend so much time doing exactly that.

The two shaders and their jobs

flowchart LR
  A["Attributes<br/>(per vertex, from buffers)"] --> V["Vertex shader<br/>runs once per vertex"]
  U["Uniforms<br/>(same for the whole draw)"] --> V
  U --> F
  V -->|"gl_Position"| R["Rasterizer"]
  V -->|"varyings"| R
  R -->|"interpolated varyings"| F["Fragment shader<br/>runs once per pixel"]
  F -->|"gl_FragColor"| O["Framebuffer"]

Three kinds of inputs: attributes (per vertex), uniforms (per draw call) and varyings (from vertex to fragment).

  • The vertex shader receives one vertex's attributes and must write gl_Position, a vec4 in clip space. It may also write varyings.
  • The fragment shader receives the interpolated varyings for one pixel and must write gl_FragColor, a vec4 of red, green, blue and alpha, each from 0.0 to 1.0.

Storage qualifiers

Variables outside functions carry a keyword that says where their value comes from (WebGL 1 syntax, which WebGL 2 also accepts):

Qualifier Where Meaning
attribute vertex shader only Per-vertex input from a buffer (position, normal, color, uv)
uniform either shader A value set from JavaScript, constant for all vertices and pixels of one draw call (matrices, time, light direction)
varying vertex writes, fragment reads Passed to the fragment shader and interpolated across the triangle

In WebGL 2 with #version 300 es, attribute becomes in, varying becomes out in the vertex shader and in in the fragment shader, and you declare your own output variable instead of gl_FragColor. The ideas are the same.

Types

GLSL's core types are small and numeric:

GLSL
float f = 0.5;          // a literal needs a decimal point: 1.0, not 1
int   n = 3;
bool  on = true;
vec2  p = vec2(0.3, 0.7);
vec3  rgb = vec3(1.0, 0.5, 0.0);
vec4  color = vec4(rgb, 1.0);      // constructors can combine pieces
mat4  m;                            // 4x4 float matrix
sampler2D tex;                      // a texture (uniform only)

Vector types come in vec2, vec3, vec4; matrices in mat2, mat3, mat4. WebGL 1 does not convert between int and float automatically, so float x = 1; is an error, and a common first compile failure. Write 1.0.

Swizzling

Components are named x y z w, or r g b a for colors, or s t p q for texture coordinates. You can pick any combination, repeat and reorder them:

GLSL
vec4 c = vec4(0.1, 0.2, 0.3, 1.0);
c.rgb          // vec3(0.1, 0.2, 0.3)
c.zyx          // vec3(0.3, 0.2, 0.1)   reversed
c.xx           // vec2(0.1, 0.1)
vec3 gray = vec3(c.g);              // vec3(0.2, 0.2, 0.2) from one value

Arithmetic works component-wise on vectors of the same size, and a scalar can combine with a vector: vec3(1.0, 2.0, 3.0) * 2.0 is vec3(2.0, 4.0, 6.0). Multiplying a matrix by a vector is a real matrix product, which is how a vertex shader applies the transformations of the 3D chapter: uMVP * vec4(aPosition, 1.0).

Built-in functions

GLSL ships with the functions that graphics code uses every day. Most work on scalars and on vectors component by component.

Function What it does
sin, cos, pow, sqrt, abs, floor, fract, mod The usual math; fract(x) is x - floor(x)
min, max, clamp(x, lo, hi) Limit values; clamp(x, 0.0, 1.0) is very common
mix(a, b, t) Linear interpolation a*(1-t) + b*t (the lerp from gradients)
step(edge, x) 0.0 when x < edge, otherwise 1.0
smoothstep(e0, e1, x) A smooth 0-to-1 ramp between two edges; the key to soft edges and antialiasing
length(v), distance(a, b), normalize(v) Vector length, distance, unit vector
dot(a, b), cross(a, b) Dot and cross product
reflect(i, n), refract(i, n, eta) The same formulas from the ray tracing lessons
texture2D(sampler, uv) Read a color from a texture

For example, the Lambert diffuse light from light and reflection is one line: float diffuse = max(dot(normal, lightDir), 0.0);.

Precision and special variables

The fragment shader of WebGL 1 must declare a default float precision, usually precision mediump float; (highp is slower and not guaranteed on older phones). The vertex shader defaults to highp.

A few built-in variables are always available:

  • gl_Position (vertex, output): the clip-space position.
  • gl_PointSize (vertex, output): the size in pixels when drawing POINTS.
  • gl_FragCoord (fragment, input): the pixel's window position in pixels, with the origin at the bottom-left and the center of the first pixel at (0.5, 0.5).
  • gl_FragColor (fragment, output): the color.
  • discard; (fragment statement): throw this fragment away, as if the pixel was not covered.

Sending uniforms from JavaScript

A uniform is declared in the shader and set from JavaScript. Look up its location once, then upload a value every time it changes (while the program is in use):

JavaScript
const timeLoc = gl.getUniformLocation(program, "u_time");
gl.uniform1f(timeLoc, seconds);                 // float
const resLoc = gl.getUniformLocation(program, "u_resolution");
gl.uniform2f(resLoc, canvas.width, canvas.height); // vec2
gl.uniformMatrix4fv(mvpLoc, false, matrixArray);   // mat4 (16 numbers)

The function name encodes the type: uniform1f is one float, uniform3f a vec3, uniform1i an int or a texture unit. A uniform that the shader does not actually use is optimized away, and getUniformLocation returns null for it; that is not an error, just something to remember when debugging.

A fragment shader as a function of pixels

A fragment shader is a pure function from a pixel position (and some uniforms) to a color. That means you can draw entire images, with no geometry beyond a full-screen rectangle, just by writing the formula. The demo below draws two triangles that cover the whole canvas and runs your fragment shader on every pixel. Pick a preset, edit the code in the text area, then press Run (compile errors show in the log, which is exactly what the shader's info log gives you in a real project). Drag Time to change u_time, or tick Animate.

A few ideas to try after running the presets:

  • In the circle shader, change 0.25 (the radius) and the two 0.01 values; making the second smoothstep edge much larger gives a blurry glow instead of a sharp edge.
  • In the ring shader, change 30.0 to a smaller or larger frequency.
  • In the checker shader, replace 8.0 with another count of squares.
  • Break something on purpose, for example delete a semicolon, and read the error message.
Edit a fragment shader live

The whole image is generated by one tiny function. Note the pattern in the circle: normalize the coordinates so they do not depend on the canvas size (gl_FragCoord.xy / u_resolution), center them, compute a distance with length, then use smoothstep to turn a distance into a mask between 0 and 1 and mix it with two colors. A huge share of shader art is a variation on that recipe.

A vertex shader at work

Fragment shaders decide color; vertex shaders decide where things are. The next demo draws a ribbon made of 40 pairs of vertices as a triangle strip. The vertex shader moves each vertex up and down with sin(frequency * x + time), driven by uniforms from the sliders, and passes a color along in a varying. The JavaScript never changes the vertex data: only three uniform values change, and the GPU recomputes all the positions. This is how animated flags, water and grass are done cheaply: the CPU sends a number, the GPU moves thousands of vertices.

A vertex shader makes a wave

Debugging shaders

You cannot console.log from a shader, so the standard technique is to output the value as a color. Want to know whether a normal is correct? Return vec4(normal * 0.5 + 0.5, 1.0), the same trick as the normal view in the ray tracer. Want to see a value between 0 and 1? Return vec4(vec3(value), 1.0). Other habits that help:

  • Always read the info log. Its messages carry line numbers (counted from the start of your shader string).
  • Float literals need decimal points. Integer-to-float conversion is not implicit in WebGL 1.
  • Loops need constant bounds in WebGL 1 (for (int i = 0; i < 8; i++)), and there is no recursion.
  • Avoid if on unpredictable per-pixel values when a mix, step or clamp does the job; branches can slow neighboring pixels that run in lockstep.
  • A uniform you declare but never use disappears. Use it or remove it from your JavaScript.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which qualifier marks a value that is the same for every vertex and pixel in one draw call, and is set from JavaScript?

    A uniform is set with gl.uniform* before the draw and stays constant for the whole call, for example a matrix, a light direction or the time.
  2. 2. What happens to a varying between the vertex shader and the fragment shader?

    Each fragment receives a blend of the three vertex values, weighted by its position in the triangle, with perspective correction.
  3. 3. What does the expression c.zyx do when c is a vec4(0.1, 0.2, 0.3, 1.0)?

    Swizzling picks and reorders components, so zyx gives (0.3, 0.2, 0.1), a reversed vec3.
  4. 4. In WebGL 1 why does 'float x = 1;' fail to compile?

    GLSL ES 1.00 has no implicit int-to-float conversion. A literal that should be a float needs a decimal point.
  5. 5. What does mix(a, b, 0.25) return?

    mix is linear interpolation: a*(1 - t) + b*t. With t = 0.25 the result is closer to a.

Summary

  • The vertex shader outputs gl_Position (and varyings) once per vertex; the fragment shader outputs gl_FragColor once per pixel.
  • attribute is per-vertex input, uniform is constant per draw call and set with gl.uniform*, varying is interpolated from the vertex to the fragment shader.
  • GLSL has float, vec2..vec4, mat2..mat4, sampler2D; swizzling (c.rgb, c.zyx) and component-wise math are central; float literals need a decimal point.
  • mix, step, smoothstep, clamp, length, dot and normalize do most of the work in shaders.
  • A fragment shader is a function from pixel position and uniforms to color, so a full-screen quad is enough to draw images from formulas.
  • Debug by outputting values as colors and by reading the shader info log.

Next, combine buffers, matrices and shaders to draw a lit, spinning model in A Rotating 3D Cube in WebGL.