I’ve been working on an art project with my partner lately and decided that learning WebGL would be a productive use of my time. I learn better when I take notes, so here are my notes.
OpenGL ES 2.0 & WebGL
OpenGL is a low level library for drawing 2D graphics. 3D graphics are accomplished by programmers writing programs to do math, converting the 3D object space into 2D image space.
OpenGL is the API we use to push data to the GPU and execute specialized code there (vs on the CPU). The program that runs on the GPU is called a shader. GPU shaders are written in GLSL. Technically shaders can be written on the CPU too, because they’re technically just “a program that tells a computer how to draw something in a specific and unique way.” But when GPUs are used, this is called hardware acceleration. As you might imagine, the “embarassingly parallel” nature of graphics makes GPUs more efficient / suitable for shaders.
The complete Khronos Working Group spec for WebGL can be found here: Latest WebGL Spec. Khronos managed WebGL; it’s a non-profit formed by a bunch of companies including Nvidia, Intel, and Silicon Graphics. Currently companies like Google are also part of it.
As with all things, at this time of writing the WebGL spec is evolving. WebGL2 is going to enable OpenGL ES 3.0 (whereas WebGL uses OpenGL ES 2.0). The spec can be found here. WebGL2 isn’t going to be entirely backwards compatible either, so beware.
In this post I’m going to record learnings with WebGL, meaning we’ll use shaders written for OpenGL ES 2.0.
Terms for 3D Graphics Programming
Clip Space is the coordinate system used by GPUs. It’s represented as a number (-1, 1) irrespective of the canvas size.
The Pixel Space is how we normally think of raster graphics, where x is the width and y is the height.
The Vertex Shader is the function responsible for converting our 3D inputs into coordinates in clip space to draw on the screen.
The Fragment Shader is the function responsible for determining the color of each pixel we told the GPU to draw via the Vertex Shader.
So for shaders: vertex = location, fragment = color.
According to the Khronos working spec:
Shaders must be loaded with a source string (shaderSource), compiled (compileShader) and attached to a program (attachShader) which must be linked (linkProgram) and then used (useProgram).
Cool! Now we know what methods we need to use from WebGL / OpenGL.
Writing a basic WebGL program