Mapping Vertices to Texels
A texture looks like it has been pasted or wrapped onto the surface model. In a sense, the opposite happens. The 3D models gets flattened or unwrapped onto the 2D texture. Each vertex lands somewhere on the texture. The 2D coordinates of a vertex's location on the texture are called texture coordinates. These texture coordinates are stored as vertex attributes, just like positions and normals.
Sometimes multiple resolutions of a texture are provided. When the viewer is close to the texture or when the graphics card is a beast, a high-resolution version of the texture is used. When the viewer is too far away from the texture to see detail or if the graphics card is an underachiever, a low-resolution version is used. So that the same texture coordinates can be applied to either resolution, the coordinates are stored not as absolute indices but as proportions in [0, 1].
Consider this square, whose spatial positions span [-1, 1] but whose texture coordinates span [0.2, 0.8]:
const positions = [
-1, -1, 0,
1, -1, 0,
1, 1, 0,
-1, 1, 0,
];
const texPositions = [
0.2, 0.2,
0.8, 0.2,
0.8, 0.8,
0.2, 0.8,
];
const attributes = new VertexAttributes();
attributes.addAttribute('position', 4, 3, positions);
attributes.addAttribute('texPosition', 4, 2, texPositions);
const positions = [ -1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0, ]; const texPositions = [ 0.2, 0.2, 0.8, 0.2, 0.8, 0.8, 0.2, 0.8, ]; const attributes = new VertexAttributes(); attributes.addAttribute('position', 4, 3, positions); attributes.addAttribute('texPosition', 4, 2, texPositions);
The texture-mapped square appears in the left panel of this renderer, and the same square is shown unwrapped and in wireframe in the right panel:
Note how the texture coordinates of 0.2 and 0.8 inset the unwrapping by 20% on each side. Drag the vertices around to alter the texture coordinates and see how the textured view changes. In particular, try the following:
- unwrap the square to the entire crate texture
- make the square's two triangles coincide on the texture
- collapse one of the triangles to a line
- unwrap the square to a small corner of the crate texture
Observe that changing a vertex's texture coordinates has no impact on its spatial properties—only its color. The square steadfastly remains a square, even if its unwrapping is not a square.
Unwrapping a square onto a texture does not require much effort or imagination since it is already flat. Sophisticated models require a more surgical approach and are usually unwrapped in a 3D modeling application, where a mixture of algorithms and manual editing are used to place vertices on the texture.