3
votes

In this tutorial author displays a cube by defining its 6 faces (6*4 vertices) and then telling webgl about triangles in each face.

Isn't this wasteful? Wouldn't it be better to define just 8 vertices and tell webgl how to connect them to get triangles? Are colors shared by multiple vertices a problem?

To make my concern evident: if the author defines triangles with indices array, why does he need so many vertices? He could specify all triangles with just 8 vertices in the vertex array.

2

2 Answers

5
votes

Author of the example here. The issue is, as you suspected, to do with the colouring of the cube.

The way to understand this kind of code most easily is to think of WebGL's "vertices" as being not just simple points in space, but instead bundles of attributes. A particular vertex might be be the bundle <(1, -1, 1), red>. A different vertex that was at the same point in space but had a different colour (eg. <(1, -1, 1), green>) would be a different vertex entirely as far as WebGL is concerned.

So while a cube has only 8 vertices in the mathematical sense of points in space, if you want to have a different colour per face, each of those points must be occupied by three different vertices, one per colour -- which makes 8x3=24 vertices in the WebGL sense.

It's not hugely efficient in terms of memory, but memory's cheap compared to the CPU power that a more normalised representation would require for efficient processing.

Hope that clarifies things.

3
votes

You can use Vertex Buffer Objects (VBO). See this example. They create a list of Vertices and and a list of Indexes "pointing" to the vertices (no duplication of vertices).