Algorithm Search⌘K

Algorithmadvanced

Volumetric mesh repair

Also called Ju polygon repair.

Ju's repair that scan-converts a polygon soup into an octree grid, fixes the signs of the grid points by parity, and contours a closed surface that separates inside from outside.

Time
O(s + k + b·g) worst
Space
Θ(g + k) extra
Where
b = the number of odd cells before patching; g = the number of grid cells; k = the number of crossings of the input with grid edges; s = the number of input polygons or segments
Properties
deterministicnot exactiterative
Origin
Tao Ju, 2004

Volumetric mesh repair, as Tao Ju gave it in 2004, turns a polygon soup into a closed surface. The soup can have gaps, holes, overlaps, double faces, dangling pieces and self-intersections. The method does not try to fix the polygons one by one. It puts a grid around them, an octree in 3D, and marks each grid edge that crosses the polygons an odd number of times. In a closed model, the marked edges are exactly the edges between an inside and an outside grid point. A defect leaves cells where the marks are not consistent, and the method changes a small set of marks there, so that the inside and outside become defined. A search then gives each grid point a sign, and marching cubes or dual contouring contours a surface between the signs. The result is a closed surface that separates inside from outside, for every input. The code on this page is the same method in the plane, on a square grid, where every step can be tested exactly. The method solves the mesh repair problem for the condition of a closed, oriented surface, at the cost of a resampled surface everywhere.

In plain words

Lay a fine net of points over the broken model. Each short line of the net either crosses the model's skin an odd number of times or not. If the skin were whole, the odd lines would be exactly the lines that go from inside to outside, and you could colour every net point as inside or outside without a contradiction.

A gap in the skin breaks this. Around the gap, a small square of the net has an odd number of odd lines, which no colouring can explain. Such squares come in pairs. Join each pair by the shortest chain of squares and flip the lines along the chain: this paints in a bit of skin across the gap.

Now colour the points by walking out from a corner that is surely outside. Finally, draw the new skin between inside and outside points. It is always closed.

The problem

The input is a list of polygons in space, with no promise about their connections: a polygon soup, as read from an STL file. The output is a closed, oriented surface that is near the input where the input is good, and that bounds a solid: every point off the surface is inside or outside, and the inside is on the side of the right-hand rule normals. The problem statement and the other conditions of a valid mesh are on the mesh repair problem page.

In the plane, the input is a list of segments, and the output is a set of closed polygons that do not cross, with the inside on the left of each segment.

The algorithm

The grid has cell size hh and a margin of one cell around the input. In the plane, the grid points sit at (Xi+ε,Yj+ε2)(X_i + \varepsilon, Y_j + \varepsilon^2) for a symbolic ε>0\varepsilon > 0, in the manner of simulation of simplicity, so no grid point lies on a segment and each crossing of a segment with the grid lines falls on exactly one grid edge.

  1. VOLUMETRIC-REPAIR(S, h)
  2. 1G ← a grid of cell size h around S, with a margin of one cell
  3. 2for each segment of S, for each grid edge e that it crosses: toggle mark(e)
  4. 3B ← the cells with an odd number of marked edges
  5. 4while B is not empty: take c ∈ B, and find by breadth-first search over the cells the nearest d ∈ B \ {c}
  6. 5toggle mark(e) for each edge e between two consecutive cells of the path from c to d; remove c and d from B
  7. 6sign(corner) ← outside; by breadth-first search over the grid edges, sign(w) ← sign(v) xor mark(vw)
  8. 7for each cell: join the midpoints of its marked edges by marching squares, with the inside on the left
  9. 8return the segments of line L7

In 3D. Ju's method has the same four steps on an octree. Line L2 scan-converts each polygon into the cells it meets, and stores the parity of the crossings on each cell edge, refining the octree only near the polygons. The marked edges define a dual surface: one quad for each marked edge, made of the four cells around it. For a closed input, this dual surface is closed. A defect leaves boundary cycles: loops of cell faces on the border of the dual surface, at the grid faces with an odd number of marked edges. Lines L4 and L5 become the patching step, which finds a small patch of the dual grid for each boundary cycle and toggles the edges under the patch. Line L6 is the same flood fill over the grid points. Line L7 is marching cubes on the signs, or dual contouring, which also uses the crossing points and the polygon normals stored in line L2 to keep sharp edges.

The predicate and its failure. Line L2 is a crossing test of a segment with a grid edge, which is two orientation tests in the plane, and a segment-triangle test in 3D. With floating point coordinates, a segment that passes very near a grid point is a sign test of a nearly zero value, and catastrophic cancellation can give it the wrong sign. Then the crossing is put on two edges, or on none. This is not a small error: the cell next to that grid point gets an odd number of marked edges, so line L4 sees a gap where the input has none, and patches it, or it pairs this cell with a real gap far away and cuts a strip through the model. The fix is to make the test exact. The code uses rational coordinates and the symbolic perturbation above, so each crossing falls on exactly one edge, and the tests check the result against an exact crossing test of every segment with every perturbed grid edge.

