Algorithm Search⌘K

Algorithmadvanced

Lattice evaluation for surface intersection

Also called lattice method for surface intersection.

Intersects a grid of iso-parametric curves of one surface with the other surface and links the points found into curves, simple but able to miss small loops.

Time
O(N (T k D^2 + b D^3) + N^2 D) worst
Space
O(N D) extra
Where
D = the degree of f on one lattice line; N = the number of lattice intervals per parameter; T = the number of terms of f; b = the number of bisection steps per root; k = the degree of f
Properties
deterministicnot exactiterative
Origin
Jarek Rossignac, Aristides Requicha, 1987

Lattice evaluation computes the intersection curve of two surfaces by cutting one of them along a lattice of parameter lines, u=i/Nu = i/N and v=j/Nv = j/N, and intersecting each line, a curve, with the other surface. Each such step is a curve surface intersection, which is far easier than the surface problem. The points found are then linked, cell by cell of the lattice, into polylines that follow the branches of the intersection. The method is simple and finds every branch that crosses a lattice line, but a closed loop that fits inside one cell is lost, and the result is only as good as the lattice is fine.

In plain words

Two curved sheets cross, and you want the line where they meet. That is hard to compute directly, so draw a grid of lines on the first sheet, like the lines on graph paper. Each grid line is a simple curve, and finding where one curve pierces the other sheet is an easy problem. Do it for every grid line, and you get many dots that lie on the crossing line.

Now connect the dots. Each square of the grid usually has two dots on its sides, and the crossing line enters the square at one dot and leaves at the other, so draw a segment between them. If a square has four dots, look at its middle point to decide which dots go together.

A small loop inside one square crosses no grid line, so it is missed. A finer grid finds smaller loops but costs more.

The problem

The input is a tensor product Bézier patch r(u,v)r(u, v) on Ω=[0,1]2\Omega = [0, 1]^2, a second surface, and a lattice size NN. In this page and its code the second surface is an implicit surface f(x,y,z)=0f(x, y, z) = 0 for a polynomial ff. Then on each lattice line the function g=f∘rg = f \circ r is one polynomial in one unknown, and the curve surface step is exact root finding. When the second surface is a parametric patch, the step is a curve and patch intersection, three equations in three unknowns, and the rest of the method does not change.

The output is a set of polylines in the parameter plane of rr, each with its vertices on the intersection curve Z={(u,v):g(u,v)=0}Z = \{(u, v) : g(u, v) = 0\}, and a list of the cells that the method could not resolve. Mapping the vertices by rr gives points in space.

The algorithm

  1. LATTICE-INTERSECT(r, f, N)
  2. 1for i ← 0 to N: add the roots t of f(r(i/N, t)) in [0, 1] as points (i/N, t)
  3. 2for j ← 0 to N: add the roots t of f(r(t, j/N)) in [0, 1] as points (t, j/N)
  4. 3for each cell C of the N × N lattice
  5. 4p0, …, p(k−1) ← the points on the boundary of C, in counterclockwise order
  6. 5if k = 2 then link p0 and p1
  7. 6else if k = 4 then if g(center of C) has the sign of g between p0 and p1 then link p1 p2 and p3 p0 else link p0 p1 and p2 p3
  8. 7else if k > 0 then mark C unresolved
  9. 8chain the links into polylines, open ones from their ends first
  10. 9return the polylines and the unresolved cells

Lines L1 and L2 are the lattice evaluation proper. The code forms the restriction of the patch to a line as a Bézier curve, converts it to the power basis, substitutes it into ff, and finds the real roots of the result in [0,1][0, 1] by splitting the interval at the roots of the derivative and bisecting. A root within 10−910^{-9} of a lattice value is moved onto it, so that a point at a lattice node is stored once. Lines L3 to L7 do for the zero set of gg what marching squares does for a sampled function, with the difference that the crossing points on the cell edges are exact roots and not linear interpolations. Line L6 resolves the four point case with the value at the center of the cell, the same rule as in marching squares.

Example

Take the bicubic bump with control points Pij=(i,j,zij)P_{ij} = (i, j, z_{ij}), where zij=3z_{ij} = 3 at the four inner points and 00 elsewhere, so r(u,v)=(3u,3v,27u(1−u)v(1−v))r(u, v) = (3u, 3v, 27 u (1 - u) v (1 - v)). Intersect it with the plane z=1z = 1, f=z−1f = z - 1, with N=4N = 4. On the line u=12u = \tfrac12, g=274v(1−v)−1g = \tfrac{27}{4} v (1 - v) - 1, with roots v=12±14−427v = \tfrac12 \pm \sqrt{\tfrac14 - \tfrac{4}{27}}. On u=14u = \tfrac14 and u=34u = \tfrac34, g=8116v(1−v)−1g = \tfrac{81}{16} v (1 - v) - 1. On u=0u = 0 and u=1u = 1, g=−1g = -1, with no root. The lines in vv give the same values by symmetry.

line points
u=14u = \tfrac14 and u=34u = \tfrac34 v=0.270939v = 0.270939, 0.7290610.729061
u=12u = \tfrac12 v=0.180858v = 0.180858, 0.8191420.819142
v=14v = \tfrac14 and v=34v = \tfrac34 u=0.270939u = 0.270939, 0.7290610.729061
v=12v = \tfrac12 u=0.180858u = 0.180858, 0.8191420.819142

