Data structureadvanced
Nef polyhedron
Also called Nef polyhedra, selective Nef complex.
A point set built from finitely many half-spaces by Boolean operations, closed also under interior, closure and boundary, and stored exactly by Hachenberger and Kettner's selective Nef complex.
- Time
- O(n^3) worst
- Space
- O(n^3) extra
- Where
- n = the number of distinct lines or planes that bound the set
- Model
- Word RAM
- Evidence
- Proof sketchCode in 1 languages
A Nef polyhedron in is a set that can be built from finitely many open half-spaces by complement and intersection, and so also by union and difference. Walter Nef introduced these sets in 1978. They contain far more than solids. A Nef polyhedron may be open, closed or neither, and it may have dangling faces, isolated edges and points, and cuts inside it. Nef polyhedra are closed under all Boolean operations and under interior, closure, boundary and regularization. This is not true of the r-sets of classical solid modeling, which need regularized operations to stay closed. The usual representation is selective: take the arrangement of all bounding hyperplanes, and mark each of its faces as in or out. Hachenberger, Kettner and Mehlhorn built the three-dimensional version, the selective Nef complex, with exact arithmetic, and it is the basis of exact Boolean operations and Minkowski sums of polyhedra in CGAL. This page gives the data structure in the plane, where the faces are vertices, edges and cells of a line arrangement, and the closure results with proofs.
In plain words
Draw a few straight lines across a sheet of paper. They cut it into pieces: points where lines cross, bits of lines between crossings, and open regions between the lines. Now colour some of the pieces. Any set you can make from half-planes by "and", "or" and "not" is exactly such a colouring, for some lines.
That gives a simple way to store the set: the lines, and a yes or no for every piece. To combine two sets, draw both sets of lines, so the pieces get smaller, and colour each small piece by the rule. To find the inside of a set, keep a coloured piece only if all pieces that touch it are coloured too. To find the closure, add every piece that touches a coloured one.
The abstract type
A Nef polygon (the case ) is a subset of the plane with these operations:
- Build an open or closed half-plane or , the empty set or the whole plane.
- Booleans: union, intersection, difference, symmetric difference and complement, with no regularization.
- Topology: interior, closure, boundary and regularization .
- Queries: does the set contain a point ; is it empty; how many marked vertices, edges and cells does it have.
- Simplify: drop the lines on which the set does not depend.
The values are the sets, not their descriptions: two formulas that give the same set give equal Nef polygons, and emptiness of the symmetric difference tests this.
Representation
Let be a finite set of lines, each in a canonical form with the first nonzero coefficient of equal to 1. The sign vector of a point is . The faces of the arrangement of are the classes of points with equal sign vectors: vertices, open edges and open cells, of dimension 0, 1 and 2 by the number of zero signs. A face is above a face when and ; the faces above are its star. In sign vectors, is above exactly when agrees with wherever is nonzero.
A Nef polygon is stored as the pair , where is the set of marked faces, given by their sign vectors. The arrangement keeps, for each face, its dimension and its star. The code builds them from the lines. Each pair of lines that cross gives a vertex. The vertices on each line, sorted along it, cut it into edges. Each edge has two cells, its sign vector with the zero for its line replaced by and by . The star of an edge is its two cells. The star of a vertex is the edges that end at it and their cells.
Operations
CONTAINS(A, p)- 1
return σ_A(p) ∈ A.marks ▷ O(n) sign tests COMBINE(A, B, op) ▷ op is and, or, minus or xor- 2
H ← A.lines ∪ B.lines, as canonical lines - 3
build the arrangement of H: its faces, their dimensions and stars - 4
for each face f of the arrangement do - 5
f_A ← f restricted to A.lines; f_B ← f restricted to B.lines - 6
mark f if op(f_A ∈ A.marks, f_B ∈ B.marks) - 7
return (H, marks) INTERIOR(A)- 8
return the marked faces f whose whole star is marked CLOSURE(A)- 9
return the faces f that are marked or have a marked face in their star BOUNDARY(A)- 10
return CLOSURE(A) minus INTERIOR(A)
Complement flips every mark on the same arrangement. A half-plane is built on the arrangement of its one line: two cells and the line itself, which is marked when the half-plane is closed. Regularization is CLOSURE(INTERIOR(A)).
Simplify. Line can be dropped when the mark of every face depends only on its signs on the other lines, that is, when the set is a union of faces of the coarser arrangement. The code drops such lines one at a time, rebuilding the arrangement after each.
Example
Take the closed square , the segment from to and the point , each built as an intersection of four closed half-planes, and let be their union. Its arrangement has the 8 lines and , with 16 vertices, 40 edges and 25 cells. The line runs through the square, so the square is two cells, the edge between them and the six vertices and six edges around them.
| set | marked vertices | marked edges | marked cells | lines after simplify |
|---|---|---|---|---|
| 8 | 8 | 2 | 8 | |
| 0 | 1 | 2 | 4 (the open square: 0, 0, 1) | |
| 8 | 8 | 2 | 8 (it is , which is closed) | |
| 8 | 7 | 0 | 8 | |
| 6 | 7 | 2 | 4 (the closed square: 4, 4, 1) | |
| complement of | 8 | 32 | 23 | 8 |
The interior of keeps the inner edge on , since both cells beside it are marked, and drops the segment and the point, whose stars are not marked. Regularization removes the segment and the point and gives back the square, which is the r-set that a classical modeler would keep. A Nef polygon keeps all three parts. Every line of is needed: and for the segment, and for the point.
A second example shows why r-sets need regularized operations. The closed half-planes and are both r-sets, but their intersection is the line : one marked edge and no cells. It is a Nef polygon, but not an r-set, and its regularization is empty.
Correctness
The three facts below are proved in the proof file.
- Every Nef polygon is a finite union of faces of a line arrangement, and every such union is a Nef polygon. A half-plane is a union of faces of the arrangement of its line. Unions of faces of a fixed arrangement are closed under complement and intersection, and a finer arrangement refines every face of a coarser one. Conversely, each face is an intersection of open half-planes and lines, and a line is the complement of the union of two open half-planes.
- The topological operations depend only on the star. Every point of a face has a neighbourhood that meets exactly and the faces of its star. So is interior to a union of faces exactly when and its whole star are in , and in the closure exactly when or a face of its star is in . Lines L8 and L9 compute this, and the results are again unions of faces, so Nef polygons are closed under interior, closure, boundary and regularization.
- Booleans are exact on the common refinement. Each face of the arrangement of lies inside the face of 's arrangement with the restricted sign vector, so line L6 marks the face exactly when its points satisfy the Boolean rule.
By contrast, the r-sets, the closed regular sets with , are not closed under intersection, as the example of the line shows, and not under complement, since the complement of a closed set is open. The regularized operations fix this, and Nef polygons give them by line L8, then line L9.
The tests check the code against the defining formulas. A random formula over 1 to 16 half-planes with integer coefficients in , open or closed, combined by and, or, minus, xor and not, is evaluated at every grid point with denominator 2 in and at every crossing of two of its lines. The answer is compared with the Nef polygon's CONTAINS. Interior, closure and boundary are checked the same way against an independent oracle. The oracle evaluates the formula at and at for a fixed set of directions that has a direction in every wedge between two possible lines, with small enough that no other line is crossed. Nested topological operators shrink by a factor of 100 per level. The tests also check , , and , that regularization is idempotent, and that simplification keeps the set.
Proof: Nef polygons are the unions of arrangement faces, are closed under Booleans and the topological operations, and the stored operations are exactfull
We use the notation and the pseudocode of the page. A Nef polygon is a subset of obtained from finitely many open half-planes by complement and intersection. Union and difference follow by De Morgan's laws. For a finite set of distinct lines, is its arrangement, whose faces are the classes of equal sign vectors, and a union of faces of is a set for some set of faces.
Lemma 1 (faces are convex and the sign vector order is the closure order). Each face of is a nonempty convex set, relatively open, of dimension 2 minus the rank of the lines on which it lies: a cell, an open edge or a vertex. For faces , exactly when for every with .
Proof. A face is the solution set of finitely many strict and non-strict linear constraints or , so it is convex. It is relatively open in the affine set cut out by its equations. If and , then a point of has a neighbourhood where line has the constant sign , and this neighbourhood meets , so . Conversely, suppose agrees with where is nonzero. Take and . For , the point has sign on every line: if , both ends have that sign; if , the value is times its value at . So the half-open segment lies in and . Since is convex and every point of it is in , .
Lemma 2 (local structure). Let be a point of the face . There is a disc around such that the faces that meet are exactly and the faces of its star, the faces with .
Proof. Let be a disc around that meets no line through which does not pass. On every line with keeps the sign , so every face that meets agrees with where is nonzero, and it is or in its star by Lemma 1. Conversely, every face of the star has in its closure (by the segment of the proof of Lemma 1), so it meets .
Theorem 1 (Nef polygons are the unions of faces). A set is a Nef polygon exactly when it is a union of faces of for some finite .
Proof. A Nef polygon is built from open half-planes with lines in some finite set . An open half-plane over a line of is the union of the faces with sign on that line. Unions of faces of a fixed arrangement are closed under complement (take the other faces) and intersection (take the common faces), because the faces partition the plane. So every Nef polygon over is a union of faces of . Conversely, a face with sign vector is the intersection, over , of the open half-plane if , and of the line if . A line is the complement of the union of its two open half-planes. So a face is a Nef polygon, and so is a finite union of faces.
Theorem 2 (closure under the topological operations). If is a union of faces of , then so are , , and . A face is in exactly when and its whole star are in , and in exactly when or some face of its star is in . So Nef polygons are closed under interior, closure, boundary and regularization.
Proof. Let and as in Lemma 2. If and its star are in , then , so . If some face of the star or is not in , then every disc around , shrunk inside , meets that face (by Lemma 2 applied to smaller discs), so . The closure is the complement of the interior of the complement, which gives the second rule. Both rules depend only on , so the results are unions of faces. The boundary is , and regularization composes the two. Theorem 1 turns these unions back into Nef polygons.
Lemma 3 (the arrangement in the code). The constructor of Arrangement lists every face of once, and up[f] is exactly the star of .
Proof. If is empty there is one face, the plane, with an empty star. Otherwise, every vertex lies on two lines that are not parallel and is found as their crossing. On line , the vertices sorted by the parameter cut the line into open segments and two rays, or leave it whole if there are none. A segment between consecutive vertices crosses no other line, so it is one edge, and its midpoint, a point beyond each end, or any point of a line without vertices, gives its sign vector. Each edge has exactly one zero, since distinct canonical lines meet in at most one point, which would be a vertex. Every cell has an edge on its boundary, since is not empty and the cell is not the plane. The cells beside an edge on line are the sign vectors of the edge with at . Both are realized by points near the middle of the edge, so every cell is listed. For the star: by Lemma 1, the faces above an edge are the two cells beside it. The faces above a vertex are the edges whose closure contains , which are the edges with as an endpoint, and the cells whose closure contains . Such a cell is a convex region with on its boundary, so it is a wedge between two consecutive lines through near , and its boundary contains an edge that ends at . So it is a cell of one of those edges.
Theorem 3 (the operations are exact). CONTAINS, COMBINE, INTERIOR, CLOSURE, BOUNDARY, the complement and simplify return the stated sets, and all of them terminate.
Proof. CONTAINS: lies in the face with sign vector , which is marked exactly when that face is in the set. COMBINE: by canonical forms, has no duplicates, and for a face of the merged arrangement, every point of has the sign vector on the lines of , so lies inside the face of , and exactly when is marked. The same holds for . So line L6 marks exactly when , and since the faces partition the plane, the result is . Complement: the faces partition the plane. Lines L8 to L10: Theorem 2 with Lemma 3. simplify: if the mark of every face depends only on its signs off line , then the set is the union of the faces of that are projections of marked faces, since each face of the coarse arrangement is the union of the fine faces that project to it. So dropping line keeps the set. Each round removes a line, so there are at most rounds. Every loop runs over a finite list.
Corollary (r-sets need regularization). The r-sets, the closed regular sets , are not closed under intersection or complement. The closed half-planes and are r-sets, but their intersection is the line , whose interior is empty, so of it is empty and not the line. The complement of a nonempty bounded r-set is open and not closed, so not an r-set. The regularized operations and return r-sets, because is idempotent. On one side, is an open subset of , so , and taking closures gives . On the other, , and taking closures gives . Nef polygons need no regularization, since by Theorems 1 and 2 each plain operation already returns a Nef polygon.
Complexity
The following is proved for the plane code, where is the number of distinct lines:
- An arrangement of lines has at most vertices, edges and cells, so faces. Each sign vector has entries, so the representation takes space, and building the arrangement takes time, plus for sorting the vertices along the lines.
- CONTAINS takes time. A Boolean operation on sets with and lines takes time. Complement, interior, closure and boundary take time linear in the total size of the stars, which is , times for hashing a sign vector.
- Simplification tries each line and rebuilds the arrangement after each drop, so it takes time.
A plane map, a doubly connected edge list with a mark on each vertex, edge and face, stores the same thing in space and overlays two maps in time for maps of total size with crossings. In three dimensions, the selective Nef complex of a polyhedron with vertices, edges and faces is built and combined in time that depends on the overlay of the local sphere maps and on the number of crossings. Hachenberger, Kettner and Mehlhorn measured the running times of their implementation on large models; this page states no worst-case bound for it.
Variants
- Selective Nef complex (three dimensions). Hachenberger, Kettner and Mehlhorn store a cell complex of vertices, edges, facets and volumes, each with a mark. Each vertex has a sphere map: the intersection of the set with a small sphere around the vertex. It is a Nef polygon on the sphere, made of points (edges leaving the vertex), arcs (facets) and regions (volumes), each with a mark. Booleans overlay the sphere maps at every vertex of both inputs and at new vertices where edges cross faces, combine the marks, and then simplify by removing the parts that do not change the set. The local picture at a vertex is what Nef called the local pyramid.
- Plane maps. In the plane the same idea is a plane map with marks, the two-dimensional structure on which the three-dimensional one is built.
- Without the arrangement. A set can also be kept as a Boolean formula over half-spaces, a CSG tree without regularization. Membership is then easy, but equality, emptiness and the topological operations need the arrangement.
- Selective geometric complexes. The SGC of Rossignac and O'Connor uses the same in-or-out marks on the cells of a complex, with curved cells and any dimension, but without the half-space generation of Nef sets.
- Regularized subsets. A modeler that needs only solids can apply regularization after every operation and store the result as a B-rep, which is smaller. The Nef structure is then used only where the exactness or the lower-dimensional parts matter.
When to use it
Use Nef polyhedra when the Boolean operations must be exact and must handle every degenerate case: touching faces, coplanar faces, edges that meet in a point, sets that pinch to a line. This is the case in robust Minkowski sums, in configuration spaces, and in geometric software where a wrong answer is worse than a slow one. Use them also when the lower-dimensional parts are part of the model, such as cuts, sheets and wires in a non-manifold model, or when the topological operations are needed. For everyday solid modeling with curved surfaces and tolerances, a B-rep kernel with regularized operations is faster and smaller. The Nef structure is limited to linear geometry.
Pitfalls
- The same line twice. If and give two different line records, the arrangement has a duplicate line, and the faces are counted twice. Bring every line to a canonical form, as the code does, before merging line sets.
- Floating-point coefficients. A sign vector is only meaningful if every sign is exact. With floating-point arithmetic, a point near a crossing gets inconsistent signs, and two faces that should be equal differ. Use rational or integer coefficients, or an exact predicate kernel such as the orientation test with exact arithmetic.
- Forgetting the lower-dimensional faces. A Boolean operation that marks only cells computes the regularized result, not the Nef result. The edges and vertices must be marked too.
- Growth of the arrangement. Every operation adds the lines of both inputs, and the arrangement grows quadratically in their number. Simplify after operations, or the size grows with the length of the modeling history and not with the complexity of the set.
- Unbounded sets. Nef polyhedra include unbounded sets such as half-planes. A modeler that expects bounded solids must check boundedness, or intersect with a big box.
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/nef-polyhedron/. The authors are listed in prov/Q616YB.jsonl.
"""Nef polygons: plane sets built from half-planes by Boolean operations.
A Nef polygon over a finite set of lines is a union of faces of the line
arrangement: vertices, open edges and open cells. A face is named by its
sign vector, the signs of a x + b y + c at its points for every line, and
the set is stored as the set of marked sign vectors. This is the selective
idea behind the plane maps of Seel and the selective Nef complexes of
Hachenberger and Kettner, without their geometric maps: the faces here are
found from the lines, and the incidences come with them.
Booleans overlay the two arrangements and combine the marks. Interior,
closure and boundary look at the star of each face: the faces whose closure
contains it. All arithmetic is exact with Fraction.
Precondition: lines have rational coefficients and (a, b) != (0, 0).
Cost: an arrangement of n lines has O(n^2) faces and is built in O(n^3)
time, since each sign vector has n entries. A Boolean operation builds the
arrangement of the union of the two line sets, so it takes O((n1 + n2)^3).
Interior, closure and boundary take time linear in the total size of the
stars, O(n^3) in all. Point membership takes O(n).
"""
from __future__ import annotations
from fractions import Fraction
from typing import Callable, Iterable, Sequence
Line = tuple[Fraction, Fraction, Fraction]
Point = tuple[Fraction, Fraction]
SV = tuple[int, ...]
def sign(v: Fraction) -> int:
return (v > 0) - (v < 0)
def canonical(a, b, c) -> tuple[Line, int]:
"""Scale a x + b y + c so that its first nonzero coefficient of (a, b)
is 1. Returns the line and the sign of the factor removed."""
a, b, c = Fraction(a), Fraction(b), Fraction(c)
k = a if a != 0 else b
if k == 0:
raise ValueError("not a line")
return (a / k, b / k, c / k), sign(k)
def side(line: Line, p: Point) -> int:
return sign(line[0] * p[0] + line[1] * p[1] + line[2])
class Arrangement:
"""The faces of the arrangement of distinct lines, by sign vector, with
their dimension and the set of faces above each one (its star)."""
def __init__(self, lines: Sequence[Line]):
self.lines: list[Line] = list(lines)
self.index = {l: i for i, l in enumerate(self.lines)}
self.dim: dict[SV, int] = {}
self.up: dict[SV, set[SV]] = {}
n = len(self.lines)
if n == 0:
self.dim[()] = 2
self.up[()] = set()
return
on_line: list[list[Point]] = [[] for _ in range(n)]
for i in range(n):
for j in range(i + 1, n):
p = self._meet(self.lines[i], self.lines[j])
if p is not None:
on_line[i].append(p)
on_line[j].append(p)
for i, (a, b, c) in enumerate(self.lines):
d = (-b, a)
vs = sorted(set(on_line[i]), key=lambda p: p[0] * d[0] + p[1] * d[1])
if vs:
reps = [(vs[0][0] - d[0], vs[0][1] - d[1], None, vs[0])]
reps += [((u[0] + w[0]) / 2, (u[1] + w[1]) / 2, u, w) for u, w in zip(vs, vs[1:])]
reps.append((vs[-1][0] + d[0], vs[-1][1] + d[1], vs[-1], None))
else:
p0 = (Fraction(0), -c / b) if b != 0 else (-c / a, Fraction(0))
reps = [(p0[0], p0[1], None, None)]
for x, y, u, w in reps:
e = self.sv((x, y))
cells = [e[:i] + (s,) + e[i + 1:] for s in (1, -1)]
self.dim[e] = 1
self.up.setdefault(e, set()).update(cells)
for f in cells:
self.dim[f] = 2
self.up.setdefault(f, set())
for v in (u, w):
if v is not None:
vv = self.sv(v)
self.dim[vv] = 0
self.up.setdefault(vv, set()).update([e] + cells)
@staticmethod
def _meet(l1: Line, l2: Line) -> Point | None:
det = l1[0] * l2[1] - l1[1] * l2[0]
if det == 0:
return None
return ((l1[1] * l2[2] - l1[2] * l2[1]) / det, (l1[2] * l2[0] - l1[0] * l2[2]) / det)
def sv(self, p: Point) -> SV:
return tuple(side(l, p) for l in self.lines)
def faces(self) -> list[SV]:
return sorted(self.dim)
class NefPolygon:
"""A Nef polygon: an arrangement and the set of its marked faces."""
def __init__(self, arr: Arrangement, marks: Iterable[SV]):
self.arr = arr
self.marks = frozenset(marks)
# construction
@staticmethod
def halfplane(a, b, c, closed: bool) -> "NefPolygon":
"""{(x, y) : a x + b y + c > 0}, or >= 0 when closed."""
line, s = canonical(a, b, c)
arr = Arrangement([line])
return NefPolygon(arr, [f for f in arr.faces() if s * f[0] > 0 or (closed and f[0] == 0)])
@staticmethod
def empty() -> "NefPolygon":
return NefPolygon(Arrangement([]), [])
@staticmethod
def plane() -> "NefPolygon":
return NefPolygon(Arrangement([]), [()])
# queries
def contains(self, p: Sequence) -> bool:
return self.arr.sv((Fraction(p[0]), Fraction(p[1]))) in self.marks # @line L1
def is_empty(self) -> bool:
return not self.marks
# Boolean operations
def _combine(self, other: "NefPolygon", op: Callable[[bool, bool], bool]) -> "NefPolygon":
lines = list(dict.fromkeys(self.arr.lines + other.arr.lines)) # @line L2
arr = Arrangement(lines) # @line L3
ia = [arr.index[l] for l in self.arr.lines]
ib = [arr.index[l] for l in other.arr.lines]
marks = []
for f in arr.faces(): # @line L4
fa = tuple(f[k] for k in ia) # @line L5
fb = tuple(f[k] for k in ib)
if op(fa in self.marks, fb in other.marks): # @line L6
marks.append(f)
return NefPolygon(arr, marks) # @line L7
def __or__(self, other):
return self._combine(other, lambda x, y: x or y)
def __and__(self, other):
return self._combine(other, lambda x, y: x and y)
def __sub__(self, other):
return self._combine(other, lambda x, y: x and not y)
def __xor__(self, other):
return self._combine(other, lambda x, y: x != y)
def complement(self) -> "NefPolygon":
return NefPolygon(self.arr, [f for f in self.arr.faces() if f not in self.marks])
# topological operations
def interior(self) -> "NefPolygon":
m = self.marks
return NefPolygon(self.arr, [f for f in m if self.arr.up[f] <= m]) # @line L8
def closure(self) -> "NefPolygon":
m = self.marks
return NefPolygon(self.arr, [f for f in self.arr.faces()
if f in m or any(g in m for g in self.arr.up[f])]) # @line L9
def boundary(self) -> "NefPolygon":
return self.closure() - self.interior() # @line L10
def regularization(self) -> "NefPolygon":
return self.interior().closure()
def simplify(self) -> "NefPolygon":
"""Drop lines on which the set does not depend: line i goes when the
mark of every face is a function of its signs on the other lines."""
cur = self
changed = True
while changed:
changed = False
for i in range(len(cur.arr.lines)):
seen: dict[SV, bool] = {}
ok = True
for f in cur.arr.faces():
g = f[:i] + f[i + 1:]
if seen.setdefault(g, f in cur.marks) != (f in cur.marks):
ok = False
break
if ok:
arr = Arrangement(cur.arr.lines[:i] + cur.arr.lines[i + 1:])
cur = NefPolygon(arr, [g for g, mk in seen.items() if mk])
changed = True
break
return cur
def count_by_dimension(self) -> tuple[int, int, int]:
c = [0, 0, 0]
for f in self.marks:
c[self.arr.dim[f]] += 1
return (c[0], c[1], c[2])
test_nef_polyhedron.py 204 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nef-polyhedron/. The authors are listed in prov/Q616YB.jsonl.
import random
import unittest
from fractions import Fraction as Fr
from math import atan2, gcd
from nef_polyhedron import NefPolygon
# Directions for the neighbourhood oracle: every primitive vector with
# entries in [-3, 3], which contains the direction of every line with such
# coefficients, and the sum of each pair of neighbours in angular order,
# which lies strictly inside every wedge between two such lines.
S3 = sorted({(x, y) for x in range(-3, 4) for y in range(-3, 4) if (x, y) != (0, 0) and gcd(x, y) == 1},
key=lambda d: atan2(d[1], d[0]))
DIRS = [(0, 0)] + S3 + [(S3[i][0] + S3[(i + 1) % len(S3)][0], S3[i][1] + S3[(i + 1) % len(S3)][1])
for i in range(len(S3))]
EPS0 = Fr(1, 1000)
def ev(node, p, eps=EPS0):
"""Evaluate a formula at p straight from its definition. A topological
operator looks at p and at p + eps d for every d in DIRS; eps is small
enough that these points see every face around p and no other."""
k = node[0]
if k == "h":
_, a, b, c, closed = node
v = a * p[0] + b * p[1] + c
return v >= 0 if closed else v > 0
if k == "not":
return not ev(node[1], p, eps)
if k in ("and", "or", "minus", "xor"):
x, y = ev(node[1], p, eps), ev(node[2], p, eps)
return {"and": x and y, "or": x or y, "minus": x and not y, "xor": x != y}[k]
near = [ev(node[1], (p[0] + eps * d[0], p[1] + eps * d[1]), eps / 100) for d in DIRS]
if k == "int":
return all(near)
if k == "cl":
return any(near)
if k == "bd":
return any(near) and not all(near)
raise ValueError(k)
def build(node):
k = node[0]
if k == "h":
return NefPolygon.halfplane(*node[1:])
if k == "not":
return build(node[1]).complement()
if k in ("and", "or", "minus", "xor"):
a, b = build(node[1]), build(node[2])
return {"and": a & b, "or": a | b, "minus": a - b, "xor": a ^ b}[k]
a = build(node[1])
return {"int": a.interior(), "cl": a.closure(), "bd": a.boundary()}[k]
def random_halfplane(rng):
while True:
a, b = rng.randint(-3, 3), rng.randint(-3, 3)
if (a, b) != (0, 0):
return ("h", a, b, rng.randint(-3, 3), rng.random() < 0.5)
def random_formula(rng, depth, topo):
if depth == 0 or rng.random() < 0.25:
return random_halfplane(rng)
r = rng.random()
if topo and r < 0.3:
return (rng.choice(["int", "cl", "bd"]), random_formula(rng, depth - 1, False))
if r < 0.4:
return ("not", random_formula(rng, depth - 1, topo))
return (rng.choice(["and", "or", "minus", "xor"]), random_formula(rng, depth - 1, topo),
random_formula(rng, depth - 1, topo))
def halfplanes(node, out):
if node[0] == "h":
out.append(node)
else:
for c in node[1:]:
halfplanes(c, out)
return out
def sample_points(node):
"""Grid points with denominator 2 and every crossing of two lines."""
pts = [(Fr(x, 2), Fr(y, 2)) for x in range(-6, 7) for y in range(-6, 7)]
hs = halfplanes(node, [])
for i in range(len(hs)):
for j in range(i + 1, len(hs)):
a1, b1, c1 = hs[i][1:4]
a2, b2, c2 = hs[j][1:4]
det = a1 * b2 - a2 * b1
if det != 0:
pts.append((Fr(b1 * c2 - c1 * b2, det), Fr(c1 * a2 - a1 * c2, det)))
return pts
class TestHandCases(unittest.TestCase):
def test_touching_halfplanes_meet_in_a_line(self):
a = NefPolygon.halfplane(1, 0, 0, True) # x >= 0
b = NefPolygon.halfplane(-1, 0, 0, True) # x <= 0
s = a & b
self.assertEqual(s.count_by_dimension(), (0, 1, 0))
self.assertTrue(s.contains((0, 5)))
self.assertTrue(s.regularization().is_empty())
def test_square_with_a_dangling_edge_and_a_point(self):
sq = (NefPolygon.halfplane(1, 0, 0, True) & NefPolygon.halfplane(-1, 0, 2, True)
& NefPolygon.halfplane(0, 1, 0, True) & NefPolygon.halfplane(0, -1, 2, True))
# the segment y = 1, 2 <= x <= 3
seg = (NefPolygon.halfplane(0, 1, -1, True) & NefPolygon.halfplane(0, -1, 1, True)
& NefPolygon.halfplane(1, 0, -2, True) & NefPolygon.halfplane(-1, 0, 3, True))
# the point (4, 4)
pt = (NefPolygon.halfplane(1, 0, -4, True) & NefPolygon.halfplane(-1, 0, 4, True)
& NefPolygon.halfplane(0, 1, -4, True) & NefPolygon.halfplane(0, -1, 4, True))
s = sq | seg | pt
for q, want in [((1, 1), True), ((Fr(5, 2), 1), True), ((4, 4), True), ((3, 2), False)]:
self.assertEqual(s.contains(q), want)
r = s.regularization()
self.assertFalse(r.contains((Fr(5, 2), 1)))
self.assertFalse(r.contains((4, 4)))
self.assertTrue(r.contains((2, 2)))
self.assertTrue(s.boundary().contains((Fr(5, 2), 1)))
# all 8 lines x = 0, 2, 3, 4 and y = 0, 1, 2, 4 carry some boundary
self.assertEqual(len(s.simplify().arr.lines), 8)
# the regularized set needs only the 4 lines of the square
self.assertEqual(len(r.simplify().arr.lines), 4)
def test_open_square_minus_its_diagonal(self):
sq = (NefPolygon.halfplane(1, 0, 0, False) & NefPolygon.halfplane(-1, 0, 1, False)
& NefPolygon.halfplane(0, 1, 0, False) & NefPolygon.halfplane(0, -1, 1, False))
diag = NefPolygon.halfplane(1, -1, 0, True) & NefPolygon.halfplane(-1, 1, 0, True)
s = sq - diag
self.assertEqual(s.count_by_dimension(), (0, 0, 2))
self.assertFalse(s.contains((Fr(1, 2), Fr(1, 2))))
self.assertTrue(s.closure().contains((Fr(1, 2), Fr(1, 2))))
self.assertTrue((s.regularization() ^ sq.closure()).is_empty())
class TestAgainstFormula(unittest.TestCase):
def test_boolean_formulas(self):
rng = random.Random(1)
checked = 0
for _ in range(80):
f = random_formula(rng, 4, False)
s = build(f)
for p in sample_points(f):
self.assertEqual(s.contains(p), ev(f, p), (f, p))
checked += 1
self.assertGreater(checked, 500)
def test_topological_operators(self):
rng = random.Random(2)
checked = 0
for _ in range(40):
f = (rng.choice(["int", "cl", "bd"]), random_formula(rng, 3, False))
s = build(f)
pts = sample_points(f)
for p in rng.sample(pts, min(25, len(pts))):
self.assertEqual(s.contains(p), ev(f, p), (f, p))
checked += 1
self.assertGreater(checked, 500)
def test_nested_formulas(self):
rng = random.Random(3)
for _ in range(25):
f = random_formula(rng, 4, True)
s = build(f)
pts = sample_points(f)
for p in rng.sample(pts, min(15, len(pts))):
self.assertEqual(s.contains(p), ev(f, p), (f, p))
class TestIdentities(unittest.TestCase):
def test_closure_identities(self):
rng = random.Random(4)
for _ in range(60):
s = build(random_formula(rng, 4, False))
c, i = s.closure(), s.interior()
self.assertTrue((c.closure() ^ c).is_empty())
self.assertTrue((i.interior() ^ i).is_empty())
self.assertTrue((s.complement().closure() ^ i.complement()).is_empty())
self.assertTrue((s.boundary() ^ (c & s.complement().closure())).is_empty())
self.assertTrue((s - c).is_empty() and (i - s).is_empty())
r = s.regularization()
self.assertTrue((r.regularization() ^ r).is_empty())
def test_simplify_keeps_the_set(self):
rng = random.Random(5)
for _ in range(60):
f = random_formula(rng, 4, False)
s = build(f)
t = s.simplify()
self.assertLessEqual(len(t.arr.lines), len(s.arr.lines))
self.assertTrue((s ^ t).is_empty())
for p in sample_points(f)[::7]:
self.assertEqual(t.contains(p), ev(f, p))
if __name__ == "__main__":
unittest.main()
History
Walter Nef defined the polyhedra generated by half-spaces in a 1978 book, as a basis for computer graphics, and showed their closure under the Boolean and topological operations. The theory was developed further by Hanspeter Bieri and Nef in the 1980s. Rossignac and Requicha argued in 1991 for non-regularized sets in solid modeling, and the selective geometric complex of Rossignac and O'Connor (1989) gave a general structure with in-or-out marks on cells. Michael Seel implemented planar Nef polyhedra in CGAL with plane maps. Peter Hachenberger, Lutz Kettner and Kurt Mehlhorn extended this to three dimensions with the selective Nef complex and published the data structure, the algorithms and experiments in 2007. CGAL's exact Boolean operations and Minkowski sums of polyhedra use it.
References
- Walter Nef, Beiträge zur Theorie der Polyeder, mit Anwendungen in der Computergraphik, Herbert Lang, Bern, 1978, the definition of polyhedra as the sets generated by finitely many open half-spaces under complement and intersection, and their closure under the topological operations
- Peter Hachenberger, Lutz Kettner and Kurt Mehlhorn, Boolean operations on 3D selective Nef complexes, data structure, algorithms, optimized implementation and experiments, Computational Geometry 38(1-2), 64 to 99, 2007, the selective Nef complex with sphere maps at the vertices, Boolean operations by overlay, selection and simplification, and the experiments with exact arithmetic
- Jarek R. Rossignac and Aristides A. G. Requicha, Constructive non-regularized geometry, Computer-Aided Design 23(1), 21 to 32, 1991, the case for non-regularized sets in solid modeling and Boolean operations that keep lower-dimensional parts
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 | W4 complete |
|
Tag Q616YB Edit this page History Report an error Markdown