Example

The input is three sides of the square [1,4]×[1,4][1, 4] \times [1, 4], with h=1h = 1: the segments (1,1)→(4,1)(1, 1) \to (4, 1), (4,1)→(4,4)(4, 1) \to (4, 4) and (1,4)→(1,1)(1, 4) \to (1, 1). The top side is missing.

  1. Grid. Line L1 makes the grid [0,5]×[0,5][0, 5] \times [0, 5] with 25 cells. The grid point (i,j)(i, j) sits at (i+ε,j+ε2)(i + \varepsilon, j + \varepsilon^2).
  2. Scan conversion. The bottom side crosses the vertical edges at x=1+εx = 1 + \varepsilon, 2+ε2 + \varepsilon and 3+ε3 + \varepsilon just below y=1+ε2y = 1 + \varepsilon^2, the right side crosses three horizontal edges at x=4x = 4, and the left side three at x=1x = 1. So 9 edges are marked.
  3. Odd cells. Each cell is even except the two cells at the free ends: the cell (0,3)(0, 3), with the corner (1,4)(1, 4), and the cell (3,3)(3, 3), with the corner (4,4)(4, 4). Each has one marked edge.
  4. Patching. The shortest path of cells from (0,3)(0, 3) to (3,3)(3, 3) runs along the row y∈[3,4]y \in [3, 4]. Line L5 toggles its three vertical edges at x=3,2,1x = 3, 2, 1, which closes the gap one cell below the missing side. Now 12 edges are marked, and every cell is even.
  5. Signs. The search from the corner (0,0)(0, 0) gives the inside to the 9 grid points (i,j)(i, j) with 1≤i,j≤31 \le i, j \le 3.
  6. Contour. Marching squares gives 12 segments through the midpoints of the 12 marked edges, for example from (0.5,1)(0.5, 1) to (1,0.5)(1, 0.5) in the corner cell, with the inside point (1,1)(1, 1) on its left, which make one closed polygon around the 9 inside points.

The result is a closed curve, but the closing is not where the missing side was: it follows the grid one cell lower, because the grid point (i,4)(i, 4) is outside of the three given sides. With a smaller hh, the closing moves closer to the line y=4y = 4.

Correctness

The proofs below are for the method in the plane, which the code follows. The 3D method rests on the same parity arguments, and Ju's paper argues them there.

  • Each crossing falls on one edge. Under the perturbation, no grid point lies on a segment, and each crossing is assigned to exactly one edge. Because of the margin, no outer edge is marked.
  • Odd cells come in pairs, and patching makes every cell even. Each marked edge lies on two cells, so the number of odd cells is even. Toggling the edges along a path of cells changes the parity of its two end cells only.
  • The signs exist, and they are unique up to complement. If every cell is even, every cycle of the grid crosses an even number of marked edges, since the cell boundaries generate the cycles. So the signs from the search are consistent on every edge, and the corner fixes them. The outer ring is outside.
  • A closed input keeps its inside. If every end point of the segments has even degree, as for any set of closed polygons, there are no odd cells, and each grid point gets its even-odd value with respect to the input. So on good input, the method changes nothing but the sampling.
  • The output is closed and separates the signs. Each output vertex starts one segment and ends one, two segments meet only at shared end points, and the even-odd value of the output at each grid point is its sign.

The tests check each of these by brute force: the scan conversion against an exact test of all segment and edge pairs, the signs against even-odd ray casting, and the uniqueness against all 2162^{16} sign vectors of a small grid. What is not proved is how good the patch is. The shortest path is one choice among many, and the patch it gives is a guess at the missing surface, as in any hole filling.

Proof: In the plane, parity patching makes every cell even, the signs then exist and are unique up to complement, closed input keeps its even-odd inside, and the contour is a set of closed curves around the inside pointsfull

Setup. The grid has nx×nyn_x \times n_y square cells of side hh and the grid points (i,j)(i, j), 0≤i≤nx0 \le i \le n_x, 0≤j≤ny0 \le j \le n_y, at the positions (Xi+ε,Yj+ε2)(X_i + \varepsilon, Y_j + \varepsilon^2) for an infinitesimal ε>0\varepsilon > 0. The input is a finite list of segments with rational end points, all at distance at least hh from the border of the grid. A grid edge joins two neighbouring grid points. An edge is inner if it lies on two cells, and outer if it lies on the border of the grid. After line L2, an edge is marked if it crosses the input an odd number of times.

