Generating Mipmaps

WebGL doesn't automatically create mipmaps for every texture; so, if we want to use one of the *_MIPMAP_* filter modes, we have to create the mipmaps for the texture first. Fortunately, all this takes is a single function call:

gl.generateMipmap(gl.TEXTURE_2D);

generateMipmap must be called after the texture has been populated with texImage2D and will automatically create a full mipmap chain for the image.

Alternatively, if you want to provide the mipmaps manually, you can always specify that you are providing a mipmap level rather than the source texture when calling texImage2D by passing a number other than 0 as the second parameter:

gl.texImage2D(gl.TEXTURE_2D, 1, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, mipmapImage);

Here, we're manually creating the first mipmap level, which is half the height and width of the normal texture. The second level would be a quarter of the dimensions of the normal texture, and so on.

This can be useful for some advanced effects or when using compressed textures that cannot be used with generateMipmap.

If you are familiar with WebGL 1, you'll remember its limit that textures with dimensions that were not a power of two (not 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, and so on) could not use mips and could not repeat. In WebGL 2, these restrictions are gone.

Non Power of Two (NPOT)

In order to use mipmaps with a texture in WebGL 1, mipmaps need to satisfy some dimension restrictions. Namely, the texture width and height must both be Powers of Two (POT). That is, the width and height can be pow(2, n) pixels, where n is any integer. Examples are 16px, 32px, 64px, 128px, 256px, 512px, 1024px, and so on. Also, note that the width and height do not have to be the same as long as both are powers of two. For example, a 512x128 texture can still be mipmapped. NPOT textures can still be used with WebGL 1, but are restricted to only using NEAREST and LINEAR filters.

Why, then, is power restricted for two textures? Recall that the mipmap chain is made up of textures whose sizes are half the previous level. When the dimensions are powers of two, this will always produce integer numbers, which means that the number of pixels never needs to be rounded off, and hence produces clean and fast scaling algorithms.

For all of the texture code samples after this point, we'll be using a simple texture class that cleanly wraps up the texture's download, creation, and setup. Any textures created with the class will automatically have mipmaps generated for them and be set to use LINEAR for the magnification filter and LINEAR_MIPMAP_LINEAR for the minification filter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.178.157