Algorithm Search⌘K

Techniqueintro

Vertex welding

Also called vertex merging, duplicate vertex removal.

Merges vertices that lie within a tolerance of each other, usually with a grid or a k-d tree, so faces that should share edges become connected.

Vertex welding merges the vertices of a mesh that lie within a tolerance ε\varepsilon of each other into one vertex, and rewrites the faces with the new indices. It turns a triangle soup, where each face has its own copy of each corner, into an indexed face set in which neighbouring faces share their vertices and edges. The technique has three parts: a spatial search for close pairs, usually a uniform grid with cells of side ε\varepsilon or a k-d tree, a rule that joins close vertices into classes, usually with a disjoint-set structure, and a clean-up that removes the faces that collapse. It is the first step of most mesh repair pipelines, because STL files and many exporters write meshes without shared vertices.

In plain words

A model often arrives as loose tiles, each with its own copy of its corners. Two tiles that should touch have corners at almost the same place, but the computer sees two different points, so it thinks there is a crack between the tiles.

Welding fixes this. Pick a small distance. Any two corners closer than that distance become one corner, and every tile that used either of them now uses the merged one. Then the tiles share their sides again.

To find the close pairs fast, drop each corner into a box of a grid whose boxes are as wide as the distance. Close corners are always in the same box or in boxes that touch, so each corner only needs to look at its own box and its neighbours.

When it applies

  • The input is a polygon soup or a mesh with duplicate vertices: STL files, exports from CAD tools that write each face alone, meshes merged from parts, and the output of marching cubes when each cell writes its own vertices.
  • The duplicates are closer to each other than to any vertex they should not merge with. There must be a gap between the size of the errors and the size of the smallest real feature. The tolerance goes into that gap.
  • The positions of the copies are nearly equal because they come from the same computation or from rounding. If the copies are far apart because of real gaps between parts, welding is the wrong tool, and hole filling or snapping of borders applies.

The template

The input is nn points p0,…,pn−1p_0, \ldots, p_{n-1}, a list of faces over them, and a tolerance ε>0\varepsilon > 0. Two points are close when ∣pi−pj∣≤ε|p_i - p_j| \le \varepsilon. The welded vertices are the classes of the transitive closure of this relation, that is, the connected components of the graph with an edge between each close pair.

  1. WELD(P, F, ε)
  2. 1for each point i: cell[i] ← (⌊x_i/ε⌋, ⌊y_i/ε⌋, ⌊z_i/ε⌋); add i to the list G[cell[i]]
  3. 2U ← a disjoint-set structure with the classes {0}, ..., {n − 1}
  4. 3for each point i, each of the 27 cells c with each coordinate of c − cell[i] in {−1, 0, 1}, each j > i in G[c] do
  5. 4if |p_i − p_j|² ≤ ε² then UNION(U, i, j)
  6. 5give each class a new index, and the position of its smallest point
  7. 6replace each vertex of each face by the new index of its class, and remove consecutive repeats
  8. 7drop each face that has fewer than 3 vertices or a repeated vertex
  9. 8return the new points, the new faces, and the edges of the new faces that have 3 or more faces

Why the grid finds every close pair. If ∣xi−xj∣≤ε|x_i - x_j| \le \varepsilon, then ∣xi/ε−xj/ε∣≤1|x_i/\varepsilon - x_j/\varepsilon| \le 1, so the floors differ by at most 1. The same holds for yy and zz. So each close pair lies in one cell or in two cells that touch, and line L3 looks at it. The test of line L4 compares squared distances, so with integer or rational coordinates it is exact and needs no square root.

Why the result is the transitive closure. Lines L3 and L4 call UNION on every close pair, and only on close pairs. The classes of the disjoint-set structure are then exactly the connected components of the graph of close pairs.

Cost. Line L1 takes O(n)O(n) expected time with a hash table of the cells, as in spatial hashing. Line L3 tests the pairs in neighbouring cells. When each cell holds O(1)O(1) points, this is O(n)O(n) tests, and the disjoint-set operations add a factor of the inverse Ackermann function. In the worst case, when all points are in a few cells, it is Θ(n2)\Theta(n^2) tests, which is also the number of close pairs then. Lines L5 to L8 take time linear in the size of the mesh. This is a fixed-radius near neighbour search followed by connected components.

Classic examples