Lemma 1 (general position). No grid point lies on a segment of positive length, and no segment end point lies on a grid edge. So every meeting of a segment with a grid edge is a proper crossing at a point inside both, and crossed_edges assigns each such crossing to exactly one edge.

Proof. The point (X+ε,Y+ε2)(X + \varepsilon, Y + \varepsilon^2) lies on the line through p≠qp \ne q if and only if (X+ε−px)(qy−py)−(Y+ε2−py)(qx−px)=0(X + \varepsilon - p_x)(q_y - p_y) - (Y + \varepsilon^2 - p_y)(q_x - p_x) = 0. As a polynomial in ε\varepsilon its coefficient of ε\varepsilon is qy−pyq_y - p_y and of ε2\varepsilon^2 is −(qx−px)-(q_x - p_x), which are not both zero, so it is not zero for small ε>0\varepsilon > 0. A rational end point cannot have the coordinate Y+ε2Y + \varepsilon^2 of a horizontal edge or X+εX + \varepsilon of a vertical edge. For the assignment, write the crossing of pqpq with the line y=Yj+ε2y = Y_j + \varepsilon^2 as x=x0+ε2 Δx/Δyx = x_0 + \varepsilon^2 \, \Delta x / \Delta y, where x0x_0 is the crossing with y=Yjy = Y_j. Then x>Xi+εx > X_i + \varepsilon if and only if x0>Xix_0 > X_i, since a tie leaves the sign of −ε-\varepsilon, and x<Xi+1+εx < X_{i+1} + \varepsilon if and only if x0≤Xi+1x_0 \le X_{i+1}. The intervals (Xi,Xi+1](X_i, X_{i+1}] are disjoint and cover the line, so exactly one index fits. The vertical case is the same with the crossing y=y0+ε Δy/Δxy = y_0 + \varepsilon \, \Delta y / \Delta x: a tie y0=Yjy_0 = Y_j goes up when Δx Δy>0\Delta x \, \Delta y > 0 and down otherwise. □\square

By the margin, no segment reaches the outer grid lines, so no outer edge is ever marked.

Lemma 2 (patching). Let BB be the set of cells with an odd number of marked edges after line L2. Then ∣B∣|B| is even, the loop of lines L4 and L5 ends, and afterwards every cell has an even number of marked edges. No outer edge changes.

Proof. As long as every marked edge is inner, each marked edge lies on exactly two cells, so the sum over all cells of the number of marked edges is twice the number of marked edges, and the number of cells with an odd count is even. The loop keeps the invariant that the set todo\mathit{todo} of the code is exactly the set of cells that are odd at that moment, and that every marked edge is inner. Line L4 takes a cell cc of todo\mathit{todo} and removes it. An odd number of cells of todo\mathit{todo} remain, so at least one, and the grid of cells is connected, so the breadth-first search finds one of them, dd. The search moves between cells only across inner edges, so line L5 changes only inner edges. Along the path c=c0,c1,…,cr=dc = c_0, c_1, \ldots, c_r = d, the edge between ct−1c_{t-1} and ctc_t changes its mark. A cell ctc_t with 0<t<r0 < t < r lies on two changed edges, so its parity stays. The cells cc and dd lie on one changed edge each, so their parity changes from odd to even. Each round removes two cells from BB, and no cell outside BB becomes odd, so after ∣B∣/2|B|/2 rounds every cell is even. □\square

Lemma 3 (signs). If every cell has an even number of marked edges, there is a function ss on the grid points with s(a)≠s(b)s(a) \ne s(b) exactly for the marked edges abab. Line L6 computes one such function with the corner (0,0)(0, 0) outside, it is the only one with that value, and every grid point on the border of the grid is outside.

Proof. Line L6 is a breadth-first search of the grid graph from (0,0)(0, 0), and it sets s(w)=s(v)⊕[vw marked]s(w) = s(v) \oplus [vw \text{ marked}] along the edges of its search tree. The grid graph is connected, so every point gets a value. For any edge abab, the tree paths from (0,0)(0, 0) to aa and to bb and the edge abab make a closed walk ZZ, and s(a)⊕s(b)⊕[ab marked]s(a) \oplus s(b) \oplus [ab \text{ marked}] is the parity of the number of marked edges in ZZ. Over GF(2)\mathrm{GF}(2), every closed walk in the grid graph is the sum of the boundaries of the cells it encloses, since the grid is a planar graph whose bounded faces are the cells, and the boundaries of the bounded faces span its cycle space. Each cell boundary has an even number of marked edges, so ZZ does too, and s(a)⊕s(b)=[ab marked]s(a) \oplus s(b) = [ab \text{ marked}]. Any other function with this property differs from ss by a constant on the connected graph, so the value at (0,0)(0, 0) fixes it, and the complement is the only other one. The border points are joined to (0,0)(0, 0) by outer edges, which are not marked, so they share its value. □\square

