Game Development Reference
In-Depth Information
dartboardVertexPositionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, dartboardVertexPositionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
dartboardVertexPositionBuffer.itemSize = 3;
dartboardVertexPositionBuffer.numItems = (dartboard_sections + 1);
dartboardVertexTexCoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, dartboardVertexTexCoordBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(texCoords), gl.STATIC_DRAW);
dartboardVertexTexCoordBuffer.itemSize = 2;
dartboardVertexTexCoordBuffer.numItems = (dartboard_sections + 1);
}
In Listing 7-22, we create a circular shape comprised of triangular sections by programmatically computing
coordinates. We could have textured the square enclosure of the dartboard with only two triangles using a
texture that had a transparent background. However, if we wanted to texture every n th section or blend
color or discard certain regions, then the triangles are essential. If we are combining lighting operations
with a texture, then accurate vertex points are also important.
Each (x, y) coordinate will be in the range -1 to 1. To generate the corresponding texture coordinate, we
then divide each (x, y) coordinate by 2 and add .5. This clamps the texture coordinate (s, t) to the range of
0 and 1. Next, to load our texture image and set the type of filtering, we need the code in Listing 7-23.
Listing 7-23. Loading and Initializing Our Texture
function initTexture(){
dartboardTexture = gl.createTexture();
dartboardTexture.image = new Image();
dartboardTexture.image.onload = function() {
handleLoadedTexture(dartboardTexture)
}
dartboardTexture.image.src = "dartboard.gif";
}
function handleLoadedTexture(texture) {
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE,
texture.image);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.bindTexture(gl.TEXTURE_2D, null);
}
Now, we have generated texture coordinates and want to texture the dartboard. We just want to color our
dart in this example and so we have two options. We can use a single shader program and set a uniform
flag that determines whether we want the shader to use a texture for each object in our scene, or we can
create and bind multiple shader programs, switching them as needed. We will go with the second option.
The following code modification redefines our variables as arrays:
COLOR_SHADER = 0,
TEXTURE_SHADER = 1,
 
Search WWH ::




Custom Search