Algorithm Search⌘K

Algorithmintro

Consistent mesh orientation

Also called face orientation propagation.

Orients all faces of a connected mesh alike by a traversal that flips each neighbour whose shared edge runs the same way, then fixes outward normals by volume sign.

Time
O(c) expected worst
Space
Θ(c) extra
Where
c = the number of corners, the sum of the face sizes
Properties
deterministicexactiterative

Consistent mesh orientation gives all faces of a manifold mesh the same orientation, so that the two faces of each inner edge go along it in opposite directions, and then turns each closed part so that its normals point out. It is a breadth-first search over the faces: a face keeps its vertex order, and a neighbour is reversed when the shared edge runs the same way in both. If the search reaches a face a second time with the opposite demand, the part is not orientable, like a Möbius strip. For a closed part, the exact sign of the signed volume decides between the two orientations. The time is linear in the size of the mesh. It is one of the first steps of mesh repair.

In plain words

Each face of a mesh lists its corners in some order, and the order tells which side is the front. Two faces next to each other agree when they walk their shared side in opposite directions, like two gears that turn together.

Start at any face and trust it. Look at each neighbour. If it walks the shared side the same way, reverse its corner list. Then do the same from the neighbours, until every face of the piece is done. If you come back to a face that you already fixed and it now needs the other order, no fix exists: the piece is one-sided.

At the end the whole piece agrees, but it may face inward. For a closed piece, add up the signed volume that its faces enclose. If the sum is negative, reverse every face of the piece.

The problem

The input is a mesh as an indexed face set: vertex positions and faces, where each face is a list of distinct vertex indices. Each edge has one or two faces. The output reverses some faces, so that for each edge-connected part:

  • if the part is orientable, the two faces of each inner edge use it in opposite directions, and
  • if the part is also closed and bounds a region, the outward normal of each face follows the right-hand rule for its vertex order.

If a part is not orientable, the output says so. Three or more faces on one edge make the question ill-posed, so the algorithm rejects such a mesh; mesh repair must split the edge first.

The algorithm

For an edge e={u,v}e = \{u, v\} with u<vu < v, a face ff has the direction df(e)=+1d_f(e) = +1 if it goes from uu to vv, and −1-1 if it goes from vv to uu. The bit sfs_f is 1 when face ff will be reversed.

  1. ORIENT(F, P)
  2. 1E ← map from each edge {u, v} to its uses (f, d_f(e)); fail if an edge has 3 or more uses
  3. 2s_f ← unset for every face f
  4. 3for each face r with s_r unset do ▷ a new component K
  5. 4s_r ← 0; Q ← [r]; K ← [r]
  6. 5while Q is not empty do
  7. 6f ← the first face of Q, removed
  8. 7for each edge e of f with a second face g do
  9. 8want ← s_f xor [d_f(e) = d_g(e)] ▷ reverse g when it runs the same way
  10. 9if s_g is unset then s_g ← want; append g to Q and to K
  11. 10else if s_g ≠ want then mark K not orientable
  12. 11if K is orientable and has no border edge then
  13. 12W ← Σ det(p_a, p_b, p_c) over the fan triangles (a, b, c) of the faces of K, as oriented by s
  14. 13if W < 0 then s_f ← 1 − s_f for every f in K
  15. 14return each face f, reversed if s_f = 1

Line L8 is the whole rule. If ff is not reversed, gg must be reversed exactly when it runs the same way as ff. If ff is reversed, the demand is the opposite. Line L12 is six times the signed volume of the part, computed with the determinant of each triangle and the origin.

The predicate and its failure. Lines L1 to L10 use only vertex indices, so they are exact on any input. Line L13 is a sign test. In floating point, WW is a sum of many terms of both signs, and for a thin or far-from-the-origin part the rounding errors can be larger than the result, through catastrophic cancellation. The code of this page uses integer or rational coordinates, so the sign is exact. With floating point input, an exact sum of the products, as in Shewchuk's expansion arithmetic, gives the true sign. Moving the origin to a vertex of the part also makes the terms smaller.

Example