Lemma 4 (closed input). Suppose each end point appears in the list of segments an even number of times, as for any set of closed polygons, with or without self-intersections. Then line L3 finds no odd cell, and the sign of each grid point is its even-odd value: the parity of the number of segments that a ray from it to the right crosses.

Proof. Let χ(a)\chi(a) be the even-odd value of the grid point aa. For an edge abab, let RR be a large number, and consider the closed polygon a→b→b+(R,0)→a+(R,0)→aa \to b \to b + (R, 0) \to a + (R, 0) \to a, which runs along the edge, along the ray from bb, along a short segment far to the right of the input, and back along the ray from aa. By Lemma 1 and the perturbation, it meets the input only in proper crossings. The input is a sum of closed polygons over GF(2)\mathrm{GF}(2), because each end point has even degree. Two closed polygons in the plane in general position cross an even number of times, so the number of crossings of abab with the input plus those of the two rays is even, and the edge abab is marked if and only if χ(a)≠χ(b)\chi(a) \ne \chi(b). Then the count of marked edges on each cell is the number of changes of χ\chi around its four corners, which is even, so there are no odd cells. The function χ\chi satisfies the condition of Lemma 3, and χ=0\chi = 0 at the corner (0,0)(0, 0), which is outside the bounding box of the input. By uniqueness, s=χs = \chi. □\square

Lemma 5 (the contour). After line L7, each output vertex is the start of exactly one segment and the end of exactly one, two segments meet only at common end points, and each grid point lies inside the output, by the even-odd rule, if and only if its sign is inside. Each segment has the inside points of its cell on its left.

Proof. In a cell, walk the four corners counterclockwise. The marked edges are exactly the edges where the sign changes, by Lemma 3, and the changes alternate between inside to outside and outside to inside. Line L7 joins each change from inside to outside to the next change back, so each marked edge of the cell is the start or the end of exactly one segment of the cell. An inner edge is walked in opposite directions by its two cells, so a change from inside to outside in one cell is a change back in the other. So the midpoint of each marked edge starts one segment and ends one segment. A segment joins midpoints of two edges of one cell, and in a cell with four marked edges the two segments cut off the two opposite outside corners, so they are disjoint. Segments of different cells lie in different closed cells, which share at most an edge, and on that edge the only output point is its midpoint. So the output is a set of disjoint closed polygons. Each output polygon crosses each marked edge once, at its midpoint, passing from one cell to the other, and crosses no unmarked edge, so its even-odd value changes across exactly the marked edges. The even-odd value of the output is 0 at (0,0)(0, 0), which lies outside all output polygons, and Lemma 3 gives that it equals ss. For the orientation, a segment from the edge after an inside corner to the edge before the next inside corner turns around the outside corners between them on its right, so the inside corners of its cell are on its left. □\square

Complexity

With a walk along each segment through the cells it meets, line L2 takes O(s+k)O(s + k) time, where kk is the number of crossings. Each search of line L4 takes O(g)O(g) time in the worst case, and there are b/2b / 2 of them, so patching takes O(b⋅g)O(b \cdot g). In practice the pairs are close, and each search stops after a few cells. Lines L6 and L7 take Θ(g)\Theta(g) time. The marks and signs take Θ(g)\Theta(g) space. The code scans every grid line for each segment, which costs O(s⋅(nx+ny))O(s \cdot (n_x + n_y)) for an nx×nyn_x \times n_y grid, simpler and enough for the tests.

In 3D, an octree that is fine only near the polygons keeps gg near the surface area of the model divided by h2h^2, in place of the volume divided by h3h^3. This is what makes the method practical for large scans.

Properties

  • Always closed. For every input, the output is a closed surface that separates inside from outside. This holds by construction, for any defects.
  • Not always a manifold. The guarantee is a closed, separating surface. Whether it is also a manifold depends on the contouring: marching squares with a fixed rule for the saddle cells gives disjoint closed curves, as the code shows, but in 3D a cell that touches the surface in several pieces can give a non-manifold vertex or edge with plain dual contouring.
  • Resamples everything. The output is a new surface at the resolution hh. Thin parts below about hh can vanish or merge, small features are lost, and the polygons of the input are not kept.
  • Robust to the defects of the input. Overlaps cancel in pairs, since two copies of a polygon toggle the same marks twice, and dangling pieces only add odd cells that patching pairs.
  • Deterministic. Ties in the searches follow a fixed order of the neighbours.
  • Not exact geometry. The signs are exact under the perturbation, but the output is an approximation of the input surface at the resolution hh.

