Sub topic 6
Storing a mesh: vertex list plus face index lists
This chapter covers the indexed face set, the most common way to store a polygon mesh in memory and on disk. It assumes you can read simple Python, know what (x, y, z) coordinates are, and have met vectors and the cross product at an introductory level. The chapter before this one separated geometry (where the points are) from topology (how the points connect). Here you will see how a data structure keeps those two things apart.
The problem with storing faces as raw points
The simplest way to store a mesh is to write out every face as a list of coordinates. A cube then becomes six faces with four corner positions each, which is 24 positions.
That has three costs.
- Duplication. A cube has only 8 distinct corners, but each corner appears in three faces, so every position is stored three times.
- Drift. If you move a corner, you must find and update every copy. Miss one and the faces no longer meet, which leaves a visible crack.
- No connectivity. To ask which faces touch a given corner, you have to compare floating-point coordinates for equality. Rounding makes that comparison unreliable.
The indexed face set removes all three problems by storing each position once and letting faces refer to positions by number.
The two arrays
An indexed face set has two parts:
- A vertex list: an array of positions. The position of a vertex in the array is its index, counting from 0.
- A face list: an array of faces. Each face is a short list of vertex indices, in order around the face boundary.
The vertex list holds the geometry. The face list holds the topology. Moving a vertex means changing one entry in the vertex list, and every face that uses it follows automatically.
# A unit cube as an indexed face set.
# Each vertex is an (x, y, z) position; each face lists vertex indices
# counter-clockwise when viewed from outside the cube.
vertices = [
(0, 0, 0), # 0
(1, 0, 0), # 1
(1, 1, 0), # 2
(0, 1, 0), # 3
(0, 0, 1), # 4
(1, 0, 1), # 5
(1, 1, 1), # 6
(0, 1, 1), # 7
]
faces = [
(0, 3, 2, 1), # bottom (z = 0)
(4, 5, 6, 7), # top (z = 1)
(0, 1, 5, 4), # front (y = 0)
(3, 7, 6, 2), # back (y = 1)
(0, 4, 7, 3), # left (x = 0)
(1, 2, 6, 5), # right (x = 1)
]Take the top face, (4, 5, 6, 7). Looking up those indices gives the positions (0,0,1), (1,0,1), (1,1,1) and (0,1,1). All four have z = 1, so the face lies in the plane z = 1, as the comment says.
In the diagram, vertices 4 and 5 receive arrows from both faces. That sharing is how the data records that the top and front faces meet along the edge from vertex 4 to vertex 5.
Why indices instead of copies
Sharing by index gives you several properties for free.
- Compactness. Each position is stored once. For a typical closed triangle mesh, each vertex is used by about six triangles, so indices save a lot of memory. An index is usually 4 bytes, while a position of three 32-bit floats is 12 bytes.
- Consistent editing. Moving vertex 5 moves it in every face that uses it.
- Exact connectivity. Two faces are neighbors at a vertex if they contain the same integer. Integer comparison is exact, unlike comparing floats.
Edges are implied
The structure above has no edge array. Each edge is a pair of consecutive vertices in some face, and the last vertex of a face connects back to the first. You can derive the edge set when you need it.
def edges_of(faces):
"""Return the set of unique undirected edges implied by the faces."""
edges = set()
for face in faces:
for i in range(len(face)):
a = face[i]
b = face[(i + 1) % len(face)]
edges.add((min(a, b), max(a, b)))
return edges
edges = edges_of(faces)
V, E, F = len(vertices), len(edges), len(faces)
print(V, E, F) # 8 12 6
print(V - E + F) # 2Two details matter here.
(i + 1) % len(face)wraps the last index back to 0, which closes the loop of the face boundary.(min(a, b), max(a, b))turns the directed pair into an undirected one. Edge 0 to 1 and edge 1 to 0 are the same edge. The cube's top and front faces both contain it, once in each direction, and the set keeps a single copy.
The counts are 8 vertices, 12 edges and 6 faces. The value V − E + F = 2 is Euler's formula for a closed surface shaped like a sphere. A later chapter covers it in detail. For now, it is a quick check that the arrays describe what you meant.
Faces of different sizes
Because each face is its own index list, faces do not need to share a size. A single mesh can mix triangles, quads and larger polygons.
# A square pyramid: one quad base and four triangular sides.
pyramid_vertices = [
(0, 0, 0), # 0 base corner
(1, 0, 0), # 1 base corner
(1, 1, 0), # 2 base corner
(0, 1, 0), # 3 base corner
(0.5, 0.5, 1) # 4 apex
]
pyramid_faces = [
(0, 3, 2, 1), # base (quad), seen from below
(0, 1, 4), # side (triangle)
(1, 2, 4), # side (triangle)
(2, 3, 4), # side (triangle)
(3, 0, 4), # side (triangle)
]
print(len(edges_of(pyramid_faces))) # 8Here V = 5, E = 8 and F = 5, and 5 − 8 + 5 = 2 again.
This flexibility is why modeling tools such as Blender store meshes this way. Artists work with quads and n-gons, which are polygons with more than four sides. Rendering hardware wants triangles, so a later step splits larger faces. That step is called triangulation.
A common variation: flat arrays
Python tuples are good for reading and teaching. Production code usually keeps the same data in flat numeric arrays, because they are compact and can be uploaded directly to a graphics card.
# The cube's vertices flattened to a single list: x0, y0, z0, x1, y1, z1, ...
flat_positions = [c for v in vertices for c in v]
# Faces flattened, with offsets marking where each face begins.
flat_indices = []
face_starts = []
for face in faces:
face_starts.append(len(flat_indices))
flat_indices.extend(face)
print(flat_positions[:6]) # [0, 0, 0, 1, 0, 0]
print(face_starts) # [0, 4, 8, 12, 16, 20]To read face k back, slice from face_starts[k] up to face_starts[k + 1], or to the end of the array for the last face. The information is the same as before, only laid out differently.
Indices, order and winding
The order of indices within a face matters. The cube's faces are listed counter-clockwise when seen from outside. That order, called the winding, decides which side of the face counts as the front. The next chapter covers winding order and normals. For now, treat the order as part of the data. Rotating a face's starting point, such as (0, 1, 5, 4) to (1, 5, 4, 0), describes the same face. Reversing it, such as (4, 5, 1, 0), flips which side is the front.
Common errors
These are the mistakes people make most often with an indexed face set.
| Mistake | Symptom | How to catch it |
|---|---|---|
| Index out of range | `IndexError` in Python, or a crash or garbage in native code | Check that every index satisfies `0 <= i < len(vertices)` |
| Off-by-one indexing | Faces connect the wrong corners, or the mesh looks twisted | Remember that formats such as OBJ count from 1, while arrays count from 0 |
| Duplicate vertices | Mesh looks fine but has cracks when edited, and edge checks report boundary edges | Merge vertices that share a position within a tolerance |
| Repeated index in one face | Zero-length edge and a degenerate face, such as `(0, 1, 1)` | Reject faces whose indices are not all distinct |
| Fewer than 3 indices | A face with no area | Require at least 3 indices per face |
| Unused vertices | Wasted memory, and vertices that belong to no face | Count how many faces use each index |
The off-by-one row deserves attention. The Wavefront OBJ format numbers vertices from 1, so a loader that forgets to subtract 1 shifts every face by one vertex. It also fails on the last vertex with an out-of-range index.
A short validator catches the first, fourth and fifth rows.
def validate(vertices, faces):
"""Return a list of problems found in an indexed face set."""
problems = []
n = len(vertices)
used = set()
for k, face in enumerate(faces):
if len(face) < 3:
problems.append(f"face {k} has fewer than 3 vertices")
if len(set(face)) != len(face):
problems.append(f"face {k} repeats a vertex")
for i in face:
if not 0 <= i < n:
problems.append(f"face {k} uses out-of-range index {i}")
else:
used.add(i)
for i in sorted(set(range(n)) - used):
problems.append(f"vertex {i} is not used by any face")
return problems
print(validate(vertices, faces)) # []
print(validate(vertices, [(0, 1, 1), (0, 1, 9), (2, 3)]))The second call prints a list that reports a repeated vertex in face 0, an out-of-range index 9 in face 1, and a face with fewer than three vertices in face 2. It also reports vertices 4 to 7 as unused, along with any other vertex those three faces do not touch.
Trade-offs of the indexed face set
The indexed face set is simple and compact, and it is the usual interchange format, but it has limits.
- Neighbor queries are slow. To find the faces around a vertex, you must scan the whole face list. Fast adjacency needs extra structures, such as the half-edge structure covered in the last chapter.
- One position per vertex. Attributes that differ between faces at the same corner, such as a sharp-edge normal or a texture seam, force the vertex to be split. The vertex attributes chapter explains this.
- No guarantee of validity. The format will accept a mesh with holes, flipped faces or edges shared by three faces. Checking for those problems is a separate step, covered in the chapters on boundaries and manifolds.
Exercise
A mesh has these vertex indices for two quads: face A is (0, 1, 2, 3) and face B is (3, 2, 4, 5). How many unique undirected edges do the two faces have in total, and which edge do they share?
Show answer
Face A has edges 0-1, 1-2, 2-3 and 3-0. Face B has edges 3-2, 2-4, 4-5 and 5-3. The edge 2-3 appears in both, as 2→3 in A and 3→2 in B, so it counts once. The total is 4 + 4 − 1 = 7 unique edges, and the shared edge is (2, 3).
Exercise
A loader reads a file in which vertices are numbered from 1 and passes the indices straight into a 0-based Python list of 8 vertices. What goes wrong, and what is the fix?
Show answer
Every face refers to the vertex one position too far along, so the mesh is distorted. A face that uses the file's last vertex, number 8, raises an IndexError because the list only has indices 0 to 7. The fix is to subtract 1 from every index when loading.