Take the tetrahedron 0=(0,0,0)0 = (0,0,0), 1=(1,0,0)1 = (1,0,0), 2=(0,1,0)2 = (0,1,0), 3=(0,0,1)3 = (0,0,1) with the faces f0=(0,1,2)f_0 = (0, 1, 2), f1=(0,1,3)f_1 = (0, 1, 3), f2=(1,2,3)f_2 = (1, 2, 3), f3=(0,2,3)f_3 = (0, 2, 3). The faces f0f_0 and f3f_3 point inward, and f1f_1 and f2f_2 point outward.

step face edge directions result
L4 f0f_0 s0=0s_0 = 0
L8 f0→f1f_0 \to f_1 {0,1}\{0, 1\} both 0→10 \to 1, the same s1=1s_1 = 1
L8 f0→f2f_0 \to f_2 {1,2}\{1, 2\} both 1→21 \to 2, the same s2=1s_2 = 1
L8 f0→f3f_0 \to f_3 {0,2}\{0, 2\} 2→02 \to 0 and 0→20 \to 2, opposite s3=0s_3 = 0
L10 f1,f2,f3f_1, f_2, f_3 the other 3 edges no conflict

Now the oriented faces are (0,1,2)(0, 1, 2), (3,1,0)(3, 1, 0), (3,2,1)(3, 2, 1), (0,2,3)(0, 2, 3), all pointing inward. In line L12 every term with the vertex 0 at the origin is zero, so W=det⁡(p3,p2,p1)=−1W = \det(p_3, p_2, p_1) = -1. The sign is negative, so line L13 reverses all four faces. The result is (2,1,0)(2, 1, 0), (0,1,3)(0, 1, 3), (1,2,3)(1, 2, 3), (3,2,0)(3, 2, 0) with W=1W = 1, six times the volume 1/61/6 of the tetrahedron.

For the Möbius strip with the five triangles (i,i+1,i+2)(i, i+1, i+2), indices mod 5, the search sets the bits around the band in both directions. The band has five inner edges, and the five labels λ\lambda have an odd sum, so the last check of an edge that closes the band asks for the opposite bit. Line L10 marks the strip as not orientable.

Correctness

Write the condition for an inner edge ee between ff and gg as sf⊕sg=λ(e)s_f \oplus s_g = \lambda(e), where λ(e)=1\lambda(e) = 1 when the two faces run the same way along ee. This is a system of equations over the bits, one for each edge of the dual graph, the graph with a node for each face and an edge for each inner edge. The search sets the bits along a spanning tree of each component so that the tree equations hold. Each other edge is then checked. If a check fails, no assignment works, because the tree forces every bit once the first bit is chosen. If no check fails, the assignment works, and its complement is the only other one. This is the same parity argument as the test of a bipartite graph. For a closed part that bounds a region, W/6W/6 is the volume of the region when the normals point out, by the divergence theorem, and minus the volume when they point in. The full proof is below.

Proof: The breadth-first flip propagation finds a consistent orientation exactly when one exists, and the volume sign makes a closed component face outwardfull

Setup. The input is a mesh whose faces each have at least 3 distinct vertices and whose edges each have one or two faces. For an edge e={u,v}e = \{u, v\} with u<vu < v and a face ff that contains it, let df(e)=+1d_f(e) = +1 if ff goes along ee from uu to vv, and −1-1 if it goes from vv to uu. A flip vector gives each face a bit sf∈{0,1}s_f \in \{0, 1\}; the face is reversed when sf=1s_f = 1, and its direction along ee becomes (−1)sfdf(e)(-1)^{s_f} d_f(e). A flip vector is consistent if the two faces f,gf, g of each inner edge ee then go along ee in opposite directions. Let λ(e)=1\lambda(e) = 1 if df(e)=dg(e)d_f(e) = d_g(e) and λ(e)=0\lambda(e) = 0 if not. Then the condition for ee is

(−1)sfdf(e)≠(−1)sgdg(e)  ⟺  sf⊕sg=λ(e).(1)(-1)^{s_f} d_f(e) \ne (-1)^{s_g} d_g(e) \iff s_f \oplus s_g = \lambda(e). \tag{1}