Variants and improvements

  • Dual contouring with Hermite data. Storing the crossing points and normals on the marked edges lets dual contouring place the output vertices on the sharp edges and corners of a CAD model.
  • Signs from a winding number. In place of parity patching, the sign of each grid point can come from the generalized winding number of the soup, which is robust to gaps and gives a smooth inside measure. Thresholding it, then contouring, is another volumetric repair.
  • Reconstruction from points. Poisson surface reconstruction ignores the connections altogether and fits an indicator function to points with normals. It gives a watertight surface too, but it needs good normals.
  • Different patch choices. Ju chooses small patches for the boundary cycles, and the code takes shortest paths. Any set of paths that pairs the odd cells makes the signs consistent, so other rules give other closings of a large gap, with the same guarantee.
  • Space carving and distance fields. A signed distance function computed from the soup, with a sign from ray casting or visibility, is the older form of volumetric repair. It fails when the soup has large gaps, because the sign is then not defined.

When to use it

Use it when the input is badly broken and a closed solid is required: for 3D printing, for slicing for additive manufacturing, for finite element meshing, or for collision tests. It handles any soup, including models where surface-based repair gives up. Do not use it when the input polygons must be kept, when the model has features thinner than the cell size you can afford, or when there is only one small hole in a good mesh: then a surface-based method such as Liepa hole filling keeps the rest of the mesh as it is.

Pitfalls

  • Cell size too coarse. Thin walls and narrow gaps close up, and small handles vanish. Pick hh below the thinnest part that must survive.
  • Cell size too fine. A gap wider than a few cells needs a patch that is large in the grid, and the patching can choose a closing that a human would not. Fix large gaps before, or use a coarser grid there.
  • Floating point scan conversion. A crossing near a grid point that is counted twice or not at all makes a false odd cell, which patching then joins to another odd cell. Use an exact or perturbed crossing test.
  • Open sheets. A single open sheet, such as a terrain or a facade, is all boundary. The method closes it into a thin slab or cuts it off along the grid, which is seldom the wanted result.
  • Nested shells. Two shells, one inside the other, give a hollow solid by parity. This is right for a thick-walled part, but wrong if the inner shell was a duplicate by mistake.
  • Measuring the change. The output differs from the input everywhere. Measure the difference, for example with the Hausdorff distance or a Metro comparison, before trusting it.

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.

volumetric_mesh_repair.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/volumetric-mesh-repair/. The authors are listed in prov/5S30QB.jsonl.

"""Volumetric repair in the plane: the 2D analogue of Ju's method (SIGGRAPH 2004).

The input is a soup of line segments that should bound regions, with gaps,
overlaps and dangling pieces. The steps are:

1. Scan conversion. A grid edge is marked when it crosses the input an odd number
   of times. The grid points are moved by a symbolic perturbation (eps, eps^2), so no
   grid point lies on a segment and each crossing falls on exactly one edge.
2. Patching. The dual curve of the marked edges has an end in each cell with an odd
   number of marked edges. These cells are joined in pairs by shortest paths of cells,
   and the edges between consecutive cells of a path change their marks.
3. Signs. A search from the outer corner gives each grid point a side; the side
   changes exactly across the marked edges.
4. Contouring. Marching squares joins the midpoints of the marked edges of each cell.

Coordinates and the cell size must be int or Fraction, so all tests are exact.
"""

from collections import deque
from fractions import Fraction
from math import ceil, floor
from typing import NamedTuple, Sequence, Union

Num = Union[int, Fraction]
Point = tuple[Num, Num]
Edge = tuple[str, int, int]  # ("h", i, j) joins (i, j) and (i + 1, j); ("v", i, j) joins (i, j) and (i, j + 1)


class Grid(NamedTuple):
    x0: Fraction
    y0: Fraction
    h: Fraction
    nx: int  # cells in x
    ny: int  # cells in y

    def point(self, i: int, j: int) -> tuple[Fraction, Fraction]:
        """The unperturbed position of the grid point (i, j)."""
        return (self.x0 + i * self.h, self.y0 + j * self.h)

    def cell_edges(self, i: int, j: int) -> list[Edge]:
        """The edges of cell (i, j) in counterclockwise order: bottom, right, top, left."""
        return [("h", i, j), ("v", i + 1, j), ("h", i, j + 1), ("v", i, j)]

    def cell_corners(self, i: int, j: int) -> list[tuple[int, int]]:
        return [(i, j), (i + 1, j), (i + 1, j + 1), (i, j + 1)]


class Repair(NamedTuple):
    grid: Grid
    marked: set[Edge]  # the marked edges after patching
    odd_cells: list[tuple[int, int]]  # the ends of the dual curve before patching
    toggled: list[Edge]  # the edges whose mark the patching changed
    inside: dict[tuple[int, int], bool]  # the side of each grid point
    segments: list[tuple[Point, Point]]  # the output, inside on the left of each segment


