Game Development Reference
In-Depth Information
The second change invokes geometry call functions to create vertices, indices,
normals, and UV coordinate arrays, as shown in the following code snippet:
geometry.materials = data.materials;
geometry.verticesFromFaceUvs(data.vertices, data.uvs, 0);
geometry.indicesFromFaces();
Changes in our Geometry object
Open
primitive/Geometry.js
in your favorite editor. We added a new function,
verticesFromFaceUvs
, to re-create vertices from the UV arrays as discussed
previously in the chapter.
Loading a textured object
Let's now load an object with texture mapping exported from Blender. Open
04-Loading-Model-Textures.html
in your editor. The code of the shaders remains
the same as the previous code snippets (
04-SquareWithTexture.html
) of this chapter.
A new attribute,
vec2 aTextureCoord
, to hold texture coordinates and a new varying,
vTextureCoord
, is added to the vertex shader to pass the coordinate to the fragment
shader. In the fragment shader, the code was changed to calculate the new fragment
color value. It is used in the texture access function,
texture2D
, to extract the color
value from the uniform,
uSampler
, as shown in the following code snippet:
gl_FragColor = vec4(iColor, 1.0)*texture2D(uSampler,
vec2(vTextureCoord.s, vTextureCoord.t));
In the main control code for the textured object, the load model function takes the
URL of the JSON model. It first invokes the
parseJSON
function which returns the
geometry object pre-populated with the vertex data information. Then, it retrieves
the texture URL from the geometry object,
geometry.materials[materialIndex].
mapDiffuse
, and it invokes
initTexture
with the texture URL. The
initTexture
function loads the texture and sets global parameters such as
gl.UNPACK_FLIP_Y_
WEBGL
to flip the texture to match the texture coordinates of WebGL in the
handleTextureLoaded
function. Then, the code loads the texture into the GPU
memory and sets texture parameters, as shown in the following code snippet:
function initTextures(imageMap) {
texture = gl.createTexture();
image = new Image();
image.onload = function() { handleTextureLoaded(image, texture);
}
image.src = path+imageMap;
}