Data structurecore
Winged-edge data structure
Also called winged edge, Baumgart winged edge.
Baumgart's B-rep in which each edge stores its two vertices, two faces and four neighbour edges, so edge queries take O(1) time and walks around a face or vertex O(1) per step.
- Time
- O(n) expected
- Space
- Θ(n) extra
- Where
- n = the number of edges
- Model
- Word RAM
- Evidence
- Proof sketchCode in 1 languages
The winged-edge data structure stores the boundary of a polyhedral solid with one record per edge. Each edge record holds the two vertices of the edge, the two faces on its two sides and four more edges, the wings: the edges before and after it on each of its two faces. Each vertex and each face stores one edge. Bruce Baumgart made it for computer vision in the early 1970s, and it was the first edge-based boundary representation. From one edge, the program can reach every adjacent vertex, face and edge in time, and it can walk around a face or around a vertex in time per step. The price is that an edge does not know in which direction a face uses it, so every step of a walk must test which side of the edge it is on.
In plain words
Think of each fold of a cardboard box as a small card. The card names the two corners at the ends of the fold and the two sides of the box that meet at it. It also names four more folds. On each of the two sides, it names the fold just before it and the fold just after it, when you go around that side.
To go around one side of the box, start at any fold of that side, look on its card for the fold after it on this side, and move to that fold. To go around a corner, look on the card for the fold just before it on the side that leaves the corner. The four wings around each card give the structure its name.
The abstract type
The structure stores a closed oriented polyhedral surface whose faces are disks, and it answers adjacency queries about it.
- : make the structure for the vertices and the faces , each a cyclic list of vertices, counterclockwise seen from outside.
- and : the two ends and the two faces of .
- : the edges of in counterclockwise order, so also its vertices.
- : the edges at in counterclockwise order, so also the neighbours and the faces of .
- : put a new vertex inside .
- and : cut into two faces by a new edge from to , and remove an edge that has two different faces.
The updates are three of the Euler operators, in the forms that keep one loop per face: SPLIT-EDGE is MEV, SPLIT-FACE is MEF and JOIN-FACES is KEF. Each one keeps , so the shell keeps its genus.
Representation
Each edge has a direction, from to . Seen from outside and walking from to , the face is on the left and on the right. The faces run counterclockwise seen from outside, so uses from start to end, and uses it from end to start.
| record | fields |
|---|---|
| edge | , , , and the four wings , , , |
| vertex | its point and one edge at |
| face | one edge of ; in a curved B-rep also the surface |
The wings and are the edges before and after in the counterclockwise loop of , and and are the same for . So the topology takes 8 references per edge and one per vertex and per face, in total. The half-edge form of the same surface stores 4 or 5 references per half-edge, 8 or 10 per edge, and it adds a loop record when faces have rings.
Baumgart's own edge nodes also hold list links and more fields than these eight; the table gives only the eight that carry the topology, as Weiler and Mäntylä describe them. Some texts call the four wings the clockwise and counterclockwise successors and predecessors, with different conventions for which is which, so read the convention of a source before you copy its code.
The edge record does not say in which direction a face uses the edge. To step to the next edge of face from edge , the program must test whether is or . This test needs the two faces of each edge to be different. In the same way, to step around vertex , it must test whether is or .
Operations
FACE-EDGES(f) ▷ the edges of f, counterclockwise from outside- 1
e₀ ← face_edge[f]; e ← e₀ - 2
repeat output e - 3
if f_left[e] = f then e ← left_next[e] else e ← right_next[e] - 4
until e = e₀ VERTEX-EDGES(v) ▷ the edges at v, counterclockwise from outside- 5
e₀ ← vertex_edge[v]; e ← e₀ - 6
repeat output e - 7
if v_start[e] = v then e ← left_prev[e] else e ← right_prev[e] - 8
until e = e₀ SPLIT-FACE(f, u, w) ▷ u, w on f and not joined by an edge- 9
walk f; find the edges a_in, a_out before and after u, and b_in, b_out before and after w - 10
make a face g and an edge n from u to w with f_left[n] ← f, f_right[n] ← g - 11
left_prev[n] ← a_in; left_next[n] ← b_out; right_prev[n] ← b_in; right_next[n] ← a_out - 12
for each edge of f from a_out to b_in: replace f by g on the side of f - 13
set the next wing of a_in on f, the prev wing of b_out on f, the next wing of b_in on g and the prev wing of a_out on g to n - 14
face_edge[f] ← n; face_edge[g] ← n
Around a face. Line L3 is the orientation test. If is the left face of , then uses from start to end, and the next edge of is . If not, uses from end to start, and the next edge is . The vertex at the start of on is in the first case and in the second.
Around a vertex. Let be an edge at , and let be the face that uses as it leaves : this is if and if not. The edge before in comes into . Seen from outside, lies counterclockwise from at , so this edge is the next edge counterclockwise around . Line L7 takes it from the wing on the side of .
Updates. In SPLIT-FACE, the new edge has on its left, so keeps the part of its loop from around to , and the new face gets the part from to . Line L12 moves the edges of that part to , one side field each. Line L13 sets the four wings that pointed across the cut. JOIN-FACES does the opposite steps: it moves the edges of the right face of to the left face and joins the wings around the two ends of . SPLIT-EDGE puts a new vertex inside : it makes a new edge from to , changes to , and sets six wings. It needs no walk, so it takes time.
Build. BUILD makes one edge for each unordered pair that is a side of a face, with a hash map on the pair. The first face that uses the pair is the left face, and the direction of the edge is the direction in which that face uses it. The second face must use it in the other direction, and it becomes the right face. Then BUILD walks each face list once and sets the prev and next wings on the side of that face. It fails if a pair is used by one face only, by more than two faces, twice in one direction, or twice by one face, and if the walk around a vertex misses an edge at that vertex.
Example
Take the cube with the vertices , , , and to the same points with , and the faces at the bottom, at the top, , , and . BUILD gives these 12 edges:
| 0 | 0 | 3 | 0 | 5 | 3 | 1 | 11 | 9 |
| 1 | 3 | 2 | 0 | 4 | 0 | 2 | 10 | 11 |
| 2 | 2 | 1 | 0 | 3 | 1 | 3 | 8 | 10 |
| 3 | 1 | 0 | 0 | 2 | 2 | 0 | 9 | 8 |
| 4 | 4 | 5 | 1 | 2 | 7 | 5 | 8 | 9 |
| 5 | 5 | 6 | 1 | 3 | 4 | 6 | 10 | 8 |
| 6 | 6 | 7 | 1 | 4 | 5 | 7 | 11 | 10 |
| 7 | 7 | 4 | 1 | 5 | 6 | 4 | 9 | 11 |
| 8 | 1 | 5 | 2 | 3 | 3 | 4 | 5 | 2 |
| 9 | 4 | 0 | 2 | 5 | 4 | 3 | 0 | 7 |
| 10 | 2 | 6 | 3 | 4 | 2 | 5 | 6 | 1 |
| 11 | 3 | 7 | 4 | 5 | 1 | 6 | 7 | 0 |
The face edges are , and the vertex edges are .
FACE-EDGES(2) starts at edge 3. Face 2 is on the right of edge 3, so the next edge is . Face 2 is on the left of edge 8, so the next edge is . Then and , the start. The walk uses the edges in both directions: the left and right sides alternate. The start vertices on face 2 are , , and , which is the face list .
VERTEX-EDGES(0) starts at edge 0, which leaves 0, so the next edge is . Edge 3 ends at 0, so the next is , and edge 9 also ends at 0, so the next is , the start. The neighbours of 0 are and the faces on the left of the edges out of 0 are , counterclockwise seen from outside the corner.
SPLIT-FACE(1, 4, 6) cuts the top face along its diagonal. It makes edge 12 from 4 to 6 with , and the wings , , , . Face 1 becomes and the new face 6 is . Now , as before.
Correctness
Assume BUILD returns. Then every edge has two different faces that use it in opposite directions, and on the side of each face, its two wings are its neighbours in the face list of that face. So line L3 moves from each edge of to the next edge of , and FACE-EDGES lists the face list of once and stops. The vertex step of line L7 is a permutation of the edges at , because its inverse is the next wing on the face that comes into , and each of its steps crosses one face at . A cycle of this permutation is one fan of faces at . BUILD checks that the cycle of has every edge at , so VERTEX-EDGES lists them all. Each update changes only the fields of the edges on the cut and keeps these two facts, so the queries stay correct after any sequence of updates. The full proof is in the proof file.
The orientation test of line L3 is correct only if . If both sides of are the same face, for example for a bridge edge that joins a hole to the outer boundary of a face, the test always takes the left wing, and the walk can go around the face in a loop that does not contain all its edges. BUILD rejects such input.
Proof: The winged-edge walks list each face and each vertex star exactly once, and the updates keep the wings correctfull
We use the pseudocode and the fields of the page. The input of BUILD is a list of faces, each a cyclic list of distinct vertices. A face uses the directed pair , indices mod . For an edge and a face with , write for left or right, and for the wings on that side, and for if the side is left and if it is right. Write for the other end.
Invariant W. (a) For each edge , . (b) For each face , the edges with can be listed as so that and , indices mod , and . (c) is an edge of , and is an edge with as an end. (d) For each vertex , the walk of lines L5 to L8 meets every edge with as an end.
The cyclic list of (b) is the face list of .
Lemma 1 (BUILD). If BUILD returns, then W holds, and the face list of each face is the input list of , up to a cyclic shift.
Proof. BUILD makes one edge per unordered pair that some face uses. If the first face that uses the pair uses it as , the edge gets , and . A later use is accepted only if it is by a face whose slot is still empty, and it sets . Any other use fails. After the loop, BUILD fails if some is empty or equal to . So if BUILD returns, each edge is used by exactly two different faces, the left face as and the right face as , and (a) holds. In particular is the first vertex of the pair that uses on , and the second. A face with distinct vertices uses each pair at most once. Now take the input list of and let be the edge of . These are different edges, they are all the edges of , and the second loop of BUILD sets and on the side of . Each side of each edge belongs to one face, so no other step writes these fields. Also and , which gives (b) and the claim about the face list. BUILD sets and to the first edge with as an end, and it fails if a vertex has none, so (c) holds. The last check of BUILD compares the length of the walk at each with the number of edges at , which gives (d) once Lemma 3 shows that the walk lists distinct edges.
Lemma 2 (FACE-EDGES). Under W, FACE-EDGES() stops and outputs the edges of once each, in the order of (b), starting at .
Proof. By (a), the test of line L3 decides correctly, so line L3 sets . By (b), is the cyclic shift on the edges of , and by (c) the walk starts on one of them. So the walk visits and returns to after exactly steps, at which point line L4 stops it.
Lemma 3 (VERTEX-EDGES). Under W, for a vertex let be the set of edges with as an end, and for let be the edge that line L7 picks. Then is a permutation of , and VERTEX-EDGES() stops and outputs the cycle of that contains , once each. With (d), this is all of .
Proof. Let and let be if and if not. Then : the face uses as it leaves . Line L7 sets , and by (b), . So , and uses it as it comes into . The two ends of an edge are different, because the vertices of a face are, so exactly one of the two cases holds for each edge. Now let , and let be the face that uses as it comes into : if and if not. If , then , because uses into and only one face does so, and by (b). So is determined by , and is injective on the finite set , hence a permutation. The walk of lines L5 to L8 applies from , which is in by (c), until it returns, so it outputs one cycle of once each and stops.
Geometrically, is the face just counterclockwise of at , seen from outside, and is the next edge counterclockwise. A cycle of is a fan of faces at , and (d) says that has one fan, which is the vertex condition of a 2-manifold.
Lemma 4 (SPLIT-EDGE). If W holds before SPLIT-EDGE(), it holds after it, every face list keeps its order with the new vertex put between and , and does not change.
Proof. Let , , and . On the edges are with , and on they are with . The update makes from to with the same two faces, sets , and sets the wings so that the cycle of becomes and the cycle of becomes . The heads and tails match: on , now ends at where starts, and ends at where starts; on , ends at where starts on that side, and ends at where starts on that side. No other face or wing changes. So (a) and (b) hold, and the update of keep (c), and the edges at are and , which line L7 joins in one cycle, so (d) holds at ; at the edge takes the place of in the cycle. One vertex and one edge are new, so is the same.
Lemma 5 (SPLIT-FACE). If W holds before SPLIT-FACE() and are vertices of that are not joined by an edge, then W holds after it, the face list of is the part of the old list from around to , the face list of the new face is the part from to , and does not change.
Proof. By Lemma 2, line L9 finds the cycle of . Let be the edge with tail and the edge with tail , so , , and . Since and are not joined, . The new edge runs from to , with on its left and on its right, so uses it as and as , and (a) holds for it. Line L12 gives the edges to , each on its side of . Lines L11 and L13 make the cycle of equal to , that is , and the cycle of equal to . On , ends at where starts, and ends at where starts. On , ends at where starts on the side of , and ends at where starts. The other wings of these edges point inside one of the two parts and are not changed, and the edges of other faces are not touched. So (b) holds, and the face lists are as claimed. Line L14 gives (c). For (d), at the old step becomes the two steps and : the edge is put into the one cycle at , and the same holds at . Each new edge is not an edge between the same ends as an old one, because of the test, so the edges at stay distinct. One edge and one face are new, so is the same.
Lemma 6 (JOIN-FACES). If W holds before JOIN-FACES(), and the two faces and have only the two ends of in common and each of has at least 3 edges, then W holds after it, and the face list of is the face list of with the part of from to put in place of .
Proof. The steps are the inverse of those of Lemma 5 with , , and : the edges of other than get on their side of , and the four wings that pointed to are joined. Since and share no vertex other than and , they share no edge other than , so no edge gets on both sides, and (a) holds. The cycle of becomes , and the heads and tails match at and at , which gives (b). The fields that pointed to are moved to and , which gives (c). At , the steps and become , which removes from the cycle and keeps one cycle, and the same holds at . The degree condition keeps at least 2 edges at each end, so no vertex is left with a face loop of length 2. So (d) holds.
Theorem. After BUILD and any sequence of SPLIT-EDGE, SPLIT-FACE and JOIN-FACES whose preconditions hold, FACE-EDGES() outputs the face list of each face and VERTEX-EDGES() outputs all edges at each vertex , each once and in counterclockwise order, and both stop. The edge queries return the fields of the edge record, which are correct by W.
Proof. W holds after BUILD by Lemma 1, and after each update by Lemmas 4 to 6, by induction on the number of updates. Lemmas 2 and 3 give the output and the termination of the walks under W.
The tests check the same facts on the cube, the octahedron and a torus, and after each of 360 random steps, against a brute force that stores only the face lists and answers each query by a scan of all faces. They also check that BUILD rejects an open surface, a reversed face, an edge on three faces and two tetrahedra that share one vertex.
Complexity
Let be the number of edges.
- BUILD takes expected time with a hash map on the vertex pairs, and space: edge fields, one field per vertex and one per face.
- EDGE-VERTICES, EDGE-FACES and each wing take time. The test of line L3 or line L7 is one comparison.
- FACE-EDGES() takes time for a face with edges, and VERTEX-EDGES() takes time for a vertex of degree . So the neighbours, the faces at a vertex and the vertices of a face take time linear in the size of the answer.
- SPLIT-EDGE takes time. SPLIT-FACE walks to find and and to change the face of the moved edges, so it takes time, plus for the test that and are not neighbours. JOIN-FACES takes time linear in the sizes of the two faces.
The constant time of the summary is the time of one step. No structure of this kind lists the edges of a face in less than steps, because it must output them.
Variants
- Half-edge. Split each edge record into two half-edges, one for each face. Each half-edge knows its own face and its own next edge, so the orientation test of line L3 goes away, and a face can have rings through a loop record. This is the doubly connected edge list of planar subdivisions, and the B-rep page builds a solid modeler form of it.
- Quad-edge. The quad-edge data structure of Guibas and Stolfi stores one record per edge with four directed versions of it, two for the edge and two for its dual. It stores the surface and its dual together, and it allows non-orientable surfaces.
- Signed edge references. Store each wing, each and each as an edge with a direction bit. Then the walks need no test, and the structure is close to a half-edge structure that shares one record per edge.
- Faces with rings. Weiler's modified winged edge puts a loop record between the edges and the faces, so that a face can have several boundaries. Without it, a face with a hole needs a bridge edge with the same face on both sides, and the orientation test fails on it.
- Non-manifold. The radial edge data structure stores any number of faces around an edge, which the two face fields of a winged edge cannot do.
When to use it
Use the winged edge when the faces are disks, the surface is a closed 2-manifold, and memory per edge matters more than the cost of one comparison per step. It suits polyhedral modelers and mesh editors that make many local changes by Euler operators, because each edge has only one record to update. When faces can have holes, or when code must walk loops fast and without branches, use a half-edge form. For a triangle mesh that does not change its connectivity, a corner table or the face-vertex lists of a polygon mesh use less memory.
Pitfalls
- The orientation test. Every step around a face must test whether the face is the left or the right face of the edge. Code that always takes walks on the wrong face as soon as an edge is used backwards, as edges 3 and 4 of face 2 are in the example.
- Same face on both sides. The test is ambiguous if . This happens with bridge edges in faces with holes and with dangling edges inside a face. Reject them, or store directions with the references.
- Wing conventions. Sources disagree on the names of the four wings and on the direction of the face loops. Mixing two conventions gives walks that go backwards or jump between faces.
- Double edges. SPLIT-FACE between two vertices that are already joined by an edge makes two edges with the same ends. A face list then no longer gives the surface, and many algorithms that look up an edge by its ends break. Test VERTEX-EDGES() first, as the implementation does.
- One fan per vertex. Two solids that touch at one vertex pass the edge tests of BUILD, but the walk around that vertex sees only one of them. Count the edges at each vertex and compare with the walk.
- Wings after an update. An update must set the wings of the neighbouring edges on the correct side. Use helper functions that choose the side by the face, as the implementation does, and check all wings after each update in the tests.
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/winged-edge-data-structure/. The authors are listed in prov/4Q9BTY.jsonl.
"""Baumgart's winged-edge structure for a closed polyhedral surface.
Each edge e runs from v_start[e] to v_end[e]. Seen from outside the solid and
walking from v_start to v_end, the face f_left[e] is on the left and f_right[e]
on the right. The faces run counterclockwise seen from outside (the right-hand
rule), so f_left[e] traverses e from start to end and f_right[e] from end to
start. The four wings are the edges before and after e in the counterclockwise
loop of each face: left_prev, left_next, right_prev and right_next.
Each vertex and each face stores one edge. The faces are disks without rings,
and the two faces of an edge are different.
"""
from __future__ import annotations
from typing import Optional, Sequence
FIELDS = ("v_start", "v_end", "f_left", "f_right", "left_prev", "left_next", "right_prev", "right_next")
class WingedEdgeError(ValueError):
"""The input or the arguments do not fit the structure."""
class WingedEdge:
def __init__(self, n_vertices: int, faces: Sequence[Sequence[int]]) -> None:
"""Build from faces given as counterclockwise lists of vertex ids 0..n-1.
Time O(n) expected for n = the sum of the face sizes, with one hash map.
"""
self.v_start: list[int] = []
self.v_end: list[int] = []
self.f_left: list[int] = []
self.f_right: list[int] = []
self.left_prev: list[int] = []
self.left_next: list[int] = []
self.right_prev: list[int] = []
self.right_next: list[int] = []
self.vertex_edge: list[int] = [-1] * n_vertices
self.face_edge: list[int] = []
self.alive_e: list[bool] = []
self.alive_f: list[bool] = []
key: dict[tuple[int, int], int] = {} # (u, v) with u < v -> edge
for f, cyc in enumerate(faces):
k = len(cyc)
if k < 3 or len(set(cyc)) != k:
raise WingedEdgeError("a face needs at least 3 distinct vertices")
self.face_edge.append(-1)
self.alive_f.append(True)
for i in range(k):
u, v = cyc[i], cyc[(i + 1) % k]
e = key.get((min(u, v), max(u, v)))
if e is None:
e = self._new_edge(u, v, f, -1)
key[(min(u, v), max(u, v))] = e
elif self.v_start[e] == v and self.f_right[e] == -1:
self.f_right[e] = f
else:
raise WingedEdgeError("an edge is used twice in one direction or by more than two faces")
self.face_edge[f] = key[(min(cyc[0], cyc[1]), max(cyc[0], cyc[1]))]
for e in range(len(self.v_start)):
if self.f_right[e] == -1:
raise WingedEdgeError("an edge has only one face")
if self.f_left[e] == self.f_right[e]:
raise WingedEdgeError("an edge has the same face on both sides")
for f, cyc in enumerate(faces):
k = len(cyc)
es = [key[(min(cyc[i], cyc[(i + 1) % k]), max(cyc[i], cyc[(i + 1) % k]))] for i in range(k)]
for i, e in enumerate(es):
self._set_prev(e, f, es[i - 1])
self._set_next(e, f, es[(i + 1) % k])
for e in range(len(self.v_start)):
for v in (self.v_start[e], self.v_end[e]):
if self.vertex_edge[v] == -1:
self.vertex_edge[v] = e
if -1 in self.vertex_edge:
raise WingedEdgeError("a vertex is on no face")
self._check_fans()
def _check_fans(self) -> None:
"""Each vertex walk must meet every edge at the vertex: one fan of faces."""
degree = [0] * len(self.vertex_edge)
for e in self.edges():
degree[self.v_start[e]] += 1
degree[self.v_end[e]] += 1
for v in range(len(self.vertex_edge)):
if len(self.vertex_edges(v)) != degree[v]:
raise WingedEdgeError(f"vertex {v} has more than one fan of faces")
# ----- O(1) helpers: the wing of e on the side of face f -----
def _new_edge(self, u: int, v: int, fl: int, fr: int) -> int:
for name, val in zip(FIELDS, (u, v, fl, fr, -1, -1, -1, -1)):
getattr(self, name).append(val)
self.alive_e.append(True)
return len(self.v_start) - 1
def _side(self, e: int, f: int) -> bool:
"""True if f is the left face of e, False if it is the right face."""
if self.f_left[e] == f:
return True
if self.f_right[e] == f:
return False
raise WingedEdgeError(f"face {f} is not on edge {e}")
def _next(self, e: int, f: int) -> int:
return self.left_next[e] if self._side(e, f) else self.right_next[e]
def _prev(self, e: int, f: int) -> int:
return self.left_prev[e] if self._side(e, f) else self.right_prev[e]
def _set_next(self, e: int, f: int, x: int) -> None:
if self._side(e, f):
self.left_next[e] = x
else:
self.right_next[e] = x
def _set_prev(self, e: int, f: int, x: int) -> None:
if self._side(e, f):
self.left_prev[e] = x
else:
self.right_prev[e] = x
def _set_face(self, e: int, old: int, new: int) -> None:
if self._side(e, old):
self.f_left[e] = new
else:
self.f_right[e] = new
def _tail(self, e: int, f: int) -> int:
"""The vertex where the loop of f enters e."""
return self.v_start[e] if self._side(e, f) else self.v_end[e]
# ----- queries -----
def edge_vertices(self, e: int) -> tuple[int, int]:
return self.v_start[e], self.v_end[e]
def edge_faces(self, e: int) -> tuple[int, int]:
"""(left face, right face), O(1)."""
return self.f_left[e], self.f_right[e]
def face_edges(self, f: int) -> list[int]:
"""The edges of f in counterclockwise order seen from outside."""
out = []
e0 = self.face_edge[f] # @line L1
e = e0
while True:
out.append(e) # @line L2
e = self.left_next[e] if self.f_left[e] == f else self.right_next[e] # @line L3
if e == e0: # @line L4
break
return out
def face_vertices(self, f: int) -> list[int]:
return [self._tail(e, f) for e in self.face_edges(f)]
def vertex_edges(self, v: int) -> list[int]:
"""The edges at v in counterclockwise order seen from outside."""
out = []
e0 = self.vertex_edge[v] # @line L5
e = e0
while True:
out.append(e) # @line L6
e = self.left_prev[e] if self.v_start[e] == v else self.right_prev[e] # @line L7
if e == e0: # @line L8
break
return out
def neighbors(self, v: int) -> list[int]:
return [self.v_end[e] if self.v_start[e] == v else self.v_start[e] for e in self.vertex_edges(v)]
def vertex_faces(self, v: int) -> list[int]:
"""The faces at v, counterclockwise: the face on the left of each edge out of v."""
return [self.f_left[e] if self.v_start[e] == v else self.f_right[e] for e in self.vertex_edges(v)]
def edges(self) -> list[int]:
return [e for e in range(len(self.v_start)) if self.alive_e[e]]
def faces(self) -> list[int]:
return [f for f in range(len(self.face_edge)) if self.alive_f[f]]
# ----- updates -----
def split_edge(self, e: int) -> int:
"""Put a new vertex m inside e. Afterwards e runs from v_start to m and a
new edge runs from m to the old v_end. Returns m. O(1)."""
a, b = self.v_start[e], self.v_end[e]
fl, fr = self.f_left[e], self.f_right[e]
x = self.left_next[e] # after e in fl
y = self.right_prev[e] # before e in fr
m = len(self.vertex_edge)
self.vertex_edge.append(e)
e2 = self._new_edge(m, b, fl, fr)
self.v_end[e] = m
self.left_next[e2], self.left_prev[e2] = x, e
self.left_next[e] = e2
self.right_next[e2], self.right_prev[e2] = e, y
self.right_prev[e] = e2
self._set_prev(x, fl, e2)
self._set_next(y, fr, e2)
if self.vertex_edge[b] == e:
self.vertex_edge[b] = e2
return m
def split_face(self, f: int, u: int, w: int) -> tuple[int, int]:
"""Add an edge n from u to w across f, two vertices of f that are not
joined by an edge. The part of f from w around to u stays f; the part
from u to w becomes a new face g. Returns (n, g). O(size of f + degree of u)."""
es = self.face_edges(f) # @line L9
tails = [self._tail(e, f) for e in es]
if u not in tails or w not in tails:
raise WingedEdgeError("u and w must be vertices of f")
iu, iw = tails.index(u), tails.index(w)
k = len(es)
if u == w or (iu + 1) % k == iw or (iw + 1) % k == iu:
raise WingedEdgeError("u and w must be different and not next to each other")
if w in self.neighbors(u):
raise WingedEdgeError("u and w are already joined by an edge")
a_out, a_in = es[iu], es[iu - 1]
b_out, b_in = es[iw], es[iw - 1]
g = len(self.face_edge)
self.face_edge.append(-1)
self.alive_f.append(True)
n = self._new_edge(u, w, f, g) # @line L10
self.left_prev[n], self.left_next[n] = a_in, b_out # @line L11
self.right_prev[n], self.right_next[n] = b_in, a_out
i = iu
while i != iw: # @line L12
self._set_face(es[i], f, g)
i = (i + 1) % k
self._set_next(a_in, f, n) # @line L13
self._set_prev(b_out, f, n)
self._set_next(b_in, g, n)
self._set_prev(a_out, g, n)
self.face_edge[f] = n # @line L14
self.face_edge[g] = n
return n, g
def join_faces(self, n: int) -> int:
"""Remove the edge n and join its right face into its left face. The two
faces must have only the two ends of n in common, and each end of n must
have at least 3 edges. Returns the deleted face. O(size of the faces)."""
f, g = self.f_left[n], self.f_right[n]
u, w = self.v_start[n], self.v_end[n]
vf, vg = set(self.face_vertices(f)), set(self.face_vertices(g))
if vf & vg != {u, w}:
raise WingedEdgeError("the two faces must meet only along the edge")
if len(self.vertex_edges(u)) < 3 or len(self.vertex_edges(w)) < 3:
raise WingedEdgeError("each end must keep at least 2 edges")
a_in, b_out = self.left_prev[n], self.left_next[n]
b_in, a_out = self.right_prev[n], self.right_next[n]
for e in self.face_edges(g):
if e != n:
self._set_face(e, g, f)
self._set_next(a_in, f, a_out)
self._set_prev(a_out, f, a_in)
self._set_next(b_in, f, b_out)
self._set_prev(b_out, f, b_in)
if self.vertex_edge[u] == n:
self.vertex_edge[u] = a_out
if self.vertex_edge[w] == n:
self.vertex_edge[w] = b_out
self.face_edge[f] = a_out
self.alive_e[n] = False
self.alive_f[g] = False
self.face_edge[g] = -1
return g
def check(self) -> None:
"""Check that the wings agree with the faces and the vertices."""
for e in self.edges():
for f, nxt, prv in ((self.f_left[e], self.left_next[e], self.left_prev[e]), (self.f_right[e], self.right_next[e], self.right_prev[e])):
if not self.alive_e[nxt] or not self.alive_e[prv]:
raise WingedEdgeError("a wing points to a deleted edge")
if self._prev(nxt, f) != e or self._next(prv, f) != e:
raise WingedEdgeError("the wings of two edges do not agree")
head = self.v_end[e] if f == self.f_left[e] else self.v_start[e]
if self._tail(nxt, f) != head:
raise WingedEdgeError("the next edge does not start where e ends")
if self.f_left[e] == self.f_right[e]:
raise WingedEdgeError("an edge has the same face on both sides")
for v, e in enumerate(self.vertex_edge):
if v not in (self.v_start[e], self.v_end[e]):
raise WingedEdgeError("a vertex edge does not touch the vertex")
for f in self.faces():
if f not in self.edge_faces(self.face_edge[f]):
raise WingedEdgeError("a face edge does not touch the face")
self._check_fans()
test_winged_edge_data_structure.py 187 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/winged-edge-data-structure/. The authors are listed in prov/4Q9BTY.jsonl.
import random
import unittest
from winged_edge_data_structure import WingedEdge, WingedEdgeError
CUBE = [[0, 3, 2, 1], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]
# vertices 0..3 at z = 0: (0,0), (1,0), (1,1), (0,1); 4..7 above them at z = 1
OCTAHEDRON = [[0, 2, 4], [2, 1, 4], [1, 3, 4], [3, 0, 4], [2, 0, 5], [1, 2, 5], [3, 1, 5], [0, 3, 5]]
# 0 = +x, 1 = -x, 2 = +y, 3 = -y, 4 = +z, 5 = -z
def torus(p, q):
"""A p by q grid of quads on a torus, oriented one way."""
vid = lambda i, j: (i % p) * q + (j % q)
return p * q, [[vid(i, j), vid(i + 1, j), vid(i + 1, j + 1), vid(i, j + 1)] for i in range(p) for j in range(q)]
def rotation(cyc, start):
i = cyc.index(start)
return cyc[i:] + cyc[:i]
class FaceList:
"""The brute force: faces as lists of vertex ids, and every query a scan."""
def __init__(self, n, faces):
self.n = n
self.faces = {f: list(c) for f, c in enumerate(faces)}
def edge_faces(self, u, v):
left = [f for f, c in self.faces.items() if any(c[i] == u and c[(i + 1) % len(c)] == v for i in range(len(c)))]
right = [f for f, c in self.faces.items() if any(c[i] == v and c[(i + 1) % len(c)] == u for i in range(len(c)))]
assert len(left) == 1 and len(right) == 1
return left[0], right[0]
def ring(self, v):
"""The neighbours of v in counterclockwise order: from the edge v -> n
of a face (..., p, v, n, ...), the next edge counterclockwise is v -> p."""
step = {}
for c in self.faces.values():
k = len(c)
for i in range(k):
if c[i] == v:
step[c[(i + 1) % k]] = c[i - 1]
start = next(iter(step))
out = [start]
x = step[start]
while x != start:
out.append(x)
x = step[x]
assert len(out) == len(step)
return out
def split_edge(self, u, v, m):
for f, c in self.faces.items():
k = len(c)
for i in range(k):
if {c[i], c[(i + 1) % k]} == {u, v}:
c.insert(i + 1, m)
break
self.n += 1
def split_face(self, f, u, w, g):
c = rotation(self.faces[f], u)
j = c.index(w)
self.faces[g] = c[: j + 1]
self.faces[f] = [u] + c[j:]
def join_faces(self, u, w):
f, g = self.edge_faces(u, w)
cf = rotation(self.faces[f], w) # w, ..., u
cg = rotation(self.faces[g], u) # u, ..., w
self.faces[f] = cf + cg[1:-1]
del self.faces[g]
return g
def compare(test, we, fl):
we.check()
test.assertEqual(sorted(we.faces()), sorted(fl.faces))
for f, c in fl.faces.items():
got = we.face_vertices(f)
test.assertEqual(rotation(got, c[0]), c)
for v in range(fl.n):
want = fl.ring(v)
got = we.neighbors(v)
test.assertEqual(rotation(got, want[0]), want)
faces = we.vertex_faces(v)
test.assertEqual(len(faces), len(want))
for x, f in zip(we.neighbors(v), faces):
test.assertEqual(fl.edge_faces(v, x)[0], f)
edges = we.edges()
for e in edges:
u, v = we.edge_vertices(e)
test.assertEqual(we.edge_faces(e), fl.edge_faces(u, v))
pairs = {frozenset((c[i], c[(i + 1) % len(c)])) for c in fl.faces.values() for i in range(len(c))}
test.assertEqual(len(pairs), len(edges))
return len(fl.n * [0]) - len(edges) + len(fl.faces)
class WingedEdgeTests(unittest.TestCase):
def test_cube(self):
we = WingedEdge(8, CUBE)
chi = compare(self, we, FaceList(8, CUBE))
self.assertEqual(chi, 2)
e = next(e for e in we.edges() if we.edge_vertices(e) == (0, 3))
self.assertEqual(we.edge_faces(e), (0, 5))
# seen from outside, at the corner (0, 0, 0): +y, then +x, then +z, counterclockwise
self.assertEqual(rotation(we.neighbors(0), 3), [3, 1, 4])
self.assertEqual(rotation(we.face_vertices(0), 0), [0, 3, 2, 1])
def test_octahedron_and_torus(self):
compare(self, WingedEdge(6, OCTAHEDRON), FaceList(6, OCTAHEDRON))
n, faces = torus(4, 5)
chi = compare(self, WingedEdge(n, faces), FaceList(n, faces))
self.assertEqual(chi, 0)
def test_bad_input(self):
with self.assertRaises(WingedEdgeError):
WingedEdge(8, CUBE[:-1]) # open surface
with self.assertRaises(WingedEdgeError):
WingedEdge(8, [CUBE[0][::-1]] + CUBE[1:]) # one face reversed
with self.assertRaises(WingedEdgeError):
WingedEdge(8, CUBE + [[0, 1, 2]]) # an edge on three faces
two_tetrahedra = [[0, 2, 1], [0, 1, 3], [0, 3, 2], [1, 2, 3], [0, 5, 4], [0, 4, 6], [0, 6, 5], [4, 5, 6]]
WingedEdge(4, two_tetrahedra[:4]).check()
with self.assertRaises(WingedEdgeError):
WingedEdge(7, two_tetrahedra) # vertex 0 has two fans
def test_random_updates(self):
rng = random.Random(4171975)
ops = {"split_edge": 0, "split_face": 0, "join_faces": 0}
for start in range(6):
if start % 3 == 0:
n, faces = 8, CUBE
elif start % 3 == 1:
n, faces = 6, OCTAHEDRON
else:
n, faces = torus(3, 4)
we, fl = WingedEdge(n, faces), FaceList(n, faces)
chi0 = compare(self, we, fl)
for step in range(60):
r = rng.random()
if r < 0.35:
e = rng.choice(we.edges())
u, v = we.edge_vertices(e)
m = we.split_edge(e)
fl.split_edge(u, v, m)
ops["split_edge"] += 1
elif r < 0.7:
f = rng.choice(we.faces())
c = fl.faces[f]
if len(c) < 4:
continue
i = rng.randrange(len(c))
j = (i + rng.randrange(2, len(c) - 1)) % len(c)
try:
n_edge, g = we.split_face(f, c[i], c[j])
except WingedEdgeError:
continue # the two vertices already have an edge
fl.split_face(f, c[i], c[j], g)
ops["split_face"] += 1
else:
e = rng.choice(we.edges())
u, w = we.edge_vertices(e)
try:
g = we.join_faces(e)
except WingedEdgeError:
continue
self.assertEqual(fl.join_faces(u, w), g)
ops["join_faces"] += 1
self.assertEqual(compare(self, we, fl), chi0)
self.assertTrue(all(c > 40 for c in ops.values()), ops)
def test_split_face_errors(self):
we = WingedEdge(8, CUBE)
with self.assertRaises(WingedEdgeError):
we.split_face(0, 0, 3) # next to each other
with self.assertRaises(WingedEdgeError):
we.split_face(0, 0, 5) # 5 is not on face 0
if __name__ == "__main__":
unittest.main()
History
Baumgart described the winged-edge polyhedron in a Stanford report of 1972 and at the AFIPS National Computer Conference in 1975, as the representation of his geometric modeling system for computer vision. It was the first boundary structure built on edges, and his Euler primitives made and changed polyhedra one edge and one face at a time. In 1985 Weiler studied which edge-based structures can answer all adjacency queries, and he gave variants with loops for faces with holes and with edge uses. In the same year Guibas and Stolfi published the quad-edge structure, which removes the orientation test with an algebra of directed edges. Mäntylä's book of 1988 compares the winged edge with the half-edge structure that later solid modelers used.
References
- Bruce G. Baumgart, A polyhedron representation for computer vision, Proceedings of the AFIPS National Computer Conference 44, 589 to 596, 1975, the winged-edge polyhedron, its edge, face and vertex nodes, and the traversals around a face and around a vertex
- Kevin Weiler, Edge-based data structures for solid modeling in curved-surface environments, IEEE Computer Graphics and Applications 5(1), 21 to 40, 1985, the winged-edge structure, its sufficiency for the adjacency relations, and the variants with loops and with edge uses
- Martti Mäntylä, An Introduction to Solid Modeling, Computer Science Press, 1988, Chapter 6, Boundary models, Section 6.2, Boundary data structures (p. 102), the winged-edge structure and its comparison with the half-edge structure
- Leonidas Guibas and Jorge Stolfi, Primitives for the manipulation of general subdivisions and the computation of Voronoi diagrams, ACM Transactions on Graphics 4(2), 74 to 123, 1985, the edge algebra and the quad-edge structure, which store one edge record with its two orientations and its dual
Where this leads
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 4Q9BTY Edit this page History Report an error Markdown