That is 1212 points. The 44 corner cells of the lattice have no point on their boundary, the other 1212 cells, the 44 center cells among them, each have 22, and line L8 chains the 1212 links into one closed polygon,

(0.25,0.270939),(0.180858,0.5),(0.25,0.729061),(0.270939,0.75),(0.5,0.819142),…,(0.270939,0.25),(0.25, 0.270939), (0.180858, 0.5), (0.25, 0.729061), (0.270939, 0.75), (0.5, 0.819142), \dots, (0.270939, 0.25),

and back to the start. The true curve is the closed curve 27u(1−u)v(1−v)=127 u (1 - u) v (1 - v) = 1. The vertices are on it to 10−1210^{-12}, but the edges are chords: at their midpoints the surface height differs from 11 by up to 0.0810.081.

With the plane z=1.68z = 1.68 the true curve is a small loop around the top, with extent u∈[12−130,12+130]u \in [\tfrac12 - \tfrac1{30}, \tfrac12 + \tfrac1{30}] on the line v=12v = \tfrac12. For N=3N = 3 the lattice values 13\tfrac13 and 23\tfrac23 miss that interval, and the method returns nothing. For N=4N = 4 the line u=12u = \tfrac12 meets the loop, and the method returns a closed polygon with 44 vertices.

Correctness

The full proof shows five facts. Lines L1 and L2 find exactly the points of the intersection curve on the lattice lines, provided no lattice line lies in the second surface. In a clean cell, one with no point at a corner and only simple roots on its edges, the number of boundary points is even, because the sign of gg changes at each one on the way around the cell. When 00 is a regular value of gg in the cell and no closed loop lies inside it, the arcs of the curve pair up the boundary points without crossing, by the Jordan curve theorem, so with two points line L5 is right, and with four points there are only two possible pairings. Line L6 picks the right one when the center lies in the middle region of the cell, the one that touches two opposite pieces of the boundary.

The fact that decides what is found is simple. The projection of a connected piece of the curve on the uu axis is an interval, so the piece meets a lattice line exactly when that interval, or its vv counterpart, contains a lattice value. Every piece whose extent in uu or in vv is at least 1/N1/N is found, and a piece inside one cell is lost. The small loop of the example is exactly this case.

What is not proved: that the center condition of line L6 holds, which the method cannot check, and any bound on the distance between a polyline edge and the curve. The tests compare the points on each lattice line with the sign changes of gg on 30003000 samples along the line, for random bicubic patches and random planes and spheres, and check that every link stays in one cell.

Proof: Lattice evaluation finds every crossing on the lattice lines, links them correctly in a cell under stated conditions, and finds exactly the components that meet a lattice linefull

Let rr be a polynomial patch on Ω=[0,1]2\Omega = [0, 1]^2, let ff be a polynomial in x,y,zx, y, z, and let g=f∘rg = f \circ r, a polynomial in (u,v)(u, v). The intersection curve in the parameter plane is Z={(u,v)∈Ω:g(u,v)=0}Z = \{(u, v) \in \Omega : g(u, v) = 0\}. The lattice has the lines u=i/Nu = i / N and v=j/Nv = j / N for 0≤i,j≤N0 \le i, j \le N, and its cells are the squares Cij=[i/N,(i+1)/N]×[j/N,(j+1)/N]C_{ij} = [i/N, (i+1)/N] \times [j/N, (j+1)/N]. The proof uses exact arithmetic for the roots of line L1 and L2; the code finds them in floating point, and the tests compare them with the sign changes of a dense sampling.

Claim 1 (lattice points). Assume that gg is not identically zero on any lattice line. Then lines L1 and L2 report exactly the points of ZZ on the lattice lines, each once.

Proof. On the line u=i/Nu = i/N the function t↦g(i/N,t)t \mapsto g(i/N, t) is a polynomial, the one that line L1 forms, and it is not the zero polynomial by assumption, so it has finitely many roots in [0,1][0, 1]. The root finder splits [0,1][0, 1] at the real roots of the derivative, so the polynomial is monotone on each piece and has at most one root in it. A root in the open part of a piece is a sign change and is found by bisection. A root at an end of a piece is a root of the derivative as well, a multiple root, and is found by the test at that end. So all roots are found, and none twice. The same holds for line L2. A point on two lattice lines, a lattice node, is stored once under its key. □\square

Claim 2 (parity). Call a cell clean if no lattice point is at one of its corners and every lattice point on its boundary is a simple root of gg along its edge. A clean cell has an even number of lattice points on its boundary.

Proof. Go once around the boundary of the cell, starting at a corner. Since gg is not zero at the corners, gg has a sign there. Along each edge, gg changes sign at each simple root and nowhere else, so the sign changes once at each lattice point on the boundary. The walk ends at the start corner with the start sign, so the number of changes is even. □\square

So an odd count at line L7 means that a lattice point lies at a corner or is a touching point.

Claim 3 (linking in a cell). Let CC be a clean cell on which 00 is a regular value of gg, that is, ∇g≠0\nabla g \ne 0 at every point of Z∩CZ \cap C, and assume that Z∩CZ \cap C has no closed component. Let p0,…,pk−1p_0, \dots, p_{k-1} be the boundary points in counterclockwise order. If k=2k = 2, line L5 links the two ends of the one arc of Z∩CZ \cap C. If k=4k = 4, the arcs of Z∩CZ \cap C join p0p_0 to p1p_1 and p2p_2 to p3p_3, or p1p_1 to p2p_2 and p3p_3 to p0p_0, and line L6 chooses the right pair whenever the center of CC lies in the region of C∖ZC \setminus Z that touches two opposite pieces of the boundary.