Let GG be the dual graph: one node for each face and one edge for each inner edge of the mesh, labelled λ(e)\lambda(e). A component is a connected component of GG.

Claim 1. For each component KK, the loop of lines L4 to L10 sets sgs_g for every face gg of KK and for no other face. It reports a conflict (line L10) if and only if KK has no consistent flip vector. If there is no conflict, the bits it sets are consistent on KK, and the only other consistent vector on KK is the complement.

Proof. Lines L5 to L9 are a breadth-first search of GG from rr: line L7 visits each inner edge of ff and its other face gg, and line L9 adds gg the first time it is reached. So the search reaches exactly the faces of KK. Each face g≠rg \ne r gets its bit at line L9 from its parent ff in the search tree, with sg=sf⊕λ(e)s_g = s_f \oplus \lambda(e) by line L8. So the bits satisfy (1) on every edge of the search tree.

Every edge of GG inside KK is checked by line L8 when its first end leaves the queue. If it is a tree edge, the check passes. If it is not, line L10 compares the bit already set with the bit that (1) asks for.

No conflict implies consistent. If no check fails, (1) holds on every edge of KK, so the bits are a consistent vector on KK.

Conflict implies no consistent vector. Suppose the check of an edge e={f,g}e = \{f, g\} fails, and let tt be any vector that satisfies (1) on all edges of KK. On the tree, (1) fixes tt from trt_r: by induction along the tree path, tx=tr⊕sxt_x = t_r \oplus s_x for every face xx of KK, because both tt and ss change by λ\lambda along each tree edge. Then tf⊕tg=sf⊕sg≠λ(e)t_f \oplus t_g = s_f \oplus s_g \ne \lambda(e), so tt breaks (1) on ee. So KK has no consistent vector.

Uniqueness. The same induction shows that a consistent vector on KK is ss when tr=0t_r = 0 and the complement of ss when tr=1t_r = 1. Both are consistent, because complementing all bits does not change sf⊕sgs_f \oplus s_g. □\square

Equivalently, KK is orientable if and only if every cycle of GG in KK has an even sum of labels, the parity condition of a two-coloring.

Claim 2. Let KK be a closed, orientable component with exact coordinates, oriented by the bits ss, and let W=∑det⁡(pa,pb,pc)W = \sum \det(p_a, p_b, p_c) over the triangles (a,b,c)(a, b, c) of the fan triangulation of each face (line L12). Then WW does not depend on the choice of the fan, it changes sign when all faces of KK are reversed, and if the faces of KK bound a region RR in space without self-intersection, W=6 vol(R)W = 6\,\mathrm{vol}(R) when the normals by the right-hand rule point out of RR, and W=−6 vol(R)W = -6\,\mathrm{vol}(R) when they point in.

Proof. Reversing a face reverses each of its fan triangles, which swaps two arguments of each determinant, so every term changes sign. For a triangle (a,b,c)(a, b, c), det⁡(pa,pb,pc)/6\det(p_a, p_b, p_c) / 6 is the signed volume of the tetrahedron (0,pa,pb,pc)(0, p_a, p_b, p_c), which is 13∫△x⋅n dA\frac{1}{3} \int_{\triangle} x \cdot n \, dA for the unit normal nn of the right-hand rule: the field x⋅nx \cdot n is constant on the plane of the triangle and equals the height of the tetrahedron over it. A planar face is cut into triangles with the same normal, and the integral is additive, so the sum over any fan triangulation is 13∫∂Rx⋅n dA\frac{1}{3} \int_{\partial R} x \cdot n \, dA. By the divergence theorem with the field x/3x / 3, whose divergence is 1, this is vol(R)\mathrm{vol}(R) when nn is the outward normal, and −vol(R)-\mathrm{vol}(R) when it is the inward one. □\square

So, for such a component, line L13 flips all faces of KK when W<0W < 0, and after it the normals point out. By claim 1, the flip keeps the orientation consistent, because the complement of a consistent vector is consistent. The arithmetic is exact, so the sign of WW is the true sign.

