2 - Hello World
Chapter 2 - Hello World
In chapter 2 of the Book of Shaders we are introduced to the GLSL shading language:
- GLSL is based on the C programming language. Some of the similarities and differences can be seen here.
- Like C, every GLSL has a
void main()
function that is automatically invoked. - The standard C primitive types are availabe like
float
,int
, andbool
, but we also get new built-in types like those for 2d, 3d, and 4d vectors (vec2
,vec3
,vec4
). - The vector types group 2, 3 or 4 normalized floats (range 0.0 to 1.0). A common use for
vec4
is to represent a colour with a R, G, B and alpha value. - Floating point precision can be specified. Lower precision means higher speeds at the cost of quality:
precision lowp float;
precision mediump float;
precision highp float;
- C-style preprocessor macro are also available for
#define
-ing globals and pre-compile conditional (#ifdef
/#endif
). - The built in variable
gl_Fragcolor
represents the colour that will be assigned to every pixel in your image.
Building a Red Hot Shader
Let's write a simple shader that assigns every pixel in our image the colour red:
Shader Output
Differing GLSL Implementations
โ ๏ธ Warning: Depending on the implementation GLSL variables will not always auto-cast. So the following version of our all red shader might not work:
For each of the WebGL targetted GLSL shader I create I'd also like to create a ShaderToy port. I'll try my best to document the differences between the implementation and perhaps I'll create a naive regexp-based source code converter, to aid this porting.
ShaderToy is an amazing community of GLSL shader artists with built-in source code editor. Inspiration galore!
For an example of the kind of work you can discover on ShaderToy check out this "day/night cycle of a mountain tree in the wind" shader by ShaderToy user Maurogik. Realize that geometry for the entire scene (the tree, the leaves, the grass, the mountains, the clouds), along with the raymarched lighting and shadow map, are all written in GLSL.
Next up we'll explore uniform and varying shader inputs.