Algorithm Search⌘K

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
Properties
deterministicnot exactiterative
Origin
Alec Jacobson, Ladislav Kavan, Olga Sorkine Hornung, 2013

The generalized winding number of a triangle mesh at a point pp is the sum of the signed solid angles of all triangles seen from pp, divided by 4π4\pi, 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 pp 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 pp not on any triangle. The output is a number w(p)w(p) that equals the winding number of the surface around pp 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 T=(A,B,C)T = (A, B, C) seen from pp has a closed formula, due to Van Oosterom and Strackee. With a=A−pa = A - p, b=B−pb = B - p, c=C−pc = C - p:

tan⁡ΩT2=det⁡[a b c]∣a∣∣b∣∣c∣+(a⋅b)∣c∣+(a⋅c)∣b∣+(b⋅c)∣a∣.\tan\frac{\Omega_T}{2} = \frac{\det[a\ b\ c]}{|a||b||c| + (a \cdot b)|c| + (a \cdot c)|b| + (b \cdot c)|a|}.

The determinant is −ORIENT3D(A,B,C,p)-\mathrm{ORIENT3D}(A, B, C, p), the orientation test of pp against the plane of TT, so ΩT>0\Omega_T > 0 when pp is behind TT. Computing the angle with atan2\mathrm{atan2} keeps it in (−2π,2π)(-2\pi, 2\pi).

  1. WINDING-NUMBER(M, p)
  2. 1s ← 0
  3. 2for each triangle T = (A, B, C) of M do
  4. 3a ← A − p; b ← B − p; c ← C − p; num ← det[a b c]
  5. 4den ← |a||b||c| + (a·b)|c| + (a·c)|b| + (b·c)|a|
  6. 5s ← s + 2 · atan2(num, den)
  7. 6return s / (4π)

The tree version. For many queries, Jacobson and coauthors build a tree of patches with bounding boxes. If pp 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 pp 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 Ω=0\Omega = 0. Repeated triangles add up, and two copies with opposite orientations cancel. If pp is a vertex, ∣a∣=0|a| = 0, 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 p=(1/2,1/2,1/2)p = (1/2, 1/2, 1/2). For the triangle (0,0,0)(0,0,0), (0,1,0)(0,1,0), (1,1,0)(1,1,0) of the bottom face, a=(−12,−12,−12)a = (-\tfrac12, -\tfrac12, -\tfrac12), b=(−12,12,−12)b = (-\tfrac12, \tfrac12, -\tfrac12), c=(12,12,−12)c = (\tfrac12, \tfrac12, -\tfrac12).

step value
L3 det⁡[a b c]=1/2>0\det[a\,b\,c] = 1/2 > 0: pp is behind the face
L4 $
L5 tan⁡(Ω/2)=1/3\tan(\Omega/2) = 1/\sqrt3, so Ω=π/3\Omega = \pi/3
L6 by symmetry all 12 triangles give π/3\pi/3, so w=4π/4π=1w = 4\pi / 4\pi = 1

At p=(3/2,1/2,1/2)p = (3/2, 1/2, 1/2), 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 w=5/6w = 5/6, because the missing face covered one sixth of the view. At the centre of the missing face w=1/2w = 1/2, halfway between inside and outside. Rounding ww 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 pp at height hh above the midpoint of the diagonal of the bottom face, inside the cube. For the triangle whose diagonal is right under pp, aa and cc point in nearly opposite directions, a⋅c≈−∣a∣∣c∣a \cdot c \approx -|a||c|, and the denominator is a difference of nearly equal numbers, a case of catastrophic cancellation. With doubles, ww is 0.999980.99998 at h=10−12h = 10^{-12}, 0.980.98 at h=10−15h = 10^{-15}, 0.5570.557 at h=10−17h = 10^{-17} and 0.500060.50006 at h=10−20h = 10^{-20}, while the exact value is 1. At (0.3,0.7,10−20)(0.3, 0.7, 10^{-20}), 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 ww is too close to 1/21/2. 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 pp, so the sum of the solid angles is the integral over all directions dd of the signed number of triangles that the ray from pp in direction dd hits. For a closed mesh this number does not change when dd crosses the shadow of an edge, because the two triangles at the edge change it by +1+1 and −1-1. So it is the same integer kk for almost all directions, and w=kw = k, which is also what a signed ray count finds. As pp goes to infinity, ww goes to 0, so it is 0 on the outside. Crossing one face against its normal raises ww by exactly 1, because the solid angle of that face jumps from −2π-2\pi to 2π2\pi; this holds for broken meshes too. So a closed surface that does not cut itself has w=1w = 1 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 T=(A,B,C)T = (A, B, C) in R3\mathbb{R}^3, oriented so that the outward normal nT=(B−A)×(C−A)n_T = (B - A) \times (C - A) 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 ∑T(AB+BC+CA)\sum_T (AB + BC + CA), where an edge XYXY cancels against YXYX. The mesh is closed if the boundary is 0. For a point pp not on the mesh, ΩT(p)\Omega_T(p) is the signed area of the radial projection of TT onto the unit sphere around pp, positive when pp is behind TT (on the side opposite to nTn_T), and