Termination. Each face enters the queue once, at line L4 or line L9, and each face has finitely many edges, so the search does O(c)O(c) steps for cc corners in total. The volume sum and the final flip take O(c)O(c) steps. ■\blacksquare

Complexity

Let cc be the number of corners, the sum of the face sizes. Line L1 builds a hash map of the edges in O(c)O(c) expected time. The search puts each face in the queue once and looks at each edge of each face once, so lines L3 to L10 take O(c)O(c) time. Line L12 adds c−2mc - 2m determinants for mm faces. The total is O(c)O(c) expected time and Θ(c)\Theta(c) space. With exact arithmetic on integer coordinates of bb bits, each determinant has about 3b3b bits, and the sum of cc of them has O(b+log⁡c)O(b + \log c) more.

Properties

  • Exact. The combinatorial part uses no arithmetic on coordinates. The volume sign is exact with exact arithmetic.
  • Unique up to the outward choice. An orientable connected part has exactly two consistent orientations, and the volume picks one.
  • Detects non-orientable parts. A Möbius strip or a Klein bottle gives a conflict in line L10.
  • Per component. Parts that share only a vertex, not an edge, are separate components and are oriented separately.

Variants and improvements

  • Union-find. The same equations can be solved with a disjoint-set structure with a parity bit on each link, which also works when the faces arrive one at a time.
  • Ray casting. For meshes with holes, inner walls and parts that only touch, the outward side is not defined by a volume. Takayama and others cast many rays from each face and choose the side that is seen more often from outside. This is a heuristic: it is measured on a large set of models, not proved, and the ray casting costs much more than the search.
  • Winding numbers. The generalized winding number tells, for any point, how many times the mesh wraps around it, even for a mesh with holes. It can choose the outward side of each part after the search.
  • Non-manifold edges. Some programs first cut the mesh at each edge with three or more faces, and then orient each piece. The result depends on how the faces at the edge are paired.

When to use it

Use it after vertex welding and before any step that needs normals, such as rendering with back-face culling, offsetting, mesh Boolean operations, or building a corner table or a half-edge structure, which need a consistent orientation. The traversal is the right tool when the mesh is manifold and closed. If the mesh has holes or self-intersections, orient each part with the traversal and decide the outward side with a winding number or with rays.

Pitfalls

  • Nested shells. A solid with a cavity has an outer shell and an inner shell. The normals of the inner shell must point into the cavity, away from the material, so the inner shell has negative volume. The rule of line L13 makes both shells positive, and so it turns the inner shell the wrong way. Decide the side of each shell by how deeply it is nested inside the others.
  • Open parts. A part with a border bounds no region, so WW has no meaning and depends on the origin. Do not flip open parts by the volume sign.
  • Self-intersecting parts. If a closed part crosses itself, WW is a sum of volumes weighted by winding numbers, and its sign can be wrong for some regions.
  • Floating point volume. A sum of many floating point determinants can have the wrong sign for a thin part far from the origin. Use exact arithmetic, or at least move the origin into the part.
  • Duplicate vertices. Faces that should be neighbours but use different copies of a vertex are not joined, and each one is oriented alone. Weld first.

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.

consistent_mesh_orientation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/consistent-mesh-orientation/. The authors are listed in prov/A5KM8D.jsonl.

"""Orient the faces of a mesh consistently, then make closed parts face outward.

A breadth-first search over the faces flips a neighbour when the shared edge
runs the same way in both faces. A conflict shows that the component is not
orientable, as for a Moebius strip. For a closed component, the exact signed
volume decides the outward side. Coordinates must be int or Fraction, so the
sign is exact.
"""

from collections import deque
from fractions import Fraction
from typing import NamedTuple, Optional, Sequence, Union

Num = Union[int, Fraction]


class Orientation(NamedTuple):
    faces: list[tuple[int, ...]]  # the faces, reversed where needed
    flipped: list[bool]  # whether each face was reversed
    component: list[int]  # the component number of each face
    orientable: list[bool]  # per component
    closed: list[bool]  # per component: no border edge
    volume6: list[Optional[Num]]  # per component: six times the signed volume after the fix