A triangle soup of a square. Two triangles of a unit square, written as a soup with 6 points: p0=(0,0,0)p_0 = (0, 0, 0), p1=(1,0,0)p_1 = (1, 0, 0), p2=(1,1,0)p_2 = (1, 1, 0) for the first triangle, and p3=(10−4,0,0)p_3 = (10^{-4}, 0, 0), p4=(1,1+10−4,0)p_4 = (1, 1 + 10^{-4}, 0), p5=(0,1,0)p_5 = (0, 1, 0) for the second. The copies p3p_3 and p4p_4 have small errors. With ε=10−3\varepsilon = 10^{-3}:

point cell close to class
p0p_0 (0,0,0)(0, 0, 0) p3p_3 0
p1p_1 (1000,0,0)(1000, 0, 0) none 1
p2p_2 (1000,1000,0)(1000, 1000, 0) p4p_4 2
p3p_3 (0,0,0)(0, 0, 0) p0p_0 0
p4p_4 (1000,1000,0)(1000, 1000, 0) p2p_2 2
p5p_5 (0,1000,0)(0, 1000, 0) none 3

The faces (0,1,2)(0, 1, 2) and (3,4,5)(3, 4, 5) become (0,1,2)(0, 1, 2) and (0,2,3)(0, 2, 3). They now share the diagonal {0,2}\{0, 2\}, the mesh has 4 vertices, 5 edges and 2 faces, and its Euler characteristic is 4−5+2=14 - 5 + 2 = 1, a disk. Before welding it was 6−6+2=26 - 6 + 2 = 2, two separate triangles.

A cube from an STL file. An STL cube has 12 triangles and 36 corner points, with each corner of the cube written 3 to 6 times, by the triangles that touch it. Welding with any ε\varepsilon smaller than the edge length gives the 8 vertices of the cube and a closed manifold mesh.

Marching cubes. A simple implementation of marching cubes writes the vertices of each cell on its own, so each vertex on a grid edge is written by up to four cells. Here the copies are computed by the same formula from the same two samples and are equal, so welding with ε=0\varepsilon = 0 (exact equality, with a hash map of the positions) is enough.

Variations

  • Exact welding. With ε=0\varepsilon = 0, merge only equal positions, with a hash map from positions to indices. It cannot chain and cannot merge two different points, but it misses copies that differ by rounding.
  • Snap to a grid. Round each position to the grid of step ε\varepsilon and merge equal results. This is fast and simple, but two points just across a cell border are not merged however close they are, and two points up to ε3\varepsilon\sqrt{3} apart in one cell are merged.
  • Weld to a kept vertex. Take the points one at a time. If a point is within ε\varepsilon of a vertex that is already kept, snap it to that vertex. If not, keep it as a new vertex. Ericson describes welding in this incremental form. A point is never merged with a point that was only close to a snapped point. This avoids chaining, but the result depends on the order of the input.
  • The mean position. Give each class the mean of its points in place of the first one. The mesh moves less on average, but every face near a merge moves a little.
  • Border welding. Merge only vertices on border edges, and only with vertices on other borders. This closes cracks between parts and leaves the inside of each part alone.
  • A k-d tree. For points with very different densities, a k-d tree gives the close pairs without the choice of a cell size.

Pitfalls

  • Chaining. Closeness is not transitive, but the classes are. Points 0,0.9ε,1.8ε,…0, 0.9\varepsilon, 1.8\varepsilon, \ldots along a line all merge into one vertex, though the first and the last are far apart. A dense part of the mesh with edges shorter than ε\varepsilon collapses into one point. Check the diameter of each class, or use a rule that does not chain.
  • A tolerance that is too large. Thin parts, small holes and short edges vanish. Faces collapse to edges or points, and line L7 drops them. Two sheets that are close but should stay apart become one, and edges with three or more faces appear. The edges of line L8 show where.
  • A tolerance that is too small. Copies that differ by more than ε\varepsilon stay apart, and the mesh keeps cracks. A relative tolerance, a small multiple of the size of the model times the machine epsilon, is a common start.
  • Non-manifold results. Welding can join two parts that only touch, at a vertex or along an edge. The result is not a manifold mesh, even if each part was one.
  • Flipped faces. Welding does not fix the orientation. After welding, faces that were oriented one by one may disagree along their new shared edges. Run consistent mesh orientation next.
  • Floating point distances. The test ∣pi−pj∣2≤ε2|p_i - p_j|^2 \le \varepsilon^2 in floating point can be wrong near the threshold. This only moves the threshold by a rounding error, which is harmless when there is a real gap between the error size and the feature size, and decides nothing when there is not.

Code

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.

vertex_welding.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vertex-welding/. The authors are listed in prov/09QVC4.jsonl.

