Vertex shader
To write a shader program you need to use GLSL which stands for “OpenGL Shading Language”. GLSL is coming with WebGL out-of-the-box, so you don't need to mess with some third party libraries for that.
The simplest vertex shader looks like this:
#version 300 es
precision highp float;
in vec2 position;
void main(void)
{
gl_Position = vec4(position, 0.0, 1.0);
}
Let's see what's going on here. First, we should specify GLSL version we'd like to use:
#version 300 es
Next, we should specify a precision of float-point numbers. There are three options available: lowp
, mediump
and highp
.
precision highp float;
The next step is to specify an input data format. In the example above all per-vertex data is just a 2D vector. This data will come from GPU buffer which we've talked about in the previous lesson:
in vec2 position;
And finally, the main
function:
void main(void)
{
gl_Position = vec4(position, 0.0, 1.0);
}
This function converts whatever were passed as input data into a relative screen-space (or a clip-space) coordinates. gl_Position
is a built-in variable where you should put a four-components vector with clip-space coordinates. First two coordinates of this vector is relative screen x
and y
coordinates. We will discuss the meaning of the rest of coordinates a bit later.
Now, let's get back to JavaScript and compile the vertex shader program above. To make things easier we'll put the source code into textarea
element. Just for fun:
<textarea id="vs">
#version 300 es
precision highp float;
in vec2 position;
void main(void)
{
gl_Position = vec4(position, 0.0, 1.0);
}
</textarea>
<!-- ... -->
<script type="text/javascript">
const canvas = document.getElementById("canvas");
const gl = canvas.getContext("webgl2");
const vs = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vs, document.getElementById("vs").value);
gl.compileShader(vs);
if(!gl.getShaderParameter(vs, gl.COMPILE_STATUS))
{
alert(gl.getShaderInfoLog(vs));
}
else
{
alert("Vertex shader has been successfully compiled!");
}
</script>
So, what did we do here. First — we created a vertex shader object:
const vs = gl.createShader(gl.VERTEX_SHADER);
Second — we set its source code, a program, written in GLSL which we kept in our textarea
element (just for fun!):
gl.shaderSource(vs, document.getElementById("vs").value);
Third — we compiled it:
gl.compileShader(vs);
And after that — we checked if a compilation has been completed without any issues. If there were some issues then we alerted their description. If not — just alerted that everything is fine:
// Check for the compilation status
if(!gl.getShaderParameter(vs, gl.COMPILE_STATUS))
{
// The compilation has failed: alert the compilation log:
alert(gl.getShaderInfoLog(vs));
}
else
{
// There were no compilation errors, yay!
alert("Vertex shader has been successfully compiled!");
}
The first step is done! Let's go to the second one.