def det3(a: Sequence[Num], b: Sequence[Num], c: Sequence[Num]) -> Num:
    return (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0])
            + a[2] * (b[0] * c[1] - b[1] * c[0]))


def signed_volume6(points: Sequence[Sequence[Num]], faces: Sequence[Sequence[int]]) -> Num:
    """Six times the signed volume bounded by oriented faces (fan triangulation of each face)."""
    total: Num = 0
    for f in faces:
        for i in range(1, len(f) - 1):
            total += det3(points[f[0]], points[f[i]], points[f[i + 1]])
    return total


def orient(faces: Sequence[Sequence[int]], points: Optional[Sequence[Sequence[Num]]] = None) -> Orientation:
    """Orient each edge-connected component; flip closed components to positive volume.

    Raise ValueError if an edge has three or more faces.
    """
    faces = [tuple(f) for f in faces]
    m = len(faces)
    uses: dict[tuple[int, int], list[tuple[int, int]]] = {}  # @line L1
    for f, face in enumerate(faces):
        k = len(face)
        if k < 3 or len(set(face)) != k:
            raise ValueError(f"face {f} is not a valid polygon: {face}")
        for i in range(k):
            u, v = face[i], face[(i + 1) % k]
            key, d = ((u, v), 1) if u < v else ((v, u), -1)
            uses.setdefault(key, []).append((f, d))
    for key, lst in uses.items():
        if len(lst) > 2:
            raise ValueError(f"edge {key} has {len(lst)} faces")
    face_edges: list[list[tuple[tuple[int, int], int]]] = [[] for _ in range(m)]
    for key, lst in uses.items():
        for f, d in lst:
            face_edges[f].append((key, d))

    s: list[int] = [-1] * m  # @line L2
    comp = [-1] * m
    orientable: list[bool] = []
    closed: list[bool] = []
    volume6: list[Optional[Num]] = []
    for r in range(m):  # @line L3
        if s[r] != -1:
            continue
        cid = len(orientable)
        s[r], comp[r] = 0, cid  # @line L4
        queue, members, ok, is_closed = deque([r]), [r], True, True
        while queue:  # @line L5
            f = queue.popleft()  # @line L6
            for key, df in face_edges[f]:  # @line L7
                lst = uses[key]
                if len(lst) == 1:
                    is_closed = False
                    continue
                g, dg = lst[1] if lst[0][0] == f else lst[0]
                want = s[f] ^ (1 if df == dg else 0)  # @line L8
                if s[g] == -1:  # @line L9
                    s[g], comp[g] = want, cid
                    queue.append(g)
                    members.append(g)
                elif s[g] != want:  # @line L10
                    ok = False
        vol: Optional[Num] = None
        if ok and is_closed and points is not None:  # @line L11
            oriented = [faces[f][::-1] if s[f] else faces[f] for f in members]
            vol = signed_volume6(points, oriented)  # @line L12
            if vol < 0:  # @line L13
                for f in members:
                    s[f] ^= 1
                vol = -vol
        orientable.append(ok)
        closed.append(is_closed)
        volume6.append(vol)
    out = [faces[f][::-1] if s[f] else faces[f] for f in range(m)]  # @line L14
    return Orientation(out, [x == 1 for x in s], comp, orientable, closed, volume6)


def is_consistent(faces: Sequence[Sequence[int]]) -> bool:
    """True if no directed edge is used twice."""
    seen: set[tuple[int, int]] = set()
    for face in faces:
        k = len(face)
        for i in range(k):
            e = (face[i], face[(i + 1) % k])
            if e in seen:
                return False
            seen.add(e)
    return True
test_consistent_mesh_orientation.py 204 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/consistent-mesh-orientation/. The authors are listed in prov/A5KM8D.jsonl.

import itertools
import random
from fractions import Fraction

from consistent_mesh_orientation import orient

# ---- brute force: try every vector of flips ----


def directed_ok(faces):
    seen = set()
    for f in faces:
        for i in range(len(f)):
            e = (f[i], f[(i + 1) % len(f)])
            if e in seen:
                return False
            seen.add(e)
    return True