Proof. Since 00 is a regular value, Z∩CZ \cap C is a compact curve without self crossings, by the implicit function theorem. At a boundary point the zero is simple along the edge, so ZZ crosses the edge there and the point is an end of the curve. A compact connected curve with ends is an arc with two ends, and since no component is closed, Z∩CZ \cap C is a set of disjoint arcs whose ends are exactly the kk boundary points, so they pair the points.

For k=2k = 2 there is one arc, and it joins p0p_0 and p1p_1.

For k=4k = 4, two disjoint arcs in the square cannot join p0p_0 to p2p_2 and p1p_1 to p3p_3: the arc from p0p_0 to p2p_2 cuts the square into two parts, by the Jordan curve theorem applied to the arc closed by a piece of the boundary, and p1p_1 and p3p_3 lie in different parts, so an arc that joins them meets it. That leaves the two pairings of the claim. Write A01A_{01}, A12A_{12}, A23A_{23}, A30A_{30} for the four pieces of the boundary between the points. The function gg has no zero on them, so it has a constant sign ss on A01A_{01}, then −s-s on A12A_{12}, ss on A23A_{23} and −s-s on A30A_{30}, by Claim 2. The two arcs cut CC into three regions. On each region g≠0g \ne 0, and the region is connected, so gg has one sign there, the sign on the boundary pieces that the region touches.

If the arcs join p0p_0 to p1p_1 and p2p_2 to p3p_3, the middle region touches A12A_{12} and A30A_{30}, and gg has the sign −s-s on it. If they join p1p_1 to p2p_2 and p3p_3 to p0p_0, the middle region touches A01A_{01} and A23A_{23}, with sign ss. Line L6 evaluates gg at a point of A01A_{01}, which gives ss, and at the center. If the center lies in the middle region, the two signs agree exactly in the second case, which is the pairing line L6 then chooses. □\square

The condition on the center is not checked by the method. When it fails, the center lies in one of the two outer regions, and line L6 can link the wrong pairs. A closed component inside the cell can also flip the sign at the center.

Claim 4 (which components are found). A connected component KK of ZZ has a point on a lattice line exactly when its projection on the uu axis contains some i/Ni/N or its projection on the vv axis contains some j/Nj/N. In particular, every component whose extent in uu or in vv is at least 1/N1/N is met, and a component inside the interior of one cell is missed.

Proof. The projection of a connected set on an axis is connected, so it is an interval [a,b][a, b]. If it contains i/Ni/N, some point of KK has u=i/Nu = i/N, and it lies on the lattice line u=i/Nu = i/N. Conversely, a point of KK on a lattice line has u=i/Nu = i/N or v=j/Nv = j/N, which is in the projection. An interval of length at least 1/N1/N in [0,1][0, 1] contains a multiple of 1/N1/N. A component in the interior of a cell has both projections inside open intervals between consecutive lattice values. □\square

Claim 5 (what the polylines are). Each vertex of a polyline is a point of ZZ, and each edge joins two points on the boundary of one cell, so the edge lies in that cell. If every cell is clean, satisfies the conditions of Claim 3, and has at most four boundary points, each polyline has the vertices of one component of ZZ that meets a lattice line, in the order of the component.

Proof. The first part follows from Claim 1 and lines L5 and L6. For the second, by Claim 3 each link of line L5 or L6 is an arc of ZZ inside a cell between consecutive lattice points of a component. An interior lattice point lies on the common edge of two cells and is the end of one arc in each, so it has two links; a point on the boundary of Ω\Omega has one. Line L8 walks these links, so it follows each component from end to end, or around a closed component back to its start. □\square

Claim 5 says nothing about the distance between an edge of a polyline and the true curve between its ends. That distance is not bounded by the method, and the page reports it only as a measurement. ■\blacksquare

Complexity

Let ff have degree kk and TT terms, and let D≤kmax⁡(m,n)D \le k \max(m, n) be the degree of gg on a lattice line of a patch of bidegree (m,n)(m, n). Forming gg on one line takes O(TkD2)O(T k D^2) operations with schoolbook products. The root finder recurses through the derivatives, DD levels, and at each level makes O(D)O(D) bisections of bb steps, each step an evaluation of cost O(D)O(D), so O(bD3)O(b D^3) per line. There are 2(N+1)2 (N + 1) lines. Each line holds at most DD points, and the linking scans the points of four lines per cell, O(D)O(D) per cell, O(N2D)O(N^2 D) in all. The total is O(N(TkD2+bD3)+N2D)O(N (T k D^2 + b D^3) + N^2 D) time, with bb about 4545 for double precision, and O(ND)O(N D) space for the points.

For a bicubic patch and a quadric, D=6D = 6, so each line costs a few thousand operations, and a 100×100100 \times 100 lattice is fast. The price is in NN: the error of the polylines falls like 1/N21/N^2 for a smooth curve that crosses the lattice lines at angles bounded away from zero, as for any chord approximation, but the number of curve surface problems grows like NN and the number of cells like N2N^2.