def make_grid(segments: Sequence[tuple[Point, Point]], h: Num) -> Grid:
    """A grid of cell size h that contains every segment with at least one cell of margin."""
    h = Fraction(h)
    xs = [Fraction(p[0]) for s in segments for p in s] or [Fraction(0)]
    ys = [Fraction(p[1]) for s in segments for p in s] or [Fraction(0)]
    i0, j0 = floor(min(xs) / h) - 1, floor(min(ys) / h) - 1
    i1, j1 = ceil(max(xs) / h) + 1, ceil(max(ys) / h) + 1
    return Grid(i0 * h, j0 * h, h, i1 - i0, j1 - j0)


def crossed_edges(g: Grid, p: Point, q: Point) -> list[Edge]:
    """The grid edges that the segment pq crosses, with the grid points at (X + eps, Y + eps^2)."""
    px, py, qx, qy = Fraction(p[0]), Fraction(p[1]), Fraction(q[0]), Fraction(q[1])
    out: list[Edge] = []
    dx, dy = qx - px, qy - py
    # horizontal lines y = Y_j + eps^2: p is above when py > Y_j, a tie counts as below
    for j in range(g.ny + 1):
        yj = g.y0 + j * g.h
        if (py > yj) != (qy > yj):
            x = px + (yj - py) * dx / dy  # the crossing, compared with X_i + eps
            # x > X_i + eps  iff x > X_i;  x < X_{i+1} + eps  iff x <= X_{i+1}
            i = ceil((x - g.x0) / g.h) - 1
            if 0 <= i < g.nx:
                out.append(("h", i, j))
    # vertical lines x = X_i + eps: p is to the right when px > X_i, a tie counts as left
    for i in range(g.nx + 1):
        xi = g.x0 + i * g.h
        if (px > xi) != (qx > xi):
            y = py + (xi - px) * dy / dx  # the crossing at eps = 0
            t = (y - g.y0) / g.h
            j = floor(t)
            if t == j:  # on the line Y_j: the sign of eps*dy/dx - eps^2 decides
                if dy * dx <= 0:
                    j -= 1  # just below Y_j
            if 0 <= j < g.ny:
                out.append(("v", i, j))
    return out


def odd_cells(g: Grid, marked: set[Edge]) -> list[tuple[int, int]]:
    return [(i, j) for j in range(g.ny) for i in range(g.nx)
            if sum(e in marked for e in g.cell_edges(i, j)) % 2 == 1]


def _shared_edge(a: tuple[int, int], b: tuple[int, int]) -> Edge:
    (i, j), (k, l) = a, b
    if k == i + 1:
        return ("v", k, j)
    if k == i - 1:
        return ("v", i, j)
    if l == j + 1:
        return ("h", i, l)
    return ("h", i, j)


def repair(segments: Sequence[tuple[Point, Point]], h: Num) -> Repair:
    g = make_grid(segments, h)  # @line L1
    marked: set[Edge] = set()
    for p, q in segments:  # @line L2
        for e in crossed_edges(g, p, q):
            marked ^= {e}
    odd = odd_cells(g, marked)  # @line L3
    todo = set(odd)
    toggled: list[Edge] = []
    for c in odd:  # @line L4
        if c not in todo:
            continue
        todo.discard(c)
        prev = {c: c}
        dq = deque([c])
        found = None
        while dq:
            a = dq.popleft()
            if a in todo:
                found = a
                break
            i, j = a
            for b in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):
                if 0 <= b[0] < g.nx and 0 <= b[1] < g.ny and b not in prev:
                    prev[b] = a
                    dq.append(b)
        assert found is not None  # the number of odd cells is even
        todo.discard(found)
        while found != c:  # @line L5
            e = _shared_edge(prev[found], found)
            marked ^= {e}
            toggled.append(e)
            found = prev[found]
    inside = {(0, 0): False}  # @line L6
    dq = deque([(0, 0)])
    while dq:
        i, j = dq.popleft()
        for (k, l), e in (((i + 1, j), ("h", i, j)), ((i - 1, j), ("h", i - 1, j)),
                          ((i, j + 1), ("v", i, j)), ((i, j - 1), ("v", i, j - 1))):
            if 0 <= k <= g.nx and 0 <= l <= g.ny and (k, l) not in inside:
                inside[(k, l)] = inside[(i, j)] ^ (e in marked)
                dq.append((k, l))
    out: list[tuple[Point, Point]] = []
    for j in range(g.ny):  # @line L7
        for i in range(g.nx):
            out += _cell_segments(g, i, j, inside, marked)
    return Repair(g, marked, odd, toggled, inside, out)  # @line L8