def brute_components(faces):
    comp = list(range(len(faces)))

    def find(x):
        while comp[x] != x:
            x = comp[x]
        return x

    def edges(f):
        return {frozenset((f[i], f[(i + 1) % len(f)])) for i in range(len(f))}

    for i, j in itertools.combinations(range(len(faces)), 2):
        if edges(faces[i]) & edges(faces[j]):
            comp[find(i)] = find(j)
    groups = {}
    for i in range(len(faces)):
        groups.setdefault(find(i), []).append(i)
    return list(groups.values())


def brute_consistent_flips(faces, members):
    out = []
    for bits in itertools.product((0, 1), repeat=len(members)):
        sub = [faces[f][::-1] if b else faces[f] for f, b in zip(members, bits)]
        if directed_ok(sub):
            out.append(bits)
    return out


def outward_on_convex(points, face, centre):
    """For a convex polytope: the right-hand normal points away from an interior point."""
    a, b, c = (points[v] for v in face[:3])
    u = [b[k] - a[k] for k in range(3)]
    w = [c[k] - a[k] for k in range(3)]
    n = (u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0])
    return sum(n[k] * (a[k] - centre[k]) for k in range(3)) > 0


# ---- shapes (faces oriented outward for the given points) ----


def tetra(rng):
    while True:
        pts = [tuple(rng.randint(-5, 5) for _ in range(3)) for _ in range(4)]
        faces = [(0, 2, 1), (0, 1, 3), (1, 2, 3), (0, 3, 2)]
        a, b, c, d = pts
        det = sum(
            (b[i] - a[i]) * ((c[(i + 1) % 3] - a[(i + 1) % 3]) * (d[(i + 2) % 3] - a[(i + 2) % 3])
                             - (c[(i + 2) % 3] - a[(i + 2) % 3]) * (d[(i + 1) % 3] - a[(i + 1) % 3]))
            for i in range(3))
        if det != 0:
            return pts, faces, True


def octahedron(rng):
    a, b, c = rng.randint(1, 5), rng.randint(1, 5), rng.randint(1, 5)
    pts = [(0, 0, c), (0, 0, -c), (a, 0, 0), (0, b, 0), (-a, 0, 0), (0, -b, 0)]
    eq = [2, 3, 4, 5]
    faces = []
    for i in range(4):
        x, y = eq[i], eq[(i + 1) % 4]
        faces += [(0, x, y), (1, y, x)]
    return pts, faces, True


def cube(rng):
    s = rng.randint(1, 4)
    pts = [(x * s, y * s, z * s) for z in (0, 1) for y in (0, 1) for x in (0, 1)]
    # index = x + 2y + 4z
    faces = [(0, 2, 3, 1), (4, 5, 7, 6), (0, 1, 5, 4), (1, 3, 7, 5), (3, 2, 6, 7), (2, 0, 4, 6)]
    return pts, faces, True


def bipyramid(rng):
    h, k = rng.randint(1, 5), rng.randint(1, 5)
    pts = [(3, 0, 0), (-2, 2, 0), (-2, -2, 0), (0, 0, h), (0, 0, -k)]
    faces = [(0, 1, 3), (1, 2, 3), (2, 0, 3), (1, 0, 4), (2, 1, 4), (0, 2, 4)]
    return pts, faces, True


def moebius(rng):
    return None, [(i, (i + 1) % 5, (i + 2) % 5) for i in range(5)], False


def disk(rng):
    faces = []
    for i in range(2):
        for j in range(2):
            p, q, r, s = 3 * i + j, 3 * (i + 1) + j, 3 * (i + 1) + j + 1, 3 * i + j + 1
            faces += [(p, q, r), (p, r, s)]
    return None, faces, False


SHAPES = [tetra, octahedron, cube, bipyramid, moebius, disk]


def scramble(rng, faces):
    out = []
    for f in faces:
        k = rng.randrange(len(f))
        f = f[k:] + f[:k]
        out.append(f[::-1] if rng.random() < 0.5 else f)
    return out


