Reading Textures

How to 3D

Chapter 9: Textures

Reading Textures

Just as we saw with 3D models, textures come from two places: file-based assets and procedural generation. Let's first examine how to read in image assets, which are either stored locally on disk or pulled from the network. The files may be made in essentially any program or acquired from cameras and other sensors.

Earlier we wrote fetchImage to read in a heightmap acquired from an elevation dataset. Textures may also be read with this method, like so:

const toastImage = await fetchImage('toast-albedo.png');
const toastImage = await fetchImage('toast-albedo.png');

Fetching should be done only during initialization or in a background task. We don't want to slow down the frame rate when loading assets.

If we have three different images for terrain textures, we might try reading them like this:

const grassImage = await fetchImage('grass.jpg');
const sandImage = await fetchImage('sand.jpg');
const dirtImage = await fetchImage('dirt.jpg');
const grassImage = await fetchImage('grass.jpg');
const sandImage = await fetchImage('sand.jpg');
const dirtImage = await fetchImage('dirt.jpg');

This code will fetch the three images in strict sequence, which might be slow. We speed things up by fetching them in parallel but waiting for them all to finish by awaiting Promise.all:

const [grassImage, sandImage, dirtImage] = await Promise.all([
  fetchImage('grass.jpg'),
  fetchImage('sand.jpg'),
  fetchImage('dirt.jpg'),
]);
const [grassImage, sandImage, dirtImage] = await Promise.all([
  fetchImage('grass.jpg'),
  fetchImage('sand.jpg'),
  fetchImage('dirt.jpg'),
]);

Though the Image constructor we call in fetchImage can decode many different image file formats, there are currently two primary formats with which we should be familiar:

JPG images are small when compressed, but we will be sending the decompressed images to our graphics card. The decompressed images are not any smaller. The only real advantages of JPG are that texture assets take up less space on disk and download faster.

← Detail without TrianglesGenerating Textures →