"""Weld the vertices of a mesh that lie within a distance eps of each other.

A uniform grid with cells of side eps finds the close pairs, and a disjoint-set
forest joins them. Two points are joined when their distance is at most eps,
and joining is transitive, so a chain of close points becomes one vertex.
Coordinates and eps must be int or Fraction, so the tests are exact.
"""

from fractions import Fraction
from itertools import product
from math import floor
from typing import NamedTuple, Sequence, Union

Num = Union[int, Fraction]


class Weld(NamedTuple):
    points: list[tuple[Num, ...]]  # one position per new vertex
    faces: list[tuple[int, ...]]  # remapped faces, degenerate ones removed
    new_index: list[int]  # new vertex of each old vertex
    dropped: list[int]  # indices of the input faces that became degenerate
    non_manifold_edges: list[tuple[int, int]]  # edges of the output with three or more faces


class DisjointSet:
    def __init__(self, n: int) -> None:
        self.parent = list(range(n))

    def find(self, x: int) -> int:
        root = x
        while self.parent[root] != root:
            root = self.parent[root]
        while self.parent[x] != root:
            self.parent[x], x = root, self.parent[x]
        return root

    def union(self, a: int, b: int) -> None:
        ra, rb = self.find(a), self.find(b)
        if ra != rb:
            if ra < rb:
                self.parent[rb] = ra
            else:
                self.parent[ra] = rb


def close(p: Sequence[Num], q: Sequence[Num], eps: Num) -> bool:
    return sum((a - b) * (a - b) for a, b in zip(p, q)) <= eps * eps


def weld_classes(points: Sequence[Sequence[Num]], eps: Num) -> list[int]:
    """The representative (smallest index) of the class of each point."""
    if eps <= 0:
        raise ValueError("eps must be positive")
    n = len(points)
    cells: dict[tuple[int, ...], list[int]] = {}
    key = []
    for i, p in enumerate(points):  # @line L1
        c = tuple(floor(Fraction(x) / eps) for x in p)
        key.append(c)
        cells.setdefault(c, []).append(i)
    ds = DisjointSet(n)  # @line L2
    offsets = list(product((-1, 0, 1), repeat=len(points[0]) if n else 3))
    for i in range(n):  # @line L3
        for off in offsets:
            c = tuple(a + b for a, b in zip(key[i], off))
            for j in cells.get(c, ()):
                if j > i and close(points[i], points[j], eps):  # @line L4
                    ds.union(i, j)
    return [ds.find(i) for i in range(n)]  # @line L5


def clean_face(face: Sequence[int]) -> tuple[int, ...]:
    """Remove repeats of consecutive vertices, cyclically."""
    out: list[int] = []
    for v in face:
        if not out or out[-1] != v:
            out.append(v)
    while len(out) > 1 and out[0] == out[-1]:
        out.pop()
    return tuple(out)


def weld(points: Sequence[Sequence[Num]], faces: Sequence[Sequence[int]], eps: Num) -> Weld:
    """Weld close vertices, remap the faces and remove the faces that collapse."""
    rep = weld_classes(points, eps)
    order = sorted(set(rep))
    new_of_rep = {r: k for k, r in enumerate(order)}
    new_index = [new_of_rep[r] for r in rep]
    new_points = [tuple(points[r]) for r in order]
    out_faces: list[tuple[int, ...]] = []
    dropped: list[int] = []
    for f, face in enumerate(faces):
        g = clean_face([new_index[v] for v in face])  # @line L6
        if len(g) < 3 or len(set(g)) != len(g):  # @line L7
            dropped.append(f)
        else:
            out_faces.append(g)
    count: dict[tuple[int, int], int] = {}
    for g in out_faces:
        for i in range(len(g)):
            u, v = g[i], g[(i + 1) % len(g)]
            e = (min(u, v), max(u, v))
            count[e] = count.get(e, 0) + 1
    bad = sorted(e for e, k in count.items() if k >= 3)
    return Weld(new_points, out_faces, new_index, dropped, bad)  # @line L8
test_vertex_welding.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vertex-welding/. The authors are listed in prov/09QVC4.jsonl.

import random
from fractions import Fraction

from vertex_welding import clean_face, weld, weld_classes

# ---- brute force: all pairs, then the components of the eps-graph ----


