OpenGL Shader Language (GLSL)

Part of OpenGL since OpenGL 2.0 (i.e. available in compatibility profile)

OpenGL API introduces new functions to deal with shaders

#version 450 core /* version number profile */

Syntax

Primitives

Constructors

Matrices are specified in column-major order.

Accessors

Component Accessors Description
x,y,z,w Positions
r,g,b,a Colors
s,t,p,q Texture coordinates
mat4 m = mat4(2.0);
vec4 zVec = m[2];
float yScale = m[1][1]; // or m[1].y

Swizzling

vec3 red3 = color.rrr; // multiplying
color = color.abgr; // reordering

Arrays

float coeff[3] = float[3](2.38, 3.14, 0.0);

for (int i = 0; i < coeff.length(); i++)
    coeff[i] *= 2.0;

Structures

struct Particle {
	float lifetime;
	vec3 position;
	vec3 velocity;
}
Particle p = (1.0, vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 1.0));
pos = p.position;

Storage Qualifiers

How to pass uniforms:

GLint uniformLocations[n];
uniformLoations[0] = glGetUniformLocation(CurrShaderProgObj, "NameOfMatrixUniform");
uniformLoations[1] = glGetUniformLocation(CurrShaderProgObj, "NameOfFloatVecUniform");
...

glUniformMatrix4fv(uniformLocations[0], 1, isTranspose, &matrix[0][0]);
glUniform4fv(uniformLocations[1], 1, &vector[0]);

Overloaded Operators

important: matrix vector multiplication

vec3 v, u;
mat3 m;

u = v * m; // u.x = dot(v, m[0]), u.y = dot(v, m[1]), u.z = dot(v, m[2])
mat3 n;
n = m * v; // usual Mv matrix * vector

Control flow

No recursion allowed.

Return Types

GLSL has no concept of pointer/reference. Functions are thus called by value-return (copied in/out, read-only/read-write).

Built-in Variables

Vertex Shader

in int gl_VertexID;
in int gl_InstanceID;

out gl_PerVertex { // this is not a struct!
	vec4 gl_Position; // most important. is the *clip space position*
    float gl_PointSize;
    float gl_ClipDistance;
}

Fragment Shader

in vec4 gl_FragCoord; // window space coordinates
// z is the z-depth value.
// w is -z_e (z_e is the z coordinate of the fragment in eye space)
in bool gl_FrontFacing;

out float gl_FragDepth; // default: gl_FragCoord.z