Algorithmresearch
Generalized winding number
Also called Jacobson winding number.
Jacobson, Kavan and Sorkine's sum of signed solid angles of a mesh at a point, which is 1 inside and 0 outside a closed mesh and degrades smoothly for broken ones.
- Time
- O(F) direct · tree_worst
- Space
- O(1) directO(F) tree
- Where
- F = the number of triangles
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Alec Jacobson, Ladislav Kavan, Olga Sorkine Hornung, 2013
The generalized winding number of a triangle mesh at a point is the sum of the signed solid angles of all triangles seen from , divided by , the solid angle of the whole sphere. For a closed mesh this is the classical winding number: an integer, 1 inside and 0 outside a closed surface that does not cut itself, and the number of times the surface wraps around in general. The formula makes sense for any mesh, also one with holes, gaps, overlaps or self-intersections. Then the value is no longer an integer, but it changes by exactly 1 across each triangle and smoothly elsewhere, and it stays close to 1 deep inside and close to 0 far outside. Alec Jacobson, Ladislav Kavan and Olga Sorkine-Hornung proposed it in 2013 as an inside test for broken meshes. It is the 3D form of the winding number algorithm for polygons, and it is the inside rule behind robust mesh Boolean operations.
In plain words
Stand at a point and look around. Each small triangle of the surface covers a patch of your view. Count that patch as positive if you see the back of the triangle, and negative if you see its front.
If the surface is closed and you are inside, the backs of the triangles cover your whole view once, so the total is one full view. If you are outside, every patch you see from the front is cancelled by a patch you see from the back, and the total is zero.
If the surface has a hole, the hole leaves a gap in your view. Inside, the total is then a bit less than one, but it is still much closer to one than to zero. So rounding the total still says inside or outside in most places.
The problem
The input is a list of triangles with faces oriented so that the outward normal follows the right-hand rule, and a query point not on any triangle. The output is a number that equals the winding number of the surface around when the mesh is closed, and that tells inside from outside as well as possible when it is not.
The algorithm
The solid angle of a triangle seen from has a closed formula, due to Van Oosterom and Strackee. With , , :
The determinant is , the orientation test of against the plane of , so when is behind . Computing the angle with keeps it in .
WINDING-NUMBER(M, p)- 1
s ← 0 - 2
for each triangle T = (A, B, C) of M do - 3
a ← A − p; b ← B − p; c ← C − p; num ← det[a b c] - 4
den ← |a||b||c| + (a·b)|c| + (a·c)|b| + (b·c)|a| - 5
s ← s + 2 · atan2(num, den) - 6
return s / (4π)
The tree version. For many queries, Jacobson and coauthors build a tree of patches with bounding boxes. If is outside the box of a patch, the patch has the same total solid angle as any surface with the same boundary inside the box, for example a fan of triangles from one boundary vertex over the boundary edges. A patch of a smooth surface has a short boundary, so its fan has far fewer triangles than the patch. Patches whose box contains are split into their children or summed directly. A closed patch has an empty fan and contributes 0 from outside its box.
Degenerate cases. A point on a triangle has no defined value; at a point inside a face, the limits from the two sides differ by 1, and the formula returns one of them or a value between, depending on the sign of a zero. A triangle with zero area has . Repeated triangles add up, and two copies with opposite orientations cancel. If is a vertex, , the formula gives atan2(0, 0) = 0 for the triangles at that vertex, and the result has no meaning.
Example
Take the unit cube, 12 triangles with outward normals, and . For the triangle , , of the bottom face, , , .
| step | value |
|---|---|
| L3 | : is behind the face |
| L4 | $ |
| L5 | , so |
| L6 | by symmetry all 12 triangles give , so |
At , outside, the six faces give angles of both signs, and the sum is 0. Now remove the bottom face. The cube is open, and at the centre , because the missing face covered one sixth of the view. At the centre of the missing face , halfway between inside and outside. Rounding still classifies the centre as inside.
When the arithmetic is floating point. Next to an edge of the mesh the formula loses its accuracy. Put at height above the midpoint of the diagonal of the bottom face, inside the cube. For the triangle whose diagonal is right under , and point in nearly opposite directions, , and the denominator is a difference of nearly equal numbers, a case of catastrophic cancellation. With doubles, is at , at , at and at , while the exact value is 1. At , away from the diagonal, the float value is correct. The fix depends on the use. For a closed mesh, the exact answer is a signed count of ray crossings with exact predicates, which the tests of this page compute in rational arithmetic, see ray casting and exact predicates; it can be used when is too close to . For a broken mesh there is no exact answer to fall back on, and points that close to the surface are ambiguous anyway. This is the robustness problem of geometry.
Correctness
The solid angle of a triangle is the signed area of its shadow on the unit sphere around , so the sum of the solid angles is the integral over all directions of the signed number of triangles that the ray from in direction hits. For a closed mesh this number does not change when crosses the shadow of an edge, because the two triangles at the edge change it by and . So it is the same integer for almost all directions, and , which is also what a signed ray count finds. As goes to infinity, goes to 0, so it is 0 on the outside. Crossing one face against its normal raises by exactly 1, because the solid angle of that face jumps from to ; this holds for broken meshes too. So a closed surface that does not cut itself has inside. The fan of a patch has the same boundary, so the patch minus its fan is closed and has winding number 0 at points outside the box. The full proof is below.
Proof: The generalized winding number of a closed mesh is an integer equal to the signed ray crossing count, 0 or 1 for an embedded closed surface, and it jumps by 1 across a face of any meshfull
Setting. A mesh is a finite list of triangles in , oriented so that the outward normal follows the right-hand rule. Triangles may intersect, repeat or have any orientation; the list is a 2-chain. Its boundary is the 1-chain , where an edge cancels against . The mesh is closed if the boundary is 0. For a point not on the mesh, is the signed area of the radial projection of onto the unit sphere around , positive when is behind (on the side opposite to ), and
Claim.
- The formula of Van Oosterom and Strackee, with , , , gives .
- If the mesh is closed, then for every direction whose ray from misses all edges and vertices and is not in the plane of any triangle, , with when . In particular is an integer, and the exact ray count of the code computes it.
- If the mesh is a closed oriented 2-manifold without self-intersections and its normals point out of the solid it bounds, then inside and outside.
- For any mesh, is continuous off the mesh, and across a point in the interior of exactly one triangle, just behind the triangle minus just in front of it is .
- For a set of triangles whose bounding box does not contain , , where is the fan over the boundary edges of from one boundary vertex . So the tree version computes the same .
Step 1 (part 1). This is the result of Van Oosterom and Strackee (1983). We check the sign. , and has the direction of when the triangle is seen counterclockwise from the side where points, so , which is positive exactly when is behind . The denominator is positive for small triangles far from , so is then small with the sign of the determinant, and both sides of the formula are continuous in off the plane of and off the triangle. The formula is the half-angle form of the spherical excess of the projected triangle; picks the angle in for , which is right because .
Step 2 (part 2). For a direction , let , with the sign of . The radial projection of covers the directions whose ray hits , once, and its signed area is . If is behind , every ray from that hits has and ; if is in front, both signs are negative. So , and .
Let be the set of directions of the claim. Its complement is the union of the projections of the edges, finitely many arcs of great circles, so is the sphere minus a set of measure 0. Take a path between two directions of that crosses the arcs transversally, at points interior to one arc each (possible because the arcs meet in finitely many points). When the path crosses the projection of an edge , the ray stops or starts hitting each triangle that has and as corners; a triangle with the directed edge changes by , and one with changes it by , so the total change is the coefficient of in the boundary chain, which is 0 for a closed mesh. So is the same constant on all of , , and .
The code of the page computes for a random rational in exact rational arithmetic and tries another when the ray touches an edge, a vertex or a plane of a triangle, so it returns exactly. It stops with probability 1, because the bad directions are a set of measure 0 (in practice the first direction works).
Step 3 (part 4). Each is continuous in off , so is continuous off the mesh. Let be in the interior of exactly one triangle . Every other triangle has continuous near . As moves from just in front of to just behind it, through , the projection of becomes a hemisphere seen from the front and a hemisphere seen from behind, so goes from close to to close to . The jump of is .
Step 4 (part 3). By part 2, is an integer off a closed mesh, and by part 4 it is continuous there, so it is constant on each connected component of the complement. When , every , so on the unbounded component. A closed embedded 2-manifold divides space into two components, the inside and the outside (the Jordan-Brouwer separation theorem for polyhedral surfaces). Crossing a face from the outside, where the normal points, to the inside changes by by part 4. So inside.
Step 5 (part 5). The chain is closed: the boundary of is the sum of over the boundary edges of ; the edges and cancel because each vertex has as many boundary edges going in as going out (the boundary of a chain is a cycle), and the rest is the boundary of . Triangles of the fan with are degenerate, have and are left out. All triangles of lie in the convex hull of the vertices of , which is inside the bounding box. If is outside the box, a ray from away from the box misses all of them, so by part 2 the winding number of the closed chain is 0, that is . A patch inside the box is split or summed directly, so the tree gives the same sum as the direct formula.
Termination. The direct sum visits each triangle once. The tree visits each node at most once, and each node is either summed, closed by its fan, or split into its two children, so it stops after at most nodes for triangles.
What floating point does. The proof is about the exact values. The code computes in floating point, and next to an edge the denominator of part 1 is a difference of nearly equal numbers. The tests show a point above the middle of a face diagonal of the unit cube where the float sum gives instead of 1.
Complexity
The direct sum takes time per query for triangles and extra space. The tree takes space and time per query in the worst case, but it is much faster in practice, because most patches are far from and are replaced by small fans. On a closed polycube with 728 triangles, 200 queries took 1.58 s with the direct sum and 0.19 s with the tree in the Python code of the page. Barill and coauthors (2018) replace the fans by a truncated multipole expansion of each patch, which brings the cost per query to about for a given accuracy.
Properties
- Exact for closed meshes. In exact arithmetic, is the integer winding number.
- Robust for broken meshes. Holes, gaps and small overlaps change by small amounts away from them, so rounding or thresholding at still classifies most points.
- Harmonic. Off the surface is a harmonic function of , smooth, with no local maximum or minimum.
- Jump of 1. Across a triangle jumps by exactly 1, for any mesh.
- Order independent. The result does not depend on the order of the triangles or on how they are connected, only on their positions and orientations.
Variants and improvements
- Winding numbers in 2D. For a polygon the same sum of signed angles over is the winding number algorithm, and for a closed polygon it gives the point in polygon answer.
- Point clouds and triangle soups. Barill, Dickson, Schmidt, Levin and Jacobson (2018) evaluate fast winding numbers for oriented point clouds with a multipole tree.
- Segmentation of a volume mesh. The original paper builds a tetrahedral mesh of the bounding box, evaluates at the tetrahedra, and chooses the inside by a graph cut that trades against a smooth boundary.
- Exact winding numbers of cells. Mesh arrangements compute the winding number of every cell of the arrangement exactly, by propagating it across the faces with the jump of 1, which avoids solid angles altogether.
When to use it
Use it to decide inside and outside for a mesh that is not watertight: for mesh repair, voxelization, the inside test of a signed distance function, or Booleans on bad input. For a closed mesh where exact answers matter, a signed ray count with exact predicates is cheaper and exact, see ray casting. For many queries, use the tree or a fast multipole version.
Pitfalls
- Wrong orientation. A face with the wrong orientation counts with the wrong sign; a mesh with all faces reversed gives inside. Fix the orientation first, see the mesh repair problem.
- Points next to the surface. Near an edge the float value loses digits: at a distance of of the edge length it is off by , and at it cannot tell inside from outside, as the example shows.
- Nested or overlapping shells. Two shells that overlap give in the overlap. Testing means union, and exactly means something else.
- Big holes. A missing face of a cube gives at the centre but at the hole. Points near a large hole cannot be classified, and no inside test can do better without more information.
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/generalized-winding-number/. The authors are listed in prov/CVGJTP.jsonl.
"""Generalized winding number of a triangle mesh (Jacobson, Kavan and Sorkine-Hornung 2013).
w(p) = (1 / 4 pi) * sum over triangles of the signed solid angle of the
triangle seen from p. Faces are oriented so that the outward normal follows
the right-hand rule, so w = 1 inside and w = 0 outside a closed mesh.
The solid angle uses the formula of Van Oosterom and Strackee (1983): with
a, b, c the corners minus p and |a|, |b|, |c| their lengths,
tan(Omega / 2) = det[a b c] / (|a||b||c| + (a.b)|c| + (a.c)|b| + (b.c)|a|).
The tree version groups faces into patches with a bounding box. For a query
outside the box of a patch, the patch has the same winding number as a fan
over its boundary loops, which has fewer triangles.
The evaluation is in floating point. exact_ray_winding is an exact
reference: a signed count of ray crossings in rational arithmetic.
"""
import math
import random
from fractions import Fraction
from mp3geom import cross, dot, sub
def solid_angle(a, b, c, p):
"""Signed solid angle of the triangle abc seen from p, in (-2 pi, 2 pi)."""
a, b, c = (tuple(float(x) - float(y) for x, y in zip(q, p)) for q in (a, b, c))
la, lb, lc = (math.sqrt(dot(q, q)) for q in (a, b, c))
det = dot(a, cross(b, c)) # @line L3
den = la * lb * lc + dot(a, b) * lc + dot(a, c) * lb + dot(b, c) * la # @line L4
return 2 * math.atan2(det, den) # @line L5
def winding_number(points, faces, p):
"""Direct sum over all faces."""
total = 0.0 # @line L1
for f in faces: # @line L2
total += solid_angle(points[f[0]], points[f[1]], points[f[2]], p)
return total / (4 * math.pi) # @line L6
def boundary_edges(faces):
"""Directed edges (i, j) of the faces whose reverse (j, i) is not an edge of the faces, with multiplicity."""
count = {}
for f in faces:
for k in range(3):
e = (f[k], f[(k + 1) % 3])
count[e] = count.get(e, 0) + 1
out = []
for (i, j), m in count.items():
net = m - count.get((j, i), 0)
out += [(i, j)] * max(net, 0)
return out
class Node:
__slots__ = ("lo", "hi", "faces", "children", "cap")
def build_tree(points, faces, leaf_size=8):
"""A tree of patches with bounding boxes and closing fans."""
def make(ids):
node = Node()
pts = [points[v] for i in ids for v in faces[i]]
node.lo = tuple(min(float(q[k]) for q in pts) for k in range(3))
node.hi = tuple(max(float(q[k]) for q in pts) for k in range(3))
node.faces = ids
node.children = []
edges = boundary_edges([faces[i] for i in ids])
node.cap = None
if edges:
centre = edges[0][0]
node.cap = [(centre, i, j) for i, j in edges if centre not in (i, j)]
else:
node.cap = []
if len(ids) > leaf_size:
axis = max(range(3), key=lambda k: node.hi[k] - node.lo[k])
key = lambda i: sum(float(points[v][axis]) for v in faces[i])
s = sorted(ids, key=key)
half = len(s) // 2
node.children = [make(s[:half]), make(s[half:])]
return node
return make(list(range(len(faces))))
def winding_number_tree(points, faces, tree, p):
"""The same value as winding_number, with closing fans for patches whose box does not contain p."""
q = tuple(float(x) for x in p)
stack, total = [tree], 0.0
while stack:
node = stack.pop()
inside = all(node.lo[k] <= q[k] <= node.hi[k] for k in range(3))
if not inside and len(node.cap) < len(node.faces):
for f in node.cap:
total += solid_angle(points[f[0]], points[f[1]], points[f[2]], p)
elif node.children:
stack.extend(node.children)
else:
for i in node.faces:
f = faces[i]
total += solid_angle(points[f[0]], points[f[1]], points[f[2]], p)
return total / (4 * math.pi)
def exact_ray_winding(points, faces, p, rng=None):
"""Exact winding number of a closed mesh at p (not on the mesh), by a signed ray crossing count.
A ray from p in a random rational direction d crosses a triangle with
normal n; the crossing counts sign(d . n). If the ray hits an edge, a
vertex or lies in the plane of a triangle, another direction is tried.
"""
rng = rng or random.Random(0)
p = tuple(Fraction(x) for x in p)
while True:
d = tuple(Fraction(rng.randint(-10**6, 10**6), 10**6) for _ in range(3))
if d == (0, 0, 0):
continue
total, ok = 0, True
for f in faces:
a, b, c = (tuple(Fraction(x) for x in points[v]) for v in f)
e1, e2 = sub(b, a), sub(c, a)
n = cross(e1, e2)
den = dot(d, n)
if den == 0:
if dot(sub(p, a), n) == 0:
ok = False
break
continue
t = dot(sub(a, p), n) / den
if t < 0:
continue
x = tuple(pi + t * di for pi, di in zip(p, d))
# barycentric signs of x in abc, by the orientation of sub-triangles against n
s = [dot(cross(sub(v, x), sub(w, x)), n) for v, w in ((b, c), (c, a), (a, b))]
if t == 0:
if all(v >= 0 for v in s):
raise ValueError("p is on the mesh")
continue
if any(v == 0 for v in s):
ok = False
break
if all(v > 0 for v in s):
total += 1 if den > 0 else -1
if ok:
return total
mp3geom.py 136 lines
# SPDX-License-Identifier: MIT
# Shared helper of the mp3 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small tools for triangle meshes, used by the mp3 pages.
Points are tuples of int, fractions.Fraction or float. The predicates are
exact when the coordinates are int or Fraction. A mesh is a list of faces,
each a tuple of three vertex indices, oriented so that the outward normal
follows the right-hand rule (counterclockwise seen from outside).
"""
from fractions import Fraction
def sub(a, b):
return tuple(x - y for x, y in zip(a, b))
def add(a, b):
return tuple(x + y for x, y in zip(a, b))
def scale(s, a):
return tuple(s * x for x in a)
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
def cross(a, b):
return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])
def orient2d(a, b, c):
"""Twice the signed area of triangle abc: > 0 if counterclockwise."""
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
def orient3d(a, b, c, d):
"""((b - a) x (c - a)) . (d - a): > 0 if d is on the side of the normal of abc."""
return dot(cross(sub(b, a), sub(c, a)), sub(d, a))
def sign(x):
return (x > 0) - (x < 0)
def solve(a, b, tol=0.0):
"""Solve a x = b by Gaussian elimination with partial pivoting.
a is a list of n rows of length n, b is a list of n rows of length m
(m right-hand sides). Entries are Fraction (exact) or float. Returns the
n rows of x. Raises ValueError if a pivot has absolute value <= tol, so
an exact singular matrix always raises when tol is 0.
"""
n = len(a)
m = len(b[0]) if n else 0
rows = [list(a[i]) + list(b[i]) for i in range(n)]
for col in range(n):
piv = max(range(col, n), key=lambda r: abs(rows[r][col]))
if abs(rows[piv][col]) <= tol:
raise ValueError("singular matrix")
rows[col], rows[piv] = rows[piv], rows[col]
pr = rows[col]
inv = 1 / pr[col] if isinstance(pr[col], float) else Fraction(1) / pr[col]
for r in range(col + 1, n):
f = rows[r][col]
if f:
f = f * inv
row = rows[r]
for k in range(col, n + m):
if pr[k]:
row[k] -= f * pr[k]
x = [[0] * m for _ in range(n)]
for i in range(n - 1, -1, -1):
row = rows[i]
for k in range(m):
s = row[n + k]
for j in range(i + 1, n):
if row[j]:
s -= row[j] * x[j][k]
x[i][k] = s / row[i] if isinstance(s, float) or isinstance(row[i], float) else Fraction(s) / row[i]
return x
def directed_edges(faces):
"""Map each directed edge (i, j) to (face index, corner of i). Raises on a repeated directed edge."""
out = {}
for f, tri in enumerate(faces):
for k in range(3):
e = (tri[k], tri[(k + 1) % 3])
if e in out:
raise ValueError("directed edge %r used twice: not an oriented manifold" % (e,))
out[e] = (f, k)
return out
def neighbours(faces):
"""Map each vertex to the set of its neighbours."""
nb = {}
for tri in faces:
for k in range(3):
i, j = tri[k], tri[(k + 1) % 3]
nb.setdefault(i, set()).add(j)
nb.setdefault(j, set()).add(i)
return nb
def boundary_loop(faces):
"""The boundary of an oriented disk as one vertex loop, in the order of the face orientation."""
de = directed_edges(faces)
nxt = {}
for i, j in de:
if (j, i) not in de:
if i in nxt:
raise ValueError("boundary vertex %r is not manifold" % (i,))
nxt[i] = j
if not nxt:
raise ValueError("the mesh has no boundary")
start = min(nxt)
loop = [start]
while True:
v = nxt[loop[-1]]
if v == start:
break
loop.append(v)
if len(loop) != len(nxt):
raise ValueError("the boundary has more than one loop")
return loop
def euler_characteristic(faces):
verts = {v for tri in faces for v in tri}
edges = {frozenset((tri[k], tri[(k + 1) % 3])) for tri in faces for k in range(3)}
return len(verts) - len(edges) + len(faces)
test_generalized_winding_number.py 163 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generalized-winding-number/. The authors are listed in prov/CVGJTP.jsonl.
import math
import random
from fractions import Fraction
from generalized_winding_number import (
build_tree,
exact_ray_winding,
solid_angle,
winding_number,
winding_number_tree,
)
QUADS = [ # the six faces of the unit cube, counterclockwise seen from outside
((0, 0, 0), (0, 1, 0), (1, 1, 0), (1, 0, 0)),
((0, 0, 1), (1, 0, 1), (1, 1, 1), (0, 1, 1)),
((0, 0, 0), (1, 0, 0), (1, 0, 1), (0, 0, 1)),
((0, 1, 0), (0, 1, 1), (1, 1, 1), (1, 1, 0)),
((0, 0, 0), (0, 0, 1), (0, 1, 1), (0, 1, 0)),
((1, 0, 0), (1, 1, 0), (1, 1, 1), (1, 0, 1)),
]
def add_cube(points, faces, origin, size, flip=False):
"""Append an axis-aligned cube; its faces point outward unless flip."""
index = {}
for q in QUADS:
ids = []
for v in q:
if v not in index:
index[v] = len(points)
points.append(tuple(o + size * x for o, x in zip(origin, v)))
ids.append(index[v])
a, b, c, d = ids
tris = [(a, b, c), (a, c, d)]
faces += [(x, z, y) for x, y, z in tris] if flip else tris
def polycube(rng, k=3, fill=0.5):
"""The boundary of a random union of unit cubes in a k x k x k grid."""
cells = {(x, y, z) for x in range(k) for y in range(k) for z in range(k) if rng.random() < fill}
cells.add((1, 1, 1))
points, index, faces = [], {}, []
def vid(v):
if v not in index:
index[v] = len(points)
points.append(v)
return index[v]
for cell in cells:
for q in QUADS:
# the normal of the quad, from its first three corners
normal = tuple(
(q[1][(k1 + 1) % 3] - q[0][(k1 + 1) % 3]) * (q[2][(k1 + 2) % 3] - q[0][(k1 + 2) % 3])
- (q[1][(k1 + 2) % 3] - q[0][(k1 + 2) % 3]) * (q[2][(k1 + 1) % 3] - q[0][(k1 + 1) % 3])
for k1 in range(3)
)
if tuple(c + n for c, n in zip(cell, normal)) in cells:
continue
a, b, c, d = (vid(tuple(c0 + x for c0, x in zip(cell, v))) for v in q)
faces += [(a, b, c), (a, c, d)]
return points, faces, cells
def random_point(rng, lo, hi):
return tuple(Fraction(rng.randint(lo * 97, hi * 97) * 2 + 1, 194) for _ in range(3))
def test_cube_is_one_inside_and_zero_outside() -> None:
points, faces = [], []
add_cube(points, faces, (0, 0, 0), 1)
rng = random.Random(1)
for _ in range(200):
p = random_point(rng, -1, 2)
exact = exact_ray_winding(points, faces, p, rng)
assert exact in (0, 1)
assert exact == (1 if all(0 < x < 1 for x in p) else 0)
assert abs(winding_number(points, faces, p) - exact) < 1e-9
def test_polycubes_against_exact_ray_count() -> None:
rng = random.Random(2013)
for _ in range(6):
points, faces, cells = polycube(rng)
for _ in range(60):
p = random_point(rng, -1, 4)
exact = exact_ray_winding(points, faces, p, rng)
inside = tuple(math.floor(x) for x in p) in cells
assert exact == (1 if inside else 0)
assert abs(winding_number(points, faces, p) - exact) < 1e-9
def test_nested_and_reversed_shells() -> None:
points, faces = [], []
add_cube(points, faces, (0, 0, 0), 3)
add_cube(points, faces, (1, 1, 1), 1)
add_cube(points, faces, (5, 0, 0), 1, flip=True)
for p, want in (((Fraction(3, 2),) * 3, 2), ((Fraction(1, 2),) * 3, 1), ((Fraction(11, 2), Fraction(1, 2), Fraction(1, 2)), -1), ((Fraction(9, 2), 0, 0), 0)):
assert exact_ray_winding(points, faces, p) == want
assert abs(winding_number(points, faces, p) - want) < 1e-9
def test_open_mesh_jumps_by_one_across_a_face() -> None:
points, faces = [], []
add_cube(points, faces, (0, 0, 0), 1)
faces = faces[2:] # remove the bottom face z = 0
rng = random.Random(9)
for _ in range(20):
x, y = rng.uniform(0.1, 0.9), rng.uniform(0.1, 0.9)
eps = 1e-6
below = winding_number(points, faces, (x, y, 1 - eps)) # inside, behind the top face
above = winding_number(points, faces, (x, y, 1 + eps))
assert abs((below - above) - 1) < 1e-5
assert 0 < below < 1 and -1 < above < 0.5
# on the missing face the value is between 0 and 1
w = winding_number(points, faces, (0.5, 0.5, 0.0))
assert 0.3 < w < 0.7
def test_tree_equals_direct_sum() -> None:
rng = random.Random(4)
for _ in range(3):
points, faces, _ = polycube(rng, k=4)
holed = [f for i, f in enumerate(faces) if i % 17 != 3]
for mesh in (faces, holed):
tree = build_tree(points, mesh, leaf_size=6)
for _ in range(40):
p = tuple(rng.uniform(-1, 5) for _ in range(3))
assert abs(winding_number_tree(points, mesh, tree, p) - winding_number(points, mesh, p)) < 1e-9
def test_solid_angle_of_an_octant() -> None:
# the triangle with corners on the three axes covers one eighth of the sphere seen from the origin
omega = solid_angle((1, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0))
assert abs(omega - 4 * math.pi / 8) < 1e-12
assert abs(solid_angle((1, 0, 0), (0, 0, 1), (0, 1, 0), (0, 0, 0)) + 4 * math.pi / 8) < 1e-12
def test_example_of_the_page() -> None:
points, faces = [], []
add_cube(points, faces, (0, 0, 0), 1)
centre = (0.5, 0.5, 0.5)
for f in faces:
assert abs(solid_angle(points[f[0]], points[f[1]], points[f[2]], centre) - math.pi / 3) < 1e-12
assert abs(winding_number(points, faces, centre) - 1) < 1e-12
assert abs(winding_number(points, faces, (1.5, 0.5, 0.5))) < 1e-12
open_box = faces[2:]
assert abs(winding_number(points, open_box, centre) - 5 / 6) < 1e-12
assert abs(winding_number(points, open_box, (0.5, 0.5, 0.0)) - 1 / 2) < 1e-12
def test_float_fails_next_to_a_shared_edge() -> None:
# The point is 1e-20 above the midpoint of the diagonal of the bottom face, inside the cube.
points, faces = [], []
add_cube(points, faces, (0, 0, 0), 1)
p = (0.5, 0.5, 1e-20)
assert exact_ray_winding(points, faces, p) == 1
w = winding_number(points, faces, p)
assert abs(w - 0.5) < 1e-3 # the float value cannot tell inside from outside
assert abs(winding_number(points, faces, (0.3, 0.7, 1e-20)) - 1) < 1e-9
History
The winding number of a closed curve around a point is a classical idea of topology and complex analysis, and the solid angle of a surface is a classical idea of potential theory: Gauss's law says that the flux of the field of a point charge through a closed surface is the solid angle it subtends. Van Oosterom and Strackee gave the closed formula for the solid angle of a triangle in 1983, for electrocardiography. Jacobson, Kavan and Sorkine-Hornung used the sum of the solid angles as a robust inside test for broken meshes in 2013, with a hierarchical evaluation. Zhou, Grinspun, Zorin and Jacobson used exact winding numbers of cells for mesh Booleans in 2016, and Barill and coauthors made the evaluation fast for point clouds and soups in 2018.
References
- Alec Jacobson, Ladislav Kavan and Olga Sorkine-Hornung, Robust inside-outside segmentation using generalized winding numbers, ACM Transactions on Graphics 32(4), 2013, Article 33, the definition as a sum of solid angles, its jump across the surface, the hierarchical evaluation with closing patches, and the segmentation of a tetrahedral mesh by graph cut
- A. van Oosterom and J. Strackee, The solid angle of a plane triangle, IEEE Transactions on Biomedical Engineering BME-30(2), 1983, 125 to 126, the closed formula for the tangent of half the solid angle of a triangle
- Qingnan Zhou, Eitan Grinspun, Denis Zorin and Alec Jacobson, Mesh arrangements for solid geometry, ACM Transactions on Graphics 35(4), 2016, Article 39, the use of exact winding numbers of the cells of an arrangement for Booleans on self-intersecting input
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 CVGJTP Edit this page History Report an error Markdown