ch7_Cubemap.html
using your HTML5 internet browser. Once again, this contains a simple textured cube example on top of which we'll build the cube map example. We want to use the cube map to create a reflective-looking surface. loadCubemapFace
and has already been added to the configure
function. Below that function, add the following code which creates and loads the cube map faces:cubeTexture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_CUBE_MAP, cubeTexture); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); loadCubemapFace(gl, gl.TEXTURE_CUBE_MAP_POSITIVE_X, cubeTexture, 'textures/cubemap/positive_x.png'), loadCubemapFace(gl, gl.TEXTURE_CUBE_MAP_NEGATIVE_X, cubeTexture, 'textures/cubemap/negative_x.png'), loadCubemapFace(gl, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, cubeTexture, 'textures/cubemap/positive_y.png'), loadCubemapFace(gl, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, cubeTexture, 'textures/cubemap/positive_y.png'), loadCubemapFace(gl, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, cubeTexture, 'textures/cubemap/negative_y.png'), loadCubemapFace(gl, gl.TEXTURE_CUBE_MAP_POSITIVE_Z, cubeTexture, 'textures/cubemap/positive_z.png'), loadCubemapFace(gl, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, cubeTexture, 'textures/cubemap/negative_z.png'),
draw
function, add the code to bind the cube map to the appropriate sampler:gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_CUBE_MAP, cubeTexture); gl.uniform1i(Program.uCubeSampler, 1);
varying
to the vertex and fragment shader:varying vec3 vVertexNormal;
vVertexNormal = (uNMatrix * vec4(-aVertexPosition, 1.0)).xyz;
uniform samplerCube uCubeSampler;
gl_FragColor = texture2D(uSampler, vTextureCoord) * textureCube(uCubeSampler, vVertexNormal);
ch7_Cubemap_Finished.html
.As you rotate the cube, you should notice that the scene portrayed in the cube map does not rotate along with it, which creates a "mirror" effect in the cube faces. This is due to multiplication of the normals by the normal matrix when assigning the vVertexNormal
varying, which puts the normals in world space.
Using cube maps for reflective surfaces like this is a very common technique, but not the only use for cube maps. Other common uses are for skyboxes or advanced lighting models.
3.145.42.94