Properties

  • Exact points. Every vertex is an intersection point, found to the precision of the root finder. Only the edges between them are approximate.
  • Independent subproblems. The lines are separate problems, so they run in parallel and need no start point.
  • Not certified. Loops smaller than a cell, tangential pieces and pieces close together can be lost or linked wrongly, and the method gives no signal except the unresolved cells.
  • Two sided choice. The lattice can be put on either surface. When both are parametric, cutting both surfaces finds more loops for the same cost.

Variants and improvements

  • Parametric second surface. Intersect each lattice line with the second patch by subdivision, Newton or the interval projected polyhedron method. This is the form surveyed by Patrikalakis and Maekawa, where each line gives an independent system of nonlinear equations.
  • Start points for marching. Most systems use a coarse lattice only to find one point on each branch, then trace the branch with marching, which gives a curve with an error tolerance in place of a polyline with chords.
  • Loop detection first. A criterion such as Sederberg and Meyers proves that no closed loop exists on a piece. Subdividing until each piece has that guarantee and its boundary is cut by the lattice turns the method into a subdivision method that finds every loop.
  • Adaptive lattices. Refine the lattice in cells with four or more points, unresolved cells, or cells where the sign of gg at the center does not match the links.
  • Exact substitution. With an implicit second surface, the whole function g(u,v)g(u, v) is one polynomial, and algebraic surface intersection uses it in place of the lattice.

When to use it

Use it for a fast preview of an intersection, to find start points for marching, and when the second surface is implicit and of low degree, where each lattice line is a cheap univariate problem. Do not use it alone where a lost loop matters, as in Boolean operations on solids, unless a loop detection test or a size argument proves that every loop is larger than a cell.

Pitfalls

  • Lost loops. A closed piece of the curve inside one cell gives no lattice points. The plane z=1.68z = 1.68 on the bump is lost with N=3N = 3 and found with N=4N = 4.
  • The ambiguous cell. With four points, the value at the center decides the pairing. On the saddle z=9(u−12)(v−12)z = 9 (u - \tfrac12)(v - \tfrac12) cut by z=±0.1z = \pm 0.1 with N=1N = 1 the rule is right, because the center lies in the middle region, but a cell where it lies in an outer region gets the wrong pairs.
  • Curves on a lattice line. If the intersection runs along a lattice line, gg is the zero polynomial there, and the root finder returns no points for that line. On the saddle with z=0z = 0 and N=2N = 2 both branches lie on lattice lines, and the result is wrong. Shift the lattice by a small irrational amount to avoid this.
  • Lattice nodes and touching points. A point at a corner of a cell, or a root of even multiplicity on an edge, gives an odd count, and line L7 leaves the cell unresolved. Near a tangential intersection many such cells appear.
  • Parameter versus space. The lattice is uniform in the parameters, not in space. A patch with a strongly uneven parametrization gets cells that are large in space, and loops of moderate size in space can fit inside them.

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.

lattice_evaluation_intersection.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lattice-evaluation-intersection/. The authors are listed in prov/WD4243.jsonl.

"""Lattice evaluation for the intersection of a Bezier patch and an implicit surface.

The patch r(u, v) on [0, 1] x [0, 1] is given by its control net. The second
surface is the zero set of a polynomial f(x, y, z), given as a dictionary that
maps an exponent triple (a, b, c) to the coefficient of x^a y^b z^c. The
method intersects the N + 1 parameter lines u = i/N and the N + 1 parameter
lines v = j/N with the surface: on each line, g = f(r) is one polynomial in
one unknown, and its real roots are the lattice points. In each cell of the
lattice the points on the boundary are linked in pairs, and the links are
chained into polylines in the parameter plane.
"""

from math import comb
from typing import Sequence

from si1geom import Vec, bernstein, lincomb, padd, patch_point, pmul, ppow, pscale, real_roots

Poly3 = dict  # (a, b, c) -> coefficient of x^a y^b z^c

SNAP = 1e-9  # a root this close to a lattice value is put on it


def eval_f(f: Poly3, q: Vec) -> float:
    return sum(c * q[0] ** a * q[1] ** b * q[2] ** e for (a, b, e), c in f.items())


def _bezier_power(Q: Sequence[Vec]) -> list:
    """Coordinate polynomials (power basis, in t) of the Bezier curve Q."""
    d = len(Q) - 1
    out = []
    for k in range(3):
        poly = [0.0]
        for i, q in enumerate(Q):
            b = pscale(comb(d, i) * q[k], pmul(ppow([0.0, 1.0], i), ppow([1.0, -1.0], d - i)))
            poly = padd(poly, b)
        out.append(poly)
    return out


def iso_polynomial(P: Sequence[Sequence[Vec]], f: Poly3, along_v: bool, value: float) -> list:
    """g(t) = f(r(value, t)) if along_v, else f(r(t, value)), in the power basis."""
    m, n = len(P) - 1, len(P[0]) - 1
    if along_v:
        B = bernstein(m, value)
        Q = [lincomb(B, [P[a][j] for a in range(m + 1)]) for j in range(n + 1)]
    else:
        B = bernstein(n, value)
        Q = [lincomb(B, P[i]) for i in range(m + 1)]
    X, Y, Z = _bezier_power(Q)
    g = [0.0]
    for (a, b, e), c in f.items():
        g = padd(g, pscale(c, pmul(pmul(ppow(X, a), ppow(Y, b)), ppow(Z, e))))
    return g


def _snap(t: float, N: int) -> float:
    k = round(t * N)
    return k / N if abs(t - k / N) <= SNAP else t