def brute_classes(points, eps):
    n = len(points)
    adj = [[j for j in range(n) if j != i and
            sum((a - b) ** 2 for a, b in zip(points[i], points[j])) <= eps * eps] for i in range(n)]
    rep = [-1] * n
    for s in range(n):
        if rep[s] != -1:
            continue
        rep[s] = s
        stack = [s]
        while stack:
            x = stack.pop()
            for y in adj[x]:
                if rep[y] == -1:
                    rep[y] = s
                    stack.append(y)
    return rep


# ---- tests ----


def test_page_example_square_soup():
    d = Fraction(1, 10000)
    pts = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (d, 0, 0), (1, 1 + d, 0), (0, 1, 0)]
    r = weld(pts, [(0, 1, 2), (3, 4, 5)], Fraction(1, 1000))
    assert r.new_index == [0, 1, 2, 0, 2, 3]
    assert r.faces == [(0, 1, 2), (0, 2, 3)]
    assert r.points[0] == (0, 0, 0) and r.dropped == [] and r.non_manifold_edges == []


def test_chaining():
    eps = Fraction(1)
    pts = [(Fraction(9, 10) * k, 0, 0) for k in range(5)]  # neighbours 0.9 apart, ends 3.6 apart
    assert weld_classes(pts, eps) == [0, 0, 0, 0, 0]
    pts2 = [(0, 0, 0), (1, 0, 0), (Fraction(21, 10), 0, 0)]  # exactly eps counts, more does not
    assert weld_classes(pts2, eps) == [0, 0, 2]


def test_collapsed_faces_and_new_non_manifold_edges():
    eps = Fraction(1, 100)
    pts = [(0, 0, 0), (1, 0, 0), (Fraction(1, 1000), 0, 0), (0, 1, 0)]
    r = weld(pts, [(0, 1, 2), (0, 1, 3)], eps)
    assert r.dropped == [0] and r.faces == [(0, 1, 2)]
    # three sheets of triangles meeting along one edge after welding
    pts = [(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 0), (1, 0, 0), (0, 0, 1),
           (0, 0, 0), (1, 0, 0), (0, -1, 0)]
    r = weld(pts, [(0, 1, 2), (3, 4, 5), (6, 7, 8)], eps)
    assert r.non_manifold_edges == [(0, 1)]


def test_clean_face():
    assert clean_face([1, 1, 2, 3, 3, 1]) == (1, 2, 3)
    assert clean_face([4, 4, 4]) == (4,)


def test_against_brute_force_random():
    rng = random.Random(1996)
    for it in range(700):
        n = rng.randint(1, 30)
        eps = Fraction(rng.randint(1, 6), rng.randint(1, 4))
        centres = [tuple(Fraction(rng.randint(-20, 20), 2) for _ in range(3)) for _ in range(rng.randint(1, 6))]
        pts = []
        for _ in range(n):
            c = rng.choice(centres)
            pts.append(tuple(x + Fraction(rng.randint(-8, 8), 4) for x in c))
        if it % 5 == 0:  # points on cell borders and at exact distance eps
            pts = [tuple(eps * rng.randint(-3, 3) for _ in range(3)) for _ in range(n)]
        assert weld_classes(pts, eps) == brute_classes(pts, eps)
        faces = [tuple(rng.sample(range(n), 3)) for _ in range(rng.randint(0, 8))] if n >= 3 else []
        r = weld(pts, faces, eps)
        rep = brute_classes(pts, eps)
        reps = sorted(set(rep))
        assert len(r.points) == len(reps)
        for f, face in enumerate(faces):
            mapped = [reps.index(rep[v]) for v in face]
            if len(set(mapped)) == 3:
                assert tuple(mapped) in r.faces
            else:
                assert f in r.dropped


def test_two_dimensional_points():
    pts = [(0, 0), (Fraction(1, 2), 0), (5, 5)]
    assert weld_classes(pts, Fraction(1, 2)) == [0, 0, 2]

References

  1. Christer Ericson, Real-Time Collision Detection, Morgan Kaufmann, 2005, Chapter 12, Geometrical Robustness, Section 12.1, Vertex Welding (the choice of the tolerance, and welding with a grid of cells)
  2. Mario Botsch, Leif Kobbelt, Mark Pauly, Pierre Alliez and Bruno Lévy, Polygon Mesh Processing, AK Peters, 2010, Chapter 8, Model Repair (gaps and duplicate elements in polygon soups)
  3. Marco Attene, Marcel Campen and Leif Kobbelt, Polygon mesh repairing, an application perspective, ACM Computing Surveys 45(2), Article 15, 2013, the parts on polygon soups, duplicate elements and small gaps

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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
  • three classic examples