Game Development Reference
In-Depth Information
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA,
gl.UNSIGNED_BYTE, img);
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);
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.enable(gl.DEPTH_TEST);
drawScene();
}
In the
handleTextureLoaded
function, we invoke
drawScene
after the texture is loaded. That is not what
we will do in our real game. We will invoke
drawScene
at a particular frame rate which means it will be invoked
continually. Also, we will load multiple textures, and we can
wait for all textures to get loaded before we start rendering.
The
drawScene
function is modified to initialize the shader variables. In the
following code, we have added two new variables, one attribute,
aTextureCoord
,
in the vertex shader and the other uniform,
uSampler
, in the fragment shader. The
first line makes
verticesTextureBuffer
the current buffer by the
bindBuffer
call.
Then, the
vertexAttribPointer
function is invoked to map the buffer to the shader
variable,
aTextureCoord
, through its reference
textureCoordAttribute
. The next
lines are interesting. WebGL can deal with up to 32 textures during any given call to
functions such as
gl.drawElements
. These textures are numbered from
TEXTURE0
to
TEXTURE31
. The first line tells WebGL that texture
0
is the one we loaded, and
the second line defines the current texture object. The third line passes the value
0
to a shader uniform. In other words, the uniform shader,
uSampler
, will hold the
reference to the first texture, as shown in the following code:
function drawScene() {
...
gl.bindBuffer(gl.ARRAY_BUFFER, verticesTextureBuffer);
gl.vertexAttribPointer(shaderProgram.textureCoordAttribute, 2,
gl.FLOAT, false, 0, 0);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.uniform1i(gl.getUniformLocation(shaderProgram,
"uSampler"), 0);
...
}