Algorithm Search⌘K

Data structureintro

Indexed face set

Also called face-vertex mesh, shared vertex representation.

A mesh stored as an array of vertex positions and a list of faces, each given by the indices of its vertices, the form of most mesh files.

Time
O(c) boundary-edgesO(n + c) expected buildO(1 + k) expected edge-faces
Space
Θ(n + c) extra
Where
c = the number of corners, the sum of the face sizes; k = the size of the answer; m = the number of faces; n = the number of vertices

An indexed face set stores a polygon mesh as two lists: an array of vertex positions, and a list of faces, where each face is the list of the indices of its vertices in order. Each vertex is stored once and the faces share it by index. This is the form of most mesh files, such as OFF, OBJ and PLY, and the name comes from the IndexedFaceSet node of VRML. The two lists alone answer "which vertices does this face have" in constant time, but not "which faces are next to this face". This page adds an edge table, a hash table from each undirected edge to the faces that use it, which answers the adjacency queries in expected time proportional to the answer and finds the boundary and non-manifold edges.

In plain words

Think of a model made of flat tiles. You write a numbered list of the corner points of all tiles, with each point written one time. Then, for each tile, you write the numbers of its corners in the order you meet them when you go around the tile. Two tiles that touch use the same numbers for their shared corners.

This is all a mesh file needs. To move a point, you change one line, and every tile that uses it moves with it. To find the tiles next to a given tile, you make a second list: for each side of a tile, which tiles use that side. A side that only one tile uses is on the edge of a hole. A side that three or more tiles use is a place where the surface branches.

The abstract type

The structure holds a mesh with nn vertices and mm faces. A face is a sequence of k≥3k \ge 3 distinct vertex indices. The order gives the orientation: by the convention of most formats, the vertices go counterclockwise when the face is seen from outside, so the outward normal follows the right-hand rule. The operations are:

  • BUILD(V,F)\mathrm{BUILD}(V, F): make the structure from the positions VV and the faces FF.
  • EDGE-FACES(u,v)\mathrm{EDGE\text{-}FACES}(u, v): the faces that have {u,v}\{u, v\} as an edge.
  • FACE-NEIGHBORS(f)\mathrm{FACE\text{-}NEIGHBORS}(f): the faces other than ff that share an edge with ff.
  • VERTEX-FACES(v)\mathrm{VERTEX\text{-}FACES}(v): the faces that have vv as a vertex.
  • BOUNDARY-EDGES\mathrm{BOUNDARY\text{-}EDGES}: the edges that one face uses. NON-MANIFOLD-EDGES\mathrm{NON\text{-}MANIFOLD\text{-}EDGES}: the edges that three or more faces use.
  • EULER\mathrm{EULER}: the Euler characteristic χ=V−E+F\chi = V - E + F of the mesh.

Representation

field meaning
V[0…n−1]V[0 \ldots n-1] the position of each vertex
F[0…m−1]F[0 \ldots m-1] each face as a tuple of vertex indices, in order
EE a hash map from the key (min⁡(u,v),max⁡(u,v))(\min(u, v), \max(u, v)) of each edge to the list of its uses (f,i)(f, i): edge ii of face ff
VF[0…n−1]VF[0 \ldots n-1] for each vertex, the faces that use it

The first two rows are the file. The last two rows are derived from them, and a program builds them after it reads the file. The key of an edge has no direction, so both faces of an edge use the same entry. The index ii in a use tells the direction: face ff goes along the edge from F[f][i]F[f][i] to F[f][i+1]F[f][i+1].

Operations

  1. BUILD(V, F)
  2. 1E ← empty hash map; VF[v] ← empty list for each vertex v
  3. 2for each face f, each corner i = 0 .. |F[f]| − 1 do
  4. 3u ← F[f][i]; v ← F[f][(i + 1) mod |F[f]|]
  5. 4append (f, i) to E[{u, v}]
  6. 5append f to VF[u]
  7. EDGE-FACES(u, v)
  8. 6return the faces of the uses in E[{u, v}], or nothing if there is no entry
  9. FACE-NEIGHBORS(f)
  10. 7for each edge e of f, each use (g, j) in E[e] with g ≠ f and g not yet output do output g
  11. BOUNDARY-EDGES
  12. 8return the keys e of E with |E[e]| = 1
  13. EULER
  14. 9return n − |E| + m