w(p)=14π∑TΩT(p).w(p) = \frac{1}{4\pi} \sum_T \Omega_T(p).

Claim.

  1. The formula of Van Oosterom and Strackee, ΩT=2 atan2(det⁡[a b c], ∣a∣∣b∣∣c∣+(a⋅b)∣c∣+(a⋅c)∣b∣+(b⋅c)∣a∣)\Omega_T = 2\,\mathrm{atan2}(\det[a\,b\,c],\ |a||b||c| + (a \cdot b)|c| + (a \cdot c)|b| + (b \cdot c)|a|) with a=A−pa = A - p, b=B−pb = B - p, c=C−pc = C - p, gives ΩT(p)\Omega_T(p).
  2. If the mesh is closed, then for every direction dd whose ray from pp misses all edges and vertices and is not in the plane of any triangle, w(p)=∑T±[the ray hits T]w(p) = \sum_T \pm [\text{the ray hits } T], with ++ when d⋅nT>0d \cdot n_T > 0. In particular w(p)w(p) is an integer, and the exact ray count of the code computes it.
  3. If the mesh is a closed oriented 2-manifold without self-intersections and its normals point out of the solid it bounds, then w=1w = 1 inside and w=0w = 0 outside.
  4. For any mesh, ww is continuous off the mesh, and across a point in the interior of exactly one triangle, ww just behind the triangle minus ww just in front of it is 11.
  5. For a set QQ of triangles whose bounding box does not contain pp, ∑T∈QΩT(p)=∑T∈cap(Q)ΩT(p)\sum_{T \in Q} \Omega_T(p) = \sum_{T \in \mathrm{cap}(Q)} \Omega_T(p), where cap(Q)\mathrm{cap}(Q) is the fan (o,X,Y)(o, X, Y) over the boundary edges XYXY of QQ from one boundary vertex oo. So the tree version computes the same ww.

Step 1 (part 1). This is the result of Van Oosterom and Strackee (1983). We check the sign. det⁡[a b c]=a⋅(b×c)\det[a\,b\,c] = a \cdot (b \times c), and b×cb \times c has the direction of nTn_T when the triangle is seen counterclockwise from the side where nTn_T points, so det⁡[a b c]=−((B−A)×(C−A))⋅(p−A)\det[a\,b\,c] = -\big((B - A) \times (C - A)\big) \cdot (p - A), which is positive exactly when pp is behind TT. The denominator is positive for small triangles far from pp, so ΩT\Omega_T is then small with the sign of the determinant, and both sides of the formula are continuous in pp off the plane of TT and off the triangle. The formula is the half-angle form of the spherical excess of the projected triangle; atan2\mathrm{atan2} picks the angle in (−π,π)(-\pi, \pi) for ΩT/2\Omega_T / 2, which is right because ∣ΩT∣<2π|\Omega_T| < 2\pi.

Step 2 (part 2). For a direction dd, let N(d)=∑T±[the ray from p in direction d hits T]N(d) = \sum_T \pm [\text{the ray from } p \text{ in direction } d \text{ hits } T], with the sign of d⋅nTd \cdot n_T. The radial projection of TT covers the directions dd whose ray hits TT, once, and its signed area is ΩT(p)\Omega_T(p). If pp is behind TT, every ray from pp that hits TT has d⋅nT>0d \cdot n_T > 0 and ΩT>0\Omega_T > 0; if pp is in front, both signs are negative. So ΩT(p)=∫S2±[hit] dσ\Omega_T(p) = \int_{S^2} \pm [\text{hit}]\, d\sigma, and ∑TΩT(p)=∫S2N(d) dσ(d)\sum_T \Omega_T(p) = \int_{S^2} N(d)\, d\sigma(d).