def _midpoint(g: Grid, e: Edge) -> Point:
    kind, i, j = e
    x, y = g.point(i, j)
    return (x + g.h / 2, y) if kind == "h" else (x, y + g.h / 2)


def _cell_segments(g: Grid, i: int, j: int, inside: dict[tuple[int, int], bool],
                   marked: set[Edge]) -> list[tuple[Point, Point]]:
    """Join each edge where the side goes from inside to outside, counterclockwise, to the next
    edge where it goes back. In a saddle cell this joins the two inside corners."""
    corners = g.cell_corners(i, j)
    edges = g.cell_edges(i, j)
    s = [inside[c] for c in corners]
    for k in range(4):
        assert (s[k] != s[(k + 1) % 4]) == (edges[k] in marked)
    segs = []
    for k in range(4):
        if s[k] and not s[(k + 1) % 4]:  # inside to outside
            m = (k + 1) % 4
            while not (not s[m] and s[(m + 1) % 4]):
                m = (m + 1) % 4
            segs.append((_midpoint(g, edges[k]), _midpoint(g, edges[m])))
    return segs
test_volumetric_mesh_repair.py 167 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/volumetric-mesh-repair/. The authors are listed in prov/5S30QB.jsonl.

import random
from fractions import Fraction
from itertools import product

from volumetric_mesh_repair import crossed_edges, make_grid, odd_cells, repair

EPS = Fraction(1, 10 ** 4)  # a concrete stand-in for the symbolic eps; small against all coordinates


# ---- brute force ----


def perturbed(g, i, j):
    x, y = g.point(i, j)
    return (x + EPS, y + EPS * EPS)


def orient(a, b, c):
    return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])


def segments_cross(a, b, p, q):
    """Exact proper crossing test of two segments in general position."""
    return (orient(a, b, p) > 0) != (orient(a, b, q) > 0) and (orient(p, q, a) > 0) != (orient(p, q, b) > 0)


def even_odd(point, segments):
    """Brute-force parity of a ray to the right against all segments (half-open rule in y)."""
    x, y = point
    c = 0
    for p, q in segments:
        if (p[1] > y) != (q[1] > y):
            xc = p[0] + (y - p[1]) * (q[0] - p[0]) / (q[1] - p[1])
            if xc > x:
                c += 1
    return c % 2 == 1


def all_grid_edges(g):
    for j in range(g.ny + 1):
        for i in range(g.nx):
            yield ("h", i, j), (i, j), (i + 1, j)
    for j in range(g.ny):
        for i in range(g.nx + 1):
            yield ("v", i, j), (i, j), (i, j + 1)


def random_chain(rng, k, r):
    pts = [(rng.randint(-r, r), rng.randint(-r, r)) for _ in range(k)]
    return [(pts[t], pts[(t + 1) % k]) for t in range(k)]


def check_contour(res):
    """Each output vertex has one segment in and one out, so the output is a set of closed curves."""
    ins, outs = {}, {}
    for a, b in res.segments:
        assert a != b
        outs[a] = outs.get(a, 0) + 1
        ins[b] = ins.get(b, 0) + 1
    assert ins == outs and set(ins.values()) <= {1}


# ---- tests ----


def test_scan_conversion_against_brute_force():
    rng = random.Random(2004)
    for _ in range(150):
        segs = [((rng.randint(-6, 6), rng.randint(-6, 6)), (rng.randint(-6, 6), rng.randint(-6, 6)))
                for _ in range(rng.randint(1, 4))]
        h = Fraction(rng.randint(1, 3), rng.randint(1, 2))
        g = make_grid(segs, h)
        for p, q in segs:
            got = set(crossed_edges(g, p, q))
            want = {e for e, a, b in all_grid_edges(g)
                    if p != q and segments_cross(perturbed(g, *a), perturbed(g, *b), p, q)}
            assert got == want


def test_closed_input_gives_even_odd_signs():
    rng = random.Random(1)
    for _ in range(80):
        segs = []
        for _ in range(rng.randint(1, 3)):
            segs += random_chain(rng, rng.randint(3, 6), 7)
        h = Fraction(rng.randint(1, 4), 2)
        res = repair(segs, h)
        assert res.odd_cells == [] and res.toggled == []
        for (i, j), side in res.inside.items():
            assert side == even_odd(perturbed(res.grid, i, j), segs)
        check_contour(res)


def test_contour_bounds_exactly_the_inside_points():
    rng = random.Random(5)
    for _ in range(60):
        segs = [s for s in random_chain(rng, rng.randint(3, 7), 6) if rng.random() < 0.8]  # with gaps
        res = repair(segs, 1)
        check_contour(res)
        for (i, j), side in res.inside.items():
            # an unperturbed grid point never lies on the output, which joins edge midpoints
            assert side == even_odd(res.grid.point(i, j), res.segments)