Line L4 puts both directions of an edge in one entry, because the key is the sorted pair. A closed manifold mesh has exactly two uses in each entry. Line L8 lists the edges of the holes, and the same scan with ∣E[e]∣≥3|E[e]| \ge 3 lists the non-manifold edges. Line L9 counts each distinct edge once, because each one is one key of EE.

The edge table can also test the orientation. Two faces that share an edge are oriented the same way exactly when they go along it in opposite directions. Two uses of an edge in the same direction show a flipped face, which consistent mesh orientation repairs.

Example

A unit square made of two triangles, in the OFF format:

OFF
4 2 0
0 0 0
1 0 0
1 1 0
0 1 0
3 0 1 2
3 0 2 3

The header gives 4 vertices and 2 faces. Each face line starts with the number of its vertices. BUILD makes this edge table:

edge uses count
{0,1}\{0, 1\} (0,0)(0, 0) 1
{1,2}\{1, 2\} (0,1)(0, 1) 1
{0,2}\{0, 2\} (0,2)(0, 2), (1,0)(1, 0) 2
{2,3}\{2, 3\} (1,1)(1, 1) 1
{0,3}\{0, 3\} (1,2)(1, 2) 1

The diagonal {0,2}\{0, 2\} has two uses. Face 0 goes along it from 2 to 0 (edge 2 of (0,1,2)(0, 1, 2)), and face 1 goes from 0 to 2 (edge 0 of (0,2,3)(0, 2, 3)). The directions are opposite, so the two faces have the same orientation. FACE-NEIGHBORS(0) is [1][1]. The four other edges are boundary edges, and χ=4−5+2=1\chi = 4 - 5 + 2 = 1, the value for a disk.

The same square as a triangle soup, the form of an STL file, has 6 vertices, with (0,0,0)(0,0,0) and (1,1,0)(1,1,0) written twice, and the faces (0,1,2)(0, 1, 2) and (3,4,5)(3, 4, 5). Now no edge has two uses, the faces have no neighbours, and χ=6−6+2=2\chi = 6 - 6 + 2 = 2: two separate triangles. Vertex welding merges the duplicate points and gives back the first form.

Correctness

The loop of line L2 keeps this invariant: for each edge ee, the entry E[e]E[e] lists, in order, the uses of ee by the corners scanned so far, and EE has no empty entry. Line L4 adds each corner to the entry of exactly its own edge. So at the end, each entry lists all uses of its edge, and the keys are exactly the distinct edges. EDGE-FACES, FACE-NEIGHBORS and BOUNDARY-EDGES read these lists, and EULER counts the keys. The full proof is below.

Proof: The edge table and the vertex table of an indexed face set answer the adjacency queries exactlyfull

Setup. The input is a vertex array of length nn and a face list F=(f0,…,fm−1)F = (f_0, \ldots, f_{m-1}), where each face f=(f[0],…,f[k−1])f = (f[0], \ldots, f[k-1]) has k≥3k \ge 3 distinct indices in {0,…,n−1}\{0, \ldots, n-1\}. Edge ii of ff is the undirected pair {f[i],f[(i+1) mod k]}\{f[i], f[(i+1) \bmod k]\}. Write inc(e)\mathrm{inc}(e) for the list of all pairs (f,i)(f, i) such that edge ii of face ff is ee, in the order of the scan.

Claim. After BUILD (lines L1 to L5):

  1. For each undirected pair ee, the table entry E[e]E[e] is inc(e)\mathrm{inc}(e), and EE has no other keys.
  2. For each vertex vv, VF[v]VF[v] lists the faces that contain vv, each one time, in increasing order.

So EDGE-FACES (line L6) returns the faces on the edge, FACE-NEIGHBORS (line L7) returns exactly the faces other than ff that share an edge with ff, BOUNDARY-EDGES (line L8) returns exactly the edges with one incidence, and line L9 returns V−E+FV - E + F of the cell complex.