Let GG 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 GG is the sphere minus a set of measure 0. Take a path between two directions of GG 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 XYXY, the ray stops or starts hitting each triangle that has XX and YY as corners; a triangle with the directed edge XYXY changes NN by ±1\pm 1, and one with YXYX changes it by ∓1\mp 1, so the total change is ±\pm the coefficient of XYXY in the boundary chain, which is 0 for a closed mesh. So NN is the same constant kk on all of GG, ∑TΩT(p)=4πk\sum_T \Omega_T(p) = 4\pi k, and w(p)=kw(p) = k.

The code of the page computes N(d)N(d) for a random rational dd in exact rational arithmetic and tries another dd when the ray touches an edge, a vertex or a plane of a triangle, so it returns w(p)w(p) 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 ΩT\Omega_T is continuous in pp off TT, so ww is continuous off the mesh. Let qq be in the interior of exactly one triangle TT. Every other triangle has Ω\Omega continuous near qq. As pp moves from just in front of TT to just behind it, through qq, the projection of TT becomes a hemisphere seen from the front and a hemisphere seen from behind, so ΩT\Omega_T goes from close to −2π-2\pi to close to +2π+2\pi. The jump of ww is 4π/4π=14\pi / 4\pi = 1.

Step 4 (part 3). By part 2, ww 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 ∣p∣→∞|p| \to \infty, every ΩT(p)→0\Omega_T(p) \to 0, so w=0w = 0 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 ww by +1+1 by part 4. So w=1w = 1 inside.

Step 5 (part 5). The chain Q−cap(Q)Q - \mathrm{cap}(Q) is closed: the boundary of cap(Q)\mathrm{cap}(Q) is the sum of oX+XY+YooX + XY + Yo over the boundary edges XYXY of QQ; the edges oXoX and YoYo 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 QQ. Triangles of the fan with o∈{X,Y}o \in \{X, Y\} are degenerate, have Ω=0\Omega = 0 and are left out. All triangles of Q−cap(Q)Q - \mathrm{cap}(Q) lie in the convex hull of the vertices of QQ, which is inside the bounding box. If pp is outside the box, a ray from pp away from the box misses all of them, so by part 2 the winding number of the closed chain is 0, that is ∑QΩT(p)−∑capΩT(p)=0\sum_Q \Omega_T(p) - \sum_{\mathrm{cap}} \Omega_T(p) = 0. 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 O(F)O(F) nodes for FF triangles. ■\blacksquare

What floating point does. The proof is about the exact values. The code computes ΩT\Omega_T 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 10−2010^{-20} above the middle of a face diagonal of the unit cube where the float sum gives 0.500060.50006 instead of 1.

Complexity

The direct sum takes O(F)O(F) time per query for FF triangles and O(1)O(1) extra space. The tree takes O(F)O(F) space and O(F)O(F) time per query in the worst case, but it is much faster in practice, because most patches are far from pp 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 O(log⁡F)O(\log F) for a given accuracy.

Properties

  • Exact for closed meshes. In exact arithmetic, ww is the integer winding number.
  • Robust for broken meshes. Holes, gaps and small overlaps change ww by small amounts away from them, so rounding or thresholding at 1/21/2 still classifies most points.
  • Harmonic. Off the surface ww is a harmonic function of pp, smooth, with no local maximum or minimum.
  • Jump of 1. Across a triangle ww 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 2π2\pi 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 ww at the tetrahedra, and chooses the inside by a graph cut that trades ww 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 −1-1 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 10−1210^{-12} of the edge length it is off by 2×10−52 \times 10^{-5}, and at 10−1710^{-17} it cannot tell inside from outside, as the example shows.
  • Nested or overlapping shells. Two shells that overlap give w=2w = 2 in the overlap. Testing w>1/2w > 1/2 means union, and w=1w = 1 exactly means something else.
  • Big holes. A missing face of a cube gives w=5/6w = 5/6 at the centre but 1/21/2 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.

generalized_winding_number.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.direct
  • a full proof of time.tree_worst
  • a full proof of space.direct
  • a full proof of space.tree
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