Meshes

Topology

To draw a shape to the WebGL canvas, we need to prepare the data in a special format called a mesh. In its simplest form, a mesh is a collection of points and a topology.

  • A point is also called a vertex (or vertices in the plural form). A vertex will contain at least a position, but can also include other data like a color, a texture coordinate, a normal, etc. We will learn what all these terms mean in future lessons. For now just remember that although many people will interchange “vertex” and “position”, these are not actually the same thing.
  • The topology defines the structure of the mesh. This basically tells the computer how to connect the list of vertices together.

In p5.js, we define a new mesh using beginShape() and endShape(). We define the vertex positions using vertex() calls between beginShape() and endShape().

The types of topology available is dependent on the framework (e.g. p5.js, three.js) and the renderer (e.g. P2D, WebGL). In p5.js, we have a few options to play with.

In older versions of p5.js, you will notice that QUADS and QUAD_STRIP do not work with WebGL. Indeed, WebGL is built to render points, lines, and triangles only. Whenever a quad or more complex shape is rendered in WebGL, it will just consist of triangles stitched together under the hood.

Exercise

Create a WebGL p5.js sketch, and draw the outline of a square using TRIANGLES and TRIANGLE_STRIP topology. Include a toggle in your code to switch from one to the other. It might help to draw the shape on paper before writing any code!

You can fork this CodeSandbox template to get started.

Triangle Frame

The _FAN and _STRIP versions of the lines and triangles can save a lot of memory. Notice in the exercise above that drawing the frame using TRIANGLES requires 24 vertices and using TRIANGLE_STRIP only requires 10 vertices. However, these are not used very often because they can be tricky to figure out and because there are alternative ways to have efficient meshes, which we’ll see in later classes.

Vertex Attributes

The elements that are part of a vertex are called attributes. So far, we have been using vertices with a single attribute, the position. Another type of attribute we can include is the vertex color. In p5.js, calling fill() before each vertex() will set the color for that point.

Using different colors per vertex result in a nice gradient. This is because WebGL interpolates the attribute values between vertices. The same thing is actually happening with the positions; even though we only give the renderer three points, we end up with a triangle. The renderer connects the triangle shape by interpolating the positions between the three values.