def make_case(rng):
    parts = rng.sample(SHAPES, rng.choice((1, 1, 2)))
    pts_all, faces_all, convex_parts, base = [], [], [], 0
    for shape in parts:
        pts, faces, convex = shape(rng)
        nv = max(max(f) for f in faces) + 1
        shift = (100 * len(convex_parts), 0, 0)
        pts = pts or [(0, 0, 0)] * nv
        pts_all += [tuple(p[k] + shift[k] for k in range(3)) for p in pts]
        faces_all += [tuple(v + base for v in f) for f in faces]
        if convex:
            centre = tuple(Fraction(sum(p[k] for p in pts), len(pts)) + shift[k] for k in range(3))
            convex_parts.append((set(range(len(faces_all) - len(faces), len(faces_all))), centre))
        base += nv
    return pts_all, scramble(rng, faces_all), convex_parts


# ---- tests ----


def test_page_example():
    # a square of two triangles, the second one flipped
    r = orient([(0, 1, 2), (0, 3, 2)])
    assert r.faces == [(0, 1, 2), (2, 3, 0)] and r.flipped == [False, True]
    assert r.orientable == [True] and r.closed == [False]
    pts = [(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)]
    r = orient([(0, 1, 2), (0, 1, 3), (1, 2, 3), (0, 2, 3)], pts)  # every face points in some way
    assert directed_ok(r.faces) and r.volume6 == [1]
    assert r.faces == [(2, 1, 0), (0, 1, 3), (1, 2, 3), (3, 2, 0)]


def test_moebius_is_not_orientable():
    r = orient([(i, (i + 1) % 5, (i + 2) % 5) for i in range(5)])
    assert r.orientable == [False] and r.closed == [False]


def test_three_faces_on_an_edge_is_rejected():
    try:
        orient([(0, 1, 2), (1, 0, 3), (0, 1, 4)])
    except ValueError:
        return
    raise AssertionError("accepted a non-manifold edge")


def test_against_brute_force_random():
    rng = random.Random(1880)
    for _ in range(600):
        pts, faces, convex_parts = make_case(rng)
        r = orient(faces, pts)
        for members in brute_components(faces):
            cid = r.component[members[0]]
            assert all(r.component[f] == cid for f in members)
            assert sum(1 for c in r.component if c == cid) == len(members)
            flips = brute_consistent_flips(faces, members)
            assert r.orientable[cid] == bool(flips)
            if flips:
                assert len(flips) == 2  # one orientation and its reverse
                got = tuple(int(r.flipped[f]) for f in members)
                assert got in flips
        for face_set, centre in convex_parts:
            for f in face_set:
                assert outward_on_convex(pts, r.faces[f], centre)


def test_large_torus():
    rng = random.Random(5)
    a, b = 6, 7
    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)]
    res = orient(scramble(rng, faces))
    assert res.orientable == [True] and res.closed == [True]
    assert directed_ok(res.faces)

History

The traversal is folklore of mesh processing and of solid modeling, and it is part of the repair steps that Botsch and others and Attene, Campen and Kobbelt describe. The parity argument is the same one that tells whether a graph is bipartite. In 2014 Takayama, Jacobson, Kavan and Sorkine-Hornung gave a method based on rays for the many models in online collections where the traversal does not apply, because the meshes are not manifold or not closed.

References

  1. Mario Botsch, Leif Kobbelt, Mark Pauly, Pierre Alliez and Bruno Lévy, Polygon Mesh Processing, AK Peters, 2010, Chapter 8, Model Repair (inconsistent orientation as a type of artifact, and its repair)
  2. Marco Attene, Marcel Campen and Leif Kobbelt, Polygon mesh repairing, an application perspective, ACM Computing Surveys 45(2), Article 15, 2013, the parts on orientation defects and on the methods that fix them
  3. Kenshi Takayama, Alec Jacobson, Ladislav Kavan and Olga Sorkine-Hornung, A simple method for correcting facet orientations in polygon meshes based on ray casting, Journal of Computer Graphics Techniques 3(4), 2014, 53 to 63, the method of visibility sampling by rays, for meshes where the traversal of this page does not apply

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
  • History with a source
  • a scene preset for the example