Game Development Reference
In-Depth Information
}
if (!gl) {
alert("Error trying to initialise WebGL");
} else {
gl.clearColor(0.0, 0.4, 0.0, 1.0);
}
}
To understand the initShaders method, first we need to show how the flow of a shader program works.
Setting up a shader program
For both vertex and fragment shaders, we need to create a shader object, set the source for the shader,
and compile it. Then we create a shader program, attach the compiled vertex and fragment shaders to it,
link the program, and use it.
Note Cleaning up shaders involves the opposite process. You detach the shaders from
the program, then delete the shaders, and finally delete the program.
In the initShaders function at the bottom of Listing 7-6, we load our vertex and fragment shader source
from external files, shader.vs and shader.fs , for our vertex and fragment shaders respectively. Notice that
we set the parameter async: false . This ensures that the source files are fetched before we try to attach
and compile the shaders. We will skip the details of the shader files until after the demo_1.html file is
explained in depth.
Listing 7-6. Setting up Our Shaders
function makeShader(src, type){
var shader = gl.createShader(type);
gl.shaderSource(shader, src);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert("Error compiling shader: " + gl.getShaderInfoLog(shader));
}
return shader;
}
function attachShaders(){
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert("Unable to initialize the shader program.");
}
}
function createShaderProgram(){
shaderProgram = gl.createProgram();
 
Search WWH ::




Custom Search