Proof of 1. The invariant of the loop of line L2 is: after the faces f0,…,fj−1f_0, \ldots, f_{j-1} and the first ii corners of fjf_j are processed, E[e]E[e] is the list of the pairs of inc(e)\mathrm{inc}(e) that come from those corners, in order, and EE has a key ee only if this list is not empty. It holds at the start, when EE is empty. Line L3 computes edge ii of fjf_j, and line L4 appends (j,i)(j, i) to the entry of exactly that edge, creating the key if it is new. No other entry changes. So the invariant holds after each step, and at the end it is claim 1. The key {u,v}\{u, v\} is normalized to (min⁡,max⁡)(\min, \max), so the two directions of an edge go to the same entry.

Proof of 2. Line L5 appends ff to VF[u]VF[u] once for each corner ii of ff with f[i]=uf[i] = u. The indices of a face are distinct, so this happens exactly once when u∈fu \in f and never otherwise. Faces are processed in increasing order.

The queries. EDGE-FACES reads E[{u,v}]E[\{u, v\}] and drops the corner index, so by claim 1 it returns the faces with {u,v}\{u, v\} as an edge. FACE-NEIGHBORS visits the entry of each edge of ff and keeps each face g≠fg \ne f the first time it appears. A face g≠fg \ne f is returned if and only if some edge of ff has an incidence in gg, that is, if and only if gg and ff share an edge. The set seenseen makes each face appear at most once. BOUNDARY-EDGES keeps the keys whose list has length 1, which by claim 1 are the edges used by exactly one corner of one face.

Euler characteristic. The cell complex of the mesh has one 0-cell for each vertex index, one 1-cell for each distinct undirected edge, and one 2-cell for each face. By claim 1 the keys of EE are exactly the distinct edges, so n−∣E∣+mn - |E| + m is V−E+FV - E + F. A vertex that no face uses is a 0-cell by itself and adds 1, which is the Euler characteristic of a point.

Termination. BUILD runs line L4 once for each corner, that is ∑f∣f∣\sum_f |f| times. Each query loops over a finite list. So every operation stops. ■\blacksquare

Complexity

Let c=∑f∣F[f]∣c = \sum_f |F[f]| be the number of corners. For a triangle mesh c=3mc = 3m.

  • BUILD does cc hash table insertions, so it takes O(n+c)O(n + c) expected time.
  • EDGE-FACES takes O(1+k)O(1 + k) expected time for kk faces on the edge.
  • FACE-NEIGHBORS takes expected time proportional to the number of uses of the edges of ff, which is O(∣f∣)O(|f|) on a manifold mesh.
  • VERTEX-FACES takes time proportional to its answer.
  • BOUNDARY-EDGES and EULER take O(c)O(c) time, or O(1)O(1) for EULER if the sizes are kept.
  • The space is Θ(n+c)\Theta(n + c): the positions, the faces, at most cc edge keys and cc uses.

The bare file form, without EE and VFVF, uses 3n3n numbers for the positions and cc indices for the faces. It is one of the smallest forms with shared vertices. Each adjacency query on it scans all faces, in Θ(c)\Theta(c) time.

Variants

  • Triangle soup. Each face stores its own coordinates, with no shared indices. STL files use this form. It has no adjacency, and vertex welding is needed to make it an indexed face set.
  • Fixed-size faces. For a triangle mesh, the faces are one array of 3m3m indices. This is the index buffer of a graphics card.
  • Corner attributes. OBJ and VRML give each corner its own index into separate normal and texture coordinate arrays, so a vertex can have different normals on the two sides of a crease.
  • Edge-based structures. The corner table adds one array of opposite corners to a triangle index array. The doubly connected edge list, the half-edge form, and the winged-edge structure store the adjacency explicitly and allow local edits in constant time.

When to use it

Use it to store and exchange meshes, and to draw them. It is the input of almost every mesh algorithm, and it can hold any mesh, also a mesh with non-manifold edges, holes and flipped faces. Use the edge table when you need adjacency once, for example to find holes, to check that a mesh is closed, or to build a better structure. If a program walks over the mesh many times, or edits it, change to a corner table or a half-edge structure.