def _key(u: float, v: float) -> tuple:
    return (round(u * 1e9), round(v * 1e9))


def lattice_evaluation_intersection(P: Sequence[Sequence[Vec]], f: Poly3, N: int) -> tuple:
    """Return (polylines, unresolved, points).

    polylines: lists of (u, v); a closed one repeats its first point at the end.
    unresolved: the cells (i, j) whose boundary holds a number of points other
    than 0, 2 or 4.
    points: all lattice points (u, v), sorted.
    """
    pts = {}
    on_u = [[] for _ in range(N + 1)]  # on_u[i]: the v of the points on u = i/N
    on_v = [[] for _ in range(N + 1)]  # on_v[j]: the u of the points on v = j/N
    for i in range(N + 1):  # @line L1
        ui = i / N
        for t in real_roots(iso_polynomial(P, f, True, ui), 0.0, 1.0):
            v = _snap(t, N)
            on_u[i].append(v)
            pts[_key(ui, v)] = (ui, v)
    for j in range(N + 1):  # @line L2
        vj = j / N
        for t in real_roots(iso_polynomial(P, f, False, vj), 0.0, 1.0):
            u = _snap(t, N)
            on_v[j].append(u)
            pts[_key(u, vj)] = (u, vj)

    def g(u: float, v: float) -> float:
        return eval_f(f, patch_point(P, u, v))

    def at_s(i: int, j: int, s: float) -> tuple:
        """The point at boundary coordinate s in [0, 4) of cell (i, j), counterclockwise."""
        u0, v0, h = i / N, j / N, 1 / N
        side, x = int(s), s - int(s)
        return [(u0 + x * h, v0), (u0 + h, v0 + x * h), (u0 + h - x * h, v0 + h), (u0, v0 + h - x * h)][side]

    links = []
    unresolved = []
    for i in range(N):  # @line L3
        for j in range(N):
            u0, u1, v0, v1 = i / N, (i + 1) / N, j / N, (j + 1) / N
            found = {}  # @line L4
            for u in on_v[j]:
                if u0 <= u <= u1:
                    found.setdefault(_key(u, v0), (u - u0) * N)
            for v in on_u[i + 1]:
                if v0 <= v <= v1:
                    found.setdefault(_key(u1, v), 1 + (v - v0) * N)
            for u in on_v[j + 1]:
                if u0 <= u <= u1:
                    found.setdefault(_key(u, v1), 2 + (u1 - u) * N)
            for v in on_u[i]:
                if v0 <= v <= v1:
                    found.setdefault(_key(u0, v), 3 + (v1 - v) * N)
            ring = sorted(found.items(), key=lambda kv: kv[1])
            k = len(ring)
            if k == 2:  # @line L5
                links.append((ring[0][0], ring[1][0]))
            elif k == 4:  # @line L6
                s01 = 0.5 * (ring[0][1] + ring[1][1])
                arc = g(*at_s(i, j, s01))
                centre = g(0.5 * (u0 + u1), 0.5 * (v0 + v1))
                if centre * arc > 0:
                    links += [(ring[1][0], ring[2][0]), (ring[3][0], ring[0][0])]
                else:
                    links += [(ring[0][0], ring[1][0]), (ring[2][0], ring[3][0])]
            elif k > 0:  # @line L7
                unresolved.append((i, j))

    adj = {}  # @line L8
    for e, (a, b) in enumerate(links):
        adj.setdefault(a, []).append((b, e))
        adj.setdefault(b, []).append((a, e))
    used = [False] * len(links)
    polylines = []
    starts = [a for a in adj if len(adj[a]) % 2 == 1] + list(adj)
    for s in starts:
        while any(not used[e] for _, e in adj[s]):
            line = [s]
            cur = s
            while True:
                nxt = next(((b, e) for b, e in adj[cur] if not used[e]), None)
                if nxt is None:
                    break
                used[nxt[1]] = True
                cur = nxt[0]
                line.append(cur)
            polylines.append([pts[k] for k in line])
    return polylines, unresolved, sorted(pts.values())  # @line L9
si1geom.py 298 lines
# SPDX-License-Identifier: MIT
# Shared helper of the si1 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small geometric and algebraic tools for the si1 pages.

