Game Development Reference
In-Depth Information
Before we start making changes to the code, let's first revise a few concepts from
Chapter 4 , Applying Textures :
• To apply textures, we need another Vertex Buffer Object that holds the
texture coordinates.
• Each texture coordinate for a 2D texture is represented by an (s, t) or (u, v)
pair and is called a texel.
We pass our texture to GPU memory, and then activate it using the
following code:
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D,
stage.textures[stage.stageObjects[i].textureIndex].texture);
gl.uniform1i(gl.getUniformLocation(shaderProgram, "uSampler"),
0);
WebGL can handle up to 32 textures in a single drawElements call. In the
previous code, we activate the first object and assign our texture data to that
object. Then, we assign the bound texture to the uSampler uniform of our
shader by referencing its index (TEXTURE0 → 0).
We read our texture data in our fragment shader using the shader function
texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)) .
vTextureCoord is a varying vector passed from the vertex shader to the
fragment shader. The following line of code is taken from the vertex shader:
vTextureCoord = aTextureCoord;
We simply assign the texture coordinate from the vertex shader to the
fragment shader. Okay, why don't we pass the value directly to the fragment
shader if we are not manipulating its value in the vertex shader? Well, we
pass them to the vertex shader since the texture coordinates are defined per
vertex. We only pass data to fragment shader that are defined per primitive.
• The number of texture coordinates must be equal to the number of vertices of
an object as each texture coordinate is mapped to a vertex and vice versa.
• The converted JSON file from an OBJ file has a uv array and a vertices
array. The relation between them is encoded in the faces array. We used an
algorithm ( geometry.verticesFromFaceUvs ) to create redundant vertices
and texture coordinates so that the number of vertices is equal to the number
of uv coordinates.
 
Search WWH ::




Custom Search