Pitfalls

  • Indices from 0 or 1. OFF counts vertices from 0, and OBJ counts them from 1 and allows negative indices from the end. A wrong base moves every face by one vertex.
  • Duplicate vertices. A file can have two vertices at the same position. The faces then do not share an edge, and the mesh looks closed but has holes in its topology. Weld first.
  • Degenerate faces. A face can repeat an index, or have collinear vertices. The structure on this page rejects a repeated index. Collinear vertices give a zero normal and break later geometric tests.
  • The edge count of the OFF header. Many writers put 0 there. Do not trust it. Count the keys of EE.
  • Directed edge keys. A key (u,v)(u, v) with a direction puts the two faces of an edge in different entries, and every edge looks like a boundary edge.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

indexed_face_set.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/indexed-face-set/. The authors are listed in prov/A865QN.jsonl.

"""An indexed face set: vertex positions and faces given as lists of vertex indices.

The class adds an edge table (a hash map from each undirected edge to the
faces that use it) and a vertex-to-face table, so that the adjacency queries
take time proportional to the size of their answer. It also reads and writes
the OFF file format.
"""

from typing import Iterator, Sequence

Edge = tuple[int, int]


def edge_key(u: int, v: int) -> Edge:
    """The key of the undirected edge {u, v}."""
    return (u, v) if u < v else (v, u)


class IndexedFaceSet:
    """Vertices and polygonal faces, with edge and vertex incidence tables."""

    def __init__(self, vertices: Sequence[Sequence[float]], faces: Sequence[Sequence[int]]) -> None:
        """Build the tables. Each face needs at least 3 distinct vertex indices in range."""
        n = len(vertices)
        self.vertices: list[tuple] = [tuple(p) for p in vertices]
        self.faces: list[tuple[int, ...]] = []
        self.edges: dict[Edge, list[tuple[int, int]]] = {}  # @line L1
        self.vertex_face: list[list[int]] = [[] for _ in range(n)]
        for f, face in enumerate(faces):  # @line L2
            face = tuple(face)
            if len(face) < 3 or len(set(face)) != len(face) or min(face) < 0 or max(face) >= n:
                raise ValueError(f"face {f} is not a valid polygon: {face}")
            self.faces.append(face)
            k = len(face)
            for i in range(k):
                u, v = face[i], face[(i + 1) % k]  # @line L3
                self.edges.setdefault(edge_key(u, v), []).append((f, i))  # @line L4
                self.vertex_face[u].append(f)  # @line L5

    def edge_faces(self, u: int, v: int) -> list[int]:
        """The faces that use the edge {u, v}, with repeats if a face uses it twice."""
        return [f for f, _ in self.edges.get(edge_key(u, v), [])]  # @line L6

    def face_edges(self, f: int) -> Iterator[Edge]:
        face = self.faces[f]
        k = len(face)
        for i in range(k):
            yield edge_key(face[i], face[(i + 1) % k])

    def face_neighbors(self, f: int) -> list[int]:
        """The faces other than f that share an edge with f, each listed once."""
        out: list[int] = []
        seen = {f}
        for e in self.face_edges(f):  # @line L7
            for g, _ in self.edges[e]:
                if g not in seen:
                    seen.add(g)
                    out.append(g)
        return out

    def vertex_faces(self, v: int) -> list[int]:
        """The faces that have v as a vertex."""
        return list(self.vertex_face[v])

    def boundary_edges(self) -> list[Edge]:
        """The edges that exactly one face uses."""
        return [e for e, uses in self.edges.items() if len(uses) == 1]  # @line L8

    def non_manifold_edges(self) -> list[Edge]:
        """The edges that three or more faces use."""
        return [e for e, uses in self.edges.items() if len(uses) >= 3]

    def euler_characteristic(self) -> int:
        """V - E + F of the cell complex. An unused vertex counts as a point."""
        return len(self.vertices) - len(self.edges) + len(self.faces)  # @line L9

    def to_off(self) -> str:
        """The mesh in the OFF text format."""
        lines = ["OFF", f"{len(self.vertices)} {len(self.faces)} {len(self.edges)}"]
        lines += [" ".join(repr(c) for c in p) for p in self.vertices]
        lines += [" ".join(str(x) for x in (len(face),) + face) for face in self.faces]
        return "\n".join(lines) + "\n"