def test_patching_makes_every_cell_even_and_signs_consistent():
    rng = random.Random(77)
    for _ in range(120):
        segs = [((rng.randint(-5, 5), rng.randint(-5, 5)), (rng.randint(-5, 5), rng.randint(-5, 5)))
                for _ in range(rng.randint(1, 6))]
        res = repair(segs, Fraction(rng.randint(1, 2)))
        g = res.grid
        assert len(res.odd_cells) % 2 == 0
        assert odd_cells(g, res.marked) == []
        for e, a, b in all_grid_edges(g):
            assert (res.inside[a] != res.inside[b]) == (e in res.marked)
        assert not any(res.inside[(i, j)] for i in (0, g.nx) for j in range(g.ny + 1))
        check_contour(res)


def test_signs_are_unique_up_to_complement():
    """Brute force over all sign vectors of a small grid: only the result and its complement fit."""
    rng = random.Random(9)
    for _ in range(12):
        segs = [((rng.randint(1, 3), rng.randint(1, 3)), (rng.randint(1, 3), rng.randint(1, 3)))
                for _ in range(rng.randint(1, 3))]
        res = repair(segs, 1)
        g = res.grid
        verts = [(i, j) for j in range(g.ny + 1) for i in range(g.nx + 1)]
        if len(verts) > 16:
            continue
        edges = list(all_grid_edges(g))
        fits = []
        for bits in product((False, True), repeat=len(verts)):
            s = dict(zip(verts, bits))
            if all((s[a] != s[b]) == (e in res.marked) for e, a, b in edges):
                fits.append(s)
        assert len(fits) == 2
        assert res.inside in fits
        assert {v: not x for v, x in res.inside.items()} in fits


def test_page_example_square_with_a_gap():
    # three sides of the square [1, 4] x [1, 4]; the top side is missing
    segs = [((1, 1), (4, 1)), ((4, 1), (4, 4)), ((1, 4), (1, 1))]
    res = repair(segs, 1)
    g = res.grid
    assert (g.x0, g.y0, g.nx, g.ny) == (0, 0, 5, 5)
    assert res.odd_cells == [(0, 3), (3, 3)]  # the cells that hold the two free ends (1, 4) and (4, 4)
    assert res.toggled == [("v", 3, 3), ("v", 2, 3), ("v", 1, 3)]
    assert len(res.marked) == 12
    inside = sorted(v for v, s in res.inside.items() if s)
    assert inside == sorted((i, j) for i in range(1, 4) for j in range(1, 4))
    assert len(res.segments) == 12
    check_contour(res)


def test_duplicate_and_dangling_segments():
    sq = [((0, 0), (3, 0)), ((3, 0), (3, 3)), ((3, 3), (0, 3)), ((0, 3), (0, 0))]
    a = repair(sq, 1)
    b = repair(sq + [((0, 0), (3, 0))] * 2 + [((1, 1), (2, 2))] * 2, 1)  # doubled copies cancel
    assert a.inside == b.inside and a.segments == b.segments
    c = repair(sq + [((3, 1), (5, 1))], 1)  # a dangling piece outside the square
    assert len(c.odd_cells) == 2 and odd_cells(c.grid, c.marked) == []
    check_contour(c)

History

Volumetric methods for repairing scans and models used signed distance fields and space carving in the 1990s, but they needed a well-defined inside, which a broken model does not have. In 2004 Tao Ju observed that the parity of the crossings on each grid edge is defined for any soup, and that its defects show up as boundary cycles that can be patched on the grid. His program PolyMender made the method widely used for repairing models for printing and simulation. Later work, such as the generalized winding number, gave other ways to define the inside of a broken model.

References

  1. Tao Ju, Robust repair of polygonal models, ACM Transactions on Graphics 23(3), 2004, 888 to 895 (SIGGRAPH 2004), the four steps (scan conversion of the polygons into an octree with the parity of each cell edge, patching of the boundary cycles of the dual surface, sign generation, and contouring)
  2. Mario Botsch, Leif Kobbelt, Mark Pauly, Pierre Alliez and Bruno Lévy, Polygon Mesh Processing, AK Peters, 2010, Chapter 8, Model Repair (volumetric repair, and its comparison with surface-based repair)
  3. Marco Attene, Marcel Campen and Leif Kobbelt, Polygon mesh repairing, an application perspective, ACM Computing Surveys 45(2), Article 15, 2013, the global, volumetric methods of repair and their effect on the input geometry

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.worst
  • 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
  • a scene preset for the example