Vectors are tuples of three numbers. A tensor product Bezier patch of bidegree
(m, n) is a list of m + 1 rows of n + 1 control points. Univariate polynomials
are lists of coefficients from the constant term up. Entries may be int,
Fraction or float; exact inputs give exact results where no square root or
division by a float is involved. No function here is the algorithm of a page.
"""

from fractions import Fraction
from math import comb, sqrt
from typing import Sequence

Vec = tuple
Num = float


# ---- vectors ---------------------------------------------------------------

def add(a: Vec, b: Vec) -> Vec:
    return (a[0] + b[0], a[1] + b[1], a[2] + b[2])


def sub(a: Vec, b: Vec) -> Vec:
    return (a[0] - b[0], a[1] - b[1], a[2] - b[2])


def scale(t, a: Vec) -> Vec:
    return (t * a[0], t * a[1], t * a[2])


def dot(a: Vec, b: Vec):
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]


def cross(a: Vec, b: Vec) -> Vec:
    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 norm(a: Vec) -> float:
    return sqrt(float(dot(a, a)))


def lincomb(ws: Sequence, ps: Sequence[Vec]) -> Vec:
    """Return sum of ws[i] * ps[i]."""
    x = y = z = 0
    for w, p in zip(ws, ps):
        x += w * p[0]
        y += w * p[1]
        z += w * p[2]
    return (x, y, z)


# ---- Bernstein basis -------------------------------------------------------

def bernstein(n: int, t) -> list:
    """Values B_{i,n}(t) for i = 0..n, by the explicit formula."""
    s = 1 - t
    return [comb(n, i) * t ** i * s ** (n - i) for i in range(n + 1)]


def bernstein_d(n: int, t, k: int) -> list:
    """k-th derivatives of B_{i,n} at t, for k = 0, 1, 2, from the difference formula."""
    if k == 0 or n == 0:
        return bernstein(n, t) if k == 0 else [0] * (n + 1)
    low = bernstein_d(n - 1, t, k - 1)
    out = []
    for i in range(n + 1):
        a = low[i - 1] if i >= 1 else 0
        b = low[i] if i <= n - 1 else 0
        out.append(n * (a - b))
    return out


def patch_point(P: Sequence[Sequence[Vec]], u, v) -> Vec:
    m, n = len(P) - 1, len(P[0]) - 1
    bu, bv = bernstein(m, u), bernstein(n, v)
    x = y = z = 0
    for i in range(m + 1):
        for j in range(n + 1):
            w = bu[i] * bv[j]
            q = P[i][j]
            x += w * q[0]
            y += w * q[1]
            z += w * q[2]
    return (x, y, z)


def patch_derivs(P: Sequence[Sequence[Vec]], u, v) -> tuple:
    """Return (r, r_u, r_v, r_uu, r_uv, r_vv) of a Bezier patch at (u, v)."""
    m, n = len(P) - 1, len(P[0]) - 1
    U = [bernstein_d(m, u, k) for k in range(3)]
    V = [bernstein_d(n, v, k) for k in range(3)]
    out = []
    for a, b in ((0, 0), (1, 0), (0, 1), (2, 0), (1, 1), (0, 2)):
        x = y = z = 0
        for i in range(m + 1):
            ui = U[a][i]
            for j in range(n + 1):
                w = ui * V[b][j]
                q = P[i][j]
                x += w * q[0]
                y += w * q[1]
                z += w * q[2]
        out.append((x, y, z))
    return tuple(out)


def curve_point(C: Sequence[Vec], t) -> Vec:
    return lincomb(bernstein(len(C) - 1, t), C)


# ---- univariate polynomials, coefficient lists from the constant term ------

def ptrim(a: list) -> list:
    a = list(a)
    while len(a) > 1 and a[-1] == 0:
        a.pop()
    return a


def padd(a: list, b: list) -> list:
    n = max(len(a), len(b))
    return ptrim([(a[i] if i < len(a) else 0) + (b[i] if i < len(b) else 0) for i in range(n)])


def pscale(c, a: list) -> list:
    return ptrim([c * x for x in a])


def pmul(a: list, b: list) -> list:
    out = [0] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        if x == 0:
            continue
        for j, y in enumerate(b):
            out[i + j] += x * y
    return ptrim(out)


def ppow(a: list, k: int) -> list:
    out = [1]
    for _ in range(k):
        out = pmul(out, a)
    return out


def peval(a: list, t):
    s = 0
    for c in reversed(a):
        s = s * t + c
    return s


def pderiv(a: list) -> list:
    return ptrim([i * a[i] for i in range(1, len(a))]) if len(a) > 1 else [0]


def real_roots(a: list, lo: float, hi: float, tol: float = 1e-13) -> list:
    """Real roots of a polynomial in [lo, hi], each once, in increasing order.

    The roots of the derivative split [lo, hi] into pieces on which the
    polynomial is monotone; each piece holds at most one root, found by
    bisection. A root of even multiplicity is found when the polynomial is
    zero (to within the rounding of a float) at a critical point.
    """
    a = ptrim([float(c) for c in a])
    if len(a) == 1:
        return []
    crit = real_roots(pderiv(a), lo, hi, tol) if len(a) > 2 else []
    knots = [lo] + [c for c in crit if lo < c < hi] + [hi]
    scale_ = max(abs(c) for c in a)
    roots = []
    for x0, x1 in zip(knots, knots[1:]):
        f0, f1 = peval(a, x0), peval(a, x1)
        if f0 == 0 or abs(f0) <= 1e-14 * scale_:
            if not roots or abs(roots[-1] - x0) > 1e-9:
                roots.append(x0)
            continue
        if f0 * f1 > 0:
            continue
        if f1 == 0 or abs(f1) <= 1e-14 * scale_:
            continue
        a0, a1 = x0, x1
        while a1 - a0 > tol:
            mid = 0.5 * (a0 + a1)
            fm = peval(a, mid)
            if (fm < 0) == (f0 < 0):
                a0, f0 = mid, fm
            else:
                a1 = mid
        roots.append(0.5 * (a0 + a1))
    f_hi = peval(a, hi)
    if abs(f_hi) <= 1e-14 * scale_ and (not roots or abs(roots[-1] - hi) > 1e-9):
        roots.append(hi)
    return roots


# ---- dense linear algebra --------------------------------------------------

def solve(A: list, b: list) -> list:
    """Solve A x = b by Gaussian elimination with partial pivoting.

    Works for Fraction entries (exact, pivot = first nonzero) and for floats.
    Raises ZeroDivisionError when A is singular (exactly, or to the pivot test
    1e-300 for floats).
    """
    n = len(A)
    M = [list(A[i]) + [b[i]] for i in range(n)]
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(M[r][c]))
        if M[piv][c] == 0 or (isinstance(M[piv][c], float) and abs(M[piv][c]) < 1e-300):
            raise ZeroDivisionError("singular matrix")
        M[c], M[piv] = M[piv], M[c]
        for r in range(c + 1, n):
            f = M[r][c] / M[c][c]
            if f != 0:
                for k in range(c, n + 1):
                    M[r][k] -= f * M[c][k]
    x = [0] * n
    for i in range(n - 1, -1, -1):
        s = M[i][n] - sum(M[i][k] * x[k] for k in range(i + 1, n))
        x[i] = s / M[i][i]
    return x


def det(A: list):
    """Determinant by fraction free Bareiss elimination for int and Fraction
    entries, and by Gaussian elimination for floats."""
    n = len(A)
    if n == 0:
        return 1
    if any(isinstance(x, float) for row in A for x in row):
        M = [list(map(float, row)) for row in A]
        d = 1.0
        for c in range(n):
            piv = max(range(c, n), key=lambda r: abs(M[r][c]))
            if M[piv][c] == 0:
                return 0.0
            if piv != c:
                M[c], M[piv] = M[piv], M[c]
                d = -d
            d *= M[c][c]
            for r in range(c + 1, n):
                f = M[r][c] / M[c][c]
                for k in range(c, n):
                    M[r][k] -= f * M[c][k]
        return d
    M = [[Fraction(x) for x in row] for row in A]
    sign = 1
    prev = Fraction(1)
    for c in range(n - 1):
        if M[c][c] == 0:
            piv = next((r for r in range(c + 1, n) if M[r][c] != 0), None)
            if piv is None:
                return Fraction(0)
            M[c], M[piv] = M[piv], M[c]
            sign = -sign
        for r in range(c + 1, n):
            for k in range(c + 1, n):
                M[r][k] = (M[r][k] * M[c][c] - M[r][c] * M[c][k]) / prev
            M[r][c] = Fraction(0)
        prev = M[c][c]
    return sign * M[n - 1][n - 1]


def jacobi_eigen(A: list, sweeps: int = 60) -> tuple:
    """Eigenvalues and eigenvectors of a small symmetric float matrix by the
    cyclic Jacobi method. Returns (values, vectors) with vectors[k] the unit
    eigenvector of values[k], sorted by increasing value."""
    n = len(A)
    M = [[float(x) for x in row] for row in A]
    V = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
    for _ in range(sweeps):
        off = sum(M[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        if off < 1e-30:
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                if abs(M[p][q]) < 1e-300:
                    continue
                theta = (M[q][q] - M[p][p]) / (2 * M[p][q])
                t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + sqrt(theta * theta + 1))
                c = 1 / sqrt(t * t + 1)
                s = t * c
                for k in range(n):
                    mkp, mkq = M[k][p], M[k][q]
                    M[k][p], M[k][q] = c * mkp - s * mkq, s * mkp + c * mkq
                for k in range(n):
                    mpk, mqk = M[p][k], M[q][k]
                    M[p][k], M[q][k] = c * mpk - s * mqk, s * mpk + c * mqk
                for k in range(n):
                    vkp, vkq = V[k][p], V[k][q]
                    V[k][p], V[k][q] = c * vkp - s * vkq, s * vkp + c * vkq
    order = sorted(range(n), key=lambda i: M[i][i])
    return [M[i][i] for i in order], [[V[k][i] for k in range(n)] for i in order]
test_lattice_evaluation_intersection.py 119 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lattice-evaluation-intersection/. The authors are listed in prov/WD4243.jsonl.

import random
import unittest

from lattice_evaluation_intersection import eval_f, lattice_evaluation_intersection
from si1geom import patch_point

Z = [[0, 0, 0, 0], [0, 3, 3, 0], [0, 3, 3, 0], [0, 0, 0, 0]]
BUMP = [[(i, j, Z[i][j]) for j in range(4)] for i in range(4)]
SADDLE = [[(i, j, (i - 1.5) * (j - 1.5)) for j in range(4)] for i in range(4)]


def plane_z(c):
    return {(0, 0, 1): 1.0, (0, 0, 0): -c}


def sphere(cx, cy, cz, R):
    return {(2, 0, 0): 1.0, (0, 2, 0): 1.0, (0, 0, 2): 1.0, (1, 0, 0): -2 * cx, (0, 1, 0): -2 * cy,
            (0, 0, 1): -2 * cz, (0, 0, 0): cx * cx + cy * cy + cz * cz - R * R}


def sign_change_cells(P, f, along_v, value, samples):
    """Brute force: the sample intervals on a parameter line where f(r) changes sign."""
    vals = []
    for k in range(samples + 1):
        t = k / samples
        q = patch_point(P, value, t) if along_v else patch_point(P, t, value)
        vals.append(eval_f(f, q))
    return [k for k in range(samples) if vals[k] * vals[k + 1] < 0]


def same_cell(a, b, N):
    for i in range(N):
        for j in range(N):
            box = (i / N - 1e-12, (i + 1) / N + 1e-12, j / N - 1e-12, (j + 1) / N + 1e-12)
            if all(box[0] <= p[0] <= box[1] and box[2] <= p[1] <= box[3] for p in (a, b)):
                return True
    return False


class TestLatticeEvaluationIntersection(unittest.TestCase):
    def test_example_plane_and_bump(self):
        pl, unresolved, pts = lattice_evaluation_intersection(BUMP, plane_z(1.0), 4)
        self.assertEqual(len(pts), 12)
        self.assertEqual(unresolved, [])
        self.assertEqual(len(pl), 1)
        loop = pl[0]
        self.assertEqual(len(loop), 13)
        self.assertEqual(loop[0], loop[-1])
        for u, v in loop:
            self.assertAlmostEqual(27 * u * (1 - u) * v * (1 - v), 1.0, places=10)
        vs = sorted(v for u, v in pts if u == 0.5)
        self.assertAlmostEqual(vs[0], 0.5 - (0.25 - 4 / 27) ** 0.5, places=12)

    def test_small_loop_is_missed_by_a_coarse_lattice(self):
        pl3, _, pts3 = lattice_evaluation_intersection(BUMP, plane_z(1.68), 3)
        self.assertEqual((pl3, pts3), ([], []))
        pl4, _, pts4 = lattice_evaluation_intersection(BUMP, plane_z(1.68), 4)
        self.assertEqual(len(pts4), 4)
        self.assertEqual(len(pl4), 1)
        self.assertEqual(pl4[0][0], pl4[0][-1])

    def test_ambiguous_cell_uses_the_centre(self):
        flat = [[(i / 3, j / 3, (i - 1.5) * (j - 1.5)) for j in range(4)] for i in range(4)]
        for c in (0.1, -0.1):
            pl, unresolved, pts = lattice_evaluation_intersection(flat, plane_z(c), 1)
            self.assertEqual(len(pts), 4)
            self.assertEqual(len(pl), 2)
            for line in pl:
                (u0, v0), (u1, v1) = line
                # each branch of 9 (u - 1/2)(v - 1/2) = c stays in one pair of quadrants
                self.assertGreater(c * (u0 - 0.5) * (v0 - 0.5), 0)
                self.assertGreater(c * (u1 - 0.5) * (v1 - 0.5), 0)
                self.assertGreater((u0 - 0.5) * (u1 - 0.5), 0)

    def test_open_branches_end_on_the_boundary(self):
        pl, unresolved, _ = lattice_evaluation_intersection(SADDLE, plane_z(0.7), 5)
        self.assertEqual(unresolved, [])
        self.assertEqual(len(pl), 2)
        for line in pl:
            self.assertNotEqual(line[0], line[-1])
            for u, v in (line[0], line[-1]):
                self.assertTrue(u in (0.0, 1.0) or v in (0.0, 1.0))

    def test_against_grid_sign_changes(self):
        rng = random.Random(11)
        samples = 3000
        for case in range(12):
            P = [[(i + rng.uniform(-0.3, 0.3), j + rng.uniform(-0.3, 0.3), rng.uniform(-2.0, 2.0))
                  for j in range(4)] for i in range(4)]
            if case % 2:
                f = sphere(rng.uniform(0.5, 2.5), rng.uniform(0.5, 2.5), rng.uniform(-1, 1), rng.uniform(0.8, 2.0))
            else:
                a, b, c = rng.uniform(-1, 1), rng.uniform(-1, 1), 1.0
                f = {(1, 0, 0): a, (0, 1, 0): b, (0, 0, 1): c, (0, 0, 0): -rng.uniform(-1.5, 1.5)}
            N = 4
            pl, unresolved, pts = lattice_evaluation_intersection(P, f, N)
            for i in range(N + 1):
                for along_v in (True, False):
                    value = i / N
                    if along_v:
                        found = sorted(v for u, v in pts if u == value)
                    else:
                        found = sorted(u for u, v in pts if v == value)
                    cells = sign_change_cells(P, f, along_v, value, samples)
                    self.assertEqual(len(found), len(cells))
                    for t, k in zip(found, cells):
                        self.assertTrue(k / samples <= t <= (k + 1) / samples)
            for u, v in pts:
                self.assertLess(abs(eval_f(f, patch_point(P, u, v))), 1e-8)
            for line in pl:
                for a_, b_ in zip(line, line[1:]):
                    self.assertTrue(same_cell(a_, b_, N))


if __name__ == "__main__":
    unittest.main()

History

Lattice evaluation was one of the first general methods for intersecting sculptured surfaces, from the solid modeling work of the 1980s, and surveys cite work of 1987 by Rossignac and Requicha and by Lien and others for it. Patrikalakis (1993) named it as one of four classes of surface intersection methods, with analytic, subdivision and marching methods, and Patrikalakis and Maekawa (2002) treated it in their book, noting that its result depends on the lattice and that it can miss loops. In current systems it survives mostly as the start point search of marching methods.

References

  1. Nicholas M. Patrikalakis and Takashi Maekawa, Shape Interrogation for Computer Aided Design and Manufacturing, Springer, 2002, Chapter 5, Section 5.8.2.1, Lattice evaluation (intersections of isoparametric curves of one surface with the other surface, connected into branches; the risk of missing loops and the dependence on the lattice size)
  2. Nicholas M. Patrikalakis, Surface-to-surface intersections, IEEE Computer Graphics and Applications 13(1), 89 to 95, 1993, the whole paper (the classification of intersection methods into analytic, lattice evaluation, subdivision and marching methods)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example