def _number(token: str) -> float:
    try:
        return int(token)
    except ValueError:
        return float(token)


def read_off(text: str) -> IndexedFaceSet:
    """Parse an OFF file. Comments start with #. The edge count of the header is ignored."""
    tokens: list[str] = []
    for line in text.splitlines():
        tokens += line.split("#", 1)[0].split()
    if not tokens or tokens[0] != "OFF":
        raise ValueError("not an OFF file")
    nv, nf = int(tokens[1]), int(tokens[2])
    pos = 4
    vertices = []
    for _ in range(nv):
        vertices.append(tuple(_number(t) for t in tokens[pos:pos + 3]))
        pos += 3
    faces = []
    for _ in range(nf):
        k = int(tokens[pos])
        faces.append(tuple(int(t) for t in tokens[pos + 1:pos + 1 + k]))
        pos += 1 + k
    return IndexedFaceSet(vertices, faces)
test_indexed_face_set.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/indexed-face-set/. The authors are listed in prov/A865QN.jsonl.

import random

from indexed_face_set import IndexedFaceSet, read_off

# ---- brute force: scan every face for every query ----


def scan_edges(face):
    k = len(face)
    return [(face[i], face[(i + 1) % k]) for i in range(k)]


def brute_edge_faces(faces, u, v):
    return [f for f, face in enumerate(faces) for a, b in scan_edges(face) if {a, b} == {u, v}]


def brute_neighbors(faces, f):
    mine = {frozenset(e) for e in scan_edges(faces[f])}
    return {g for g, face in enumerate(faces) if g != f and mine & {frozenset(e) for e in scan_edges(face)}}


def brute_vertex_faces(faces, v):
    return [f for f, face in enumerate(faces) if v in face]


def brute_edge_set(faces):
    return {frozenset(e) for face in faces for e in scan_edges(face)}


def rand_mesh(rng, n, nf):
    faces = []
    for _ in range(nf):
        k = rng.choice((3, 3, 3, 4, 5))
        faces.append(tuple(rng.sample(range(n), min(k, n))))
    verts = [(rng.randint(-9, 9), rng.randint(-9, 9), rng.randint(-9, 9)) for _ in range(n)]
    return verts, faces


# ---- tests ----


def test_page_example_square():
    m = IndexedFaceSet([(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)], [(0, 1, 2), (0, 2, 3)])
    assert m.edges[(0, 2)] == [(0, 2), (1, 0)]
    assert m.edge_faces(2, 0) == [0, 1]
    assert sorted(m.boundary_edges()) == [(0, 1), (0, 3), (1, 2), (2, 3)]
    assert m.face_neighbors(0) == [1]
    assert m.vertex_faces(0) == [0, 1]
    assert m.euler_characteristic() == 1


def test_page_example_soup():
    pts = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 0, 0), (1, 1, 0), (0, 1, 0)]
    m = IndexedFaceSet(pts, [(0, 1, 2), (3, 4, 5)])
    assert m.face_neighbors(0) == []
    assert len(m.boundary_edges()) == 6
    assert m.euler_characteristic() == 2


def test_closed_meshes():
    tet = IndexedFaceSet([(0, 0, 0)] * 4, [(0, 2, 1), (0, 1, 3), (1, 2, 3), (0, 3, 2)])
    assert tet.euler_characteristic() == 2 and tet.boundary_edges() == []
    cube = IndexedFaceSet([(0, 0, 0)] * 8, [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4),
                                             (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)])
    assert cube.euler_characteristic() == 2 and cube.boundary_edges() == []
    assert all(len(cube.face_neighbors(f)) == 4 for f in range(6))
    a, b = 4, 5
    faces = []
    for i in range(a):
        for j in range(b):
            p, q = i * b + j, ((i + 1) % a) * b + j
            r, s = ((i + 1) % a) * b + (j + 1) % b, i * b + (j + 1) % b
            faces += [(p, q, r), (p, r, s)]
    torus = IndexedFaceSet([(0, 0, 0)] * (a * b), faces)
    assert torus.euler_characteristic() == 0 and torus.boundary_edges() == []


