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.
- Solves
- Mesh repair
- Time
- O(c) expected worst
- Space
- Θ(c) extra
- Where
- c = the number of corners, the sum of the face sizes
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
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 with , a face has the direction if it goes from to , and if it goes from to . The bit is 1 when face will be reversed.
ORIENT(F, P)- 1
E ← map from each edge {u, v} to its uses (f, d_f(e)); fail if an edge has 3 or more uses - 2
s_f ← unset for every face f - 3
for each face r with s_r unset do ▷ a new component K - 4
s_r ← 0; Q ← [r]; K ← [r] - 5
while Q is not empty do - 6
f ← the first face of Q, removed - 7
for each edge e of f with a second face g do - 8
want ← s_f xor [d_f(e) = d_g(e)] ▷ reverse g when it runs the same way - 9
if s_g is unset then s_g ← want; append g to Q and to K - 10
else if s_g ≠ want then mark K not orientable - 11
if K is orientable and has no border edge then - 12
W ← Σ det(p_a, p_b, p_c) over the fan triangles (a, b, c) of the faces of K, as oriented by s - 13
if W < 0 then s_f ← 1 − s_f for every f in K - 14
return each face f, reversed if s_f = 1
Line L8 is the whole rule. If is not reversed, must be reversed exactly when it runs the same way as . If 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, 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 , , , with the faces , , , . The faces and point inward, and and point outward.
| step | face | edge | directions | result |
|---|---|---|---|---|
| L4 | ||||
| L8 | both , the same | |||
| L8 | both , the same | |||
| L8 | and , opposite | |||
| L10 | the other 3 edges | no conflict |
Now the oriented faces are , , , , all pointing inward. In line L12 every term with the vertex 0 at the origin is zero, so . The sign is negative, so line L13 reverses all four faces. The result is , , , with , six times the volume of the tetrahedron.
For the Möbius strip with the five triangles , indices mod 5, the search sets the bits around the band in both directions. The band has five inner edges, and the five labels 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 between and as , where when the two faces run the same way along . 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, 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 with and a face that contains it, let if goes along from to , and if it goes from to . A flip vector gives each face a bit ; the face is reversed when , and its direction along becomes . A flip vector is consistent if the two faces of each inner edge then go along in opposite directions. Let if and if not. Then the condition for is
Let be the dual graph: one node for each face and one edge for each inner edge of the mesh, labelled . A component is a connected component of .
Claim 1. For each component , the loop of lines L4 to L10 sets for every face of and for no other face. It reports a conflict (line L10) if and only if has no consistent flip vector. If there is no conflict, the bits it sets are consistent on , and the only other consistent vector on is the complement.
Proof. Lines L5 to L9 are a breadth-first search of from : line L7 visits each inner edge of and its other face , and line L9 adds the first time it is reached. So the search reaches exactly the faces of . Each face gets its bit at line L9 from its parent in the search tree, with by line L8. So the bits satisfy (1) on every edge of the search tree.
Every edge of inside 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 , so the bits are a consistent vector on .
Conflict implies no consistent vector. Suppose the check of an edge fails, and let be any vector that satisfies (1) on all edges of . On the tree, (1) fixes from : by induction along the tree path, for every face of , because both and change by along each tree edge. Then , so breaks (1) on . So has no consistent vector.
Uniqueness. The same induction shows that a consistent vector on is when and the complement of when . Both are consistent, because complementing all bits does not change .
Equivalently, is orientable if and only if every cycle of in has an even sum of labels, the parity condition of a two-coloring.
Claim 2. Let be a closed, orientable component with exact coordinates, oriented by the bits , and let over the triangles of the fan triangulation of each face (line L12). Then does not depend on the choice of the fan, it changes sign when all faces of are reversed, and if the faces of bound a region in space without self-intersection, when the normals by the right-hand rule point out of , and 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 , is the signed volume of the tetrahedron , which is for the unit normal of the right-hand rule: the field 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 . By the divergence theorem with the field , whose divergence is 1, this is when is the outward normal, and when it is the inward one.
So, for such a component, line L13 flips all faces of when , 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 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 steps for corners in total. The volume sum and the final flip take steps.
Complexity
Let be the number of corners, the sum of the face sizes. Line L1 builds a hash map of the edges in 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 time. Line L12 adds determinants for faces. The total is expected time and space. With exact arithmetic on integer coordinates of bits, each determinant has about bits, and the sum of of them has 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 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, 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.
# 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
- 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)
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag A5KM8D Edit this page History Report an error Markdown