WebGL 1.0 is compatible with OpenGL ES 2.0, and permits GPU programming in GLSL ES, the OpenGL Shading Language for Embedded Systems.
GLSL resembles C++. It's statically typed and lexically scoped with curly brace block structure and semicolon statement endings.
Every GLSL program includes two shaders, the vertex shader and the fragment shader.
Every shader should configure its precision by including the following line near the top.Both the vertex and fragment shaders begin executing in their
Every vertex shader should write a 4-vector to
gl_Position and every fragment shader should write a 4-vector to
In addition to the C++ types
float, GLSL provides vector types
vec4, and matrix types
mat4, useful for geometric calculation.
mat4 M, A, B;
vec4 u = vec4(0.0, 0.1, 0.2, 0.4);
u.x = 2.0;
Vector element access
u = u + v;
u.xyz = v.zyx
M = 1.0;
Matrix element access
M = A * B;
u = M * v;
Storage qualifiers indicate how variables are used and where their values come from. A declaration with no qualifier is an ordinary variable. Here are some qualified examples.
const float pi = 3.141592;
const declares a variable with a constant value.
uniform mat4 modelMatrix;
uniform declares a variable whose value is set by the application using
gl.uniformMatrix. A uniform variable cannot be modified by the shader.
attribute vec4 vertexPosition;
attribute declares a vertex shader variable whose value is provided by a vertex buffer object. This buffer association is configured by the application using
gl.vertexAttribPointer. An attribute variable cannot be modified by the shader.
varying vec3 fragmentColor;
varying declares a variable that acts an output from the vertex shader and an input to the fragment shader. A varying variable must be set by the vertex shader, and cannot be modified by the fragment shader.
Flow control constructs are identical to C++. Looping:
GLSL includes a large library of useful functions. Here are some of the more heavily-used ones.
Compute the dot product of two vectors.
Compute the cross product of two vectors.
Return the normalization of a vector.
Return the length of a vector.
Raise $x$ to the power $y$.
Compute the square root.
Return the absolute value.
Return largest integer less than or equal.
Return smallest integer greater than or equal.
Return the larger of two values.
Return the smaller of two values.
mix(x, y, a)
Compute the linear interpolation of two values.
Return 1 if $x\geq y$ or 0 otherwise.
Convert degrees to radians.
Convert radians to degrees.
Compute the sine of an angle in radians.
Compute the cosine of an angle in radians.
Compute the inverse sine of an angle in radians.
Compute the inverse cosine of an angle in radians.
All scalar functions operate element-wise on vector arguments.