def test_non_manifold_edge():
    # three triangles on one edge {0, 1}
    m = IndexedFaceSet([(0, 0, 0)] * 5, [(0, 1, 2), (1, 0, 3), (0, 1, 4)])
    assert m.non_manifold_edges() == [(0, 1)]
    assert sorted(m.edge_faces(0, 1)) == [0, 1, 2]


def test_invalid_faces():
    for bad in ([(0, 1)], [(0, 1, 1)], [(0, 1, 3)]):
        try:
            IndexedFaceSet([(0, 0, 0)] * 3, bad)
        except ValueError:
            continue
        raise AssertionError(f"accepted {bad}")


def test_off_round_trip():
    text = "OFF\n# a square\n4 2 0\n0 0 0\n1 0 0\n1.5 1 0\n0 1 -2.25\n3 0 1 2\n3 0 2 3\n"
    m = read_off(text)
    assert m.vertices[2] == (1.5, 1, 0) and m.faces == [(0, 1, 2), (0, 2, 3)]
    m2 = read_off(m.to_off())
    assert m2.vertices == m.vertices and m2.faces == m.faces
    rng = random.Random(11)
    verts = [(rng.random(), rng.uniform(-1e9, 1e9), rng.randint(-5, 5)) for _ in range(20)]
    faces = [tuple(rng.sample(range(20), 3)) for _ in range(15)]
    m3 = read_off(IndexedFaceSet(verts, faces).to_off())
    assert m3.vertices == verts and m3.faces == faces


def test_against_brute_force_random():
    rng = random.Random(2024)
    for _ in range(600):
        n = rng.randint(3, 9)
        verts, faces = rand_mesh(rng, n, rng.randint(1, 10))
        m = IndexedFaceSet(verts, faces)
        for u in range(n):
            for v in range(n):
                if u != v:
                    assert sorted(m.edge_faces(u, v)) == sorted(brute_edge_faces(faces, u, v))
            assert m.vertex_faces(u) == brute_vertex_faces(faces, u)
        for f in range(len(faces)):
            got = m.face_neighbors(f)
            assert len(got) == len(set(got)) and set(got) == brute_neighbors(faces, f)
        edges = brute_edge_set(faces)
        counts = {e: sum(1 for face in faces for x in scan_edges(face) if frozenset(x) == e) for e in edges}
        assert {frozenset(e) for e in m.boundary_edges()} == {e for e, c in counts.items() if c == 1}
        assert {frozenset(e) for e in m.non_manifold_edges()} == {e for e, c in counts.items() if c >= 3}
        assert m.euler_characteristic() == n - len(edges) + len(faces)
        assert read_off(m.to_off()).faces == m.faces

History

The format of a vertex list and a face list of indices is as old as computer graphics. The name comes from the IndexedFaceSet node of Silicon Graphics' Open Inventor, which VRML took over in its 1.0 version in 1995. The VRML97 standard, ISO/IEC 14772-1:1997, defines the node with the fields coord and coordIndex, where the index −1-1 ends a face. Botsch and others describe it as the face-based data structure, the simplest of the mesh data structures.

References

  1. Mario Botsch, Leif Kobbelt, Mark Pauly, Pierre Alliez and Bruno Lévy, Polygon Mesh Processing, AK Peters, 2010, Chapter 2, Mesh Data Structures, Section 2.1, Face-Based Data Structures
  2. The Virtual Reality Modeling Language, ISO/IEC 14772-1:1997, Chapter 6, Node Reference, Section 6.23, IndexedFaceSet (the coord and coordIndex fields, and the ccw field for the vertex order)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.boundary-edges
  • a full proof of time.build
  • a full proof of time.edge-faces
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources