Algorithmadvanced
Edgebreaker
Also called Edgebreaker compression.
Rossignac's connectivity compression that visits the triangles of a mesh one by one and writes one of five symbols for each, using at most 2 bits per triangle on a closed genus 0 mesh.
- Time
- O(t^2) decodeO(t) expected encode
- Space
- Θ(t) extra
- Where
- t = the number of triangles
- Model
- Word RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jarek Rossignac, 1999
Edgebreaker compresses the connectivity of a triangle mesh: the list of which vertices form each triangle, without the coordinates. It visits the triangles one by one, each next to one already visited, and writes one of five symbols, C, L, E, R or S, for each. The symbol says where the third vertex of the new triangle lies: a new vertex, or a vertex on the border of the visited part. On a closed mesh with the topology of a sphere, the code with 1 bit for C and 3 bits for the other symbols takes exactly bits for triangles, and the decoder rebuilds the same mesh with its vertices renumbered. Jarek Rossignac published the method in 1999, and it is a standard method of mesh compression.
In plain words
Think of the surface as a ball covered with triangles. Paint one triangle. Then, again and again, paint a triangle next to the painted part, and write one letter that says what its far corner touches.
If the far corner was never painted, write C. If it is the painted corner just to the left or just to the right, write L or R. If the triangle fills the last gap of a hole, write E. If the corner is somewhere else on the edge of the paint, the unpainted part splits in two. Write S, finish one part, and come back for the other.
C is very common, so it gets a short word of one bit, and the other letters get three bits. A reader who gets only the letters can paint the same triangles in the same order, and so rebuild the whole mesh.
The problem
The input is a mesh given as an indexed face set: a list of triangles, each a triple of three different vertex ids, oriented by the right-hand rule so that every directed edge is in exactly one triangle and its reverse in exactly one other. So is closed, every edge has two triangles, and is oriented. We also need to be connected through its edges and to have , that is, genus . The proof shows that these conditions make a triangulated sphere. The goal is a short string from which a decoder can rebuild up to a renumbering of its vertices: the decoder must give the triangles of with each vertex replaced by for one bijection of the vertex ids onto . The vertex coordinates are sent separately, in the order of .
The algorithm
The encoder keeps the triangles it has visited. The rest of the surface, the part not yet visited, is a set of pieces, and each piece is bounded by a closed loop of vertices and edges. The loop runs along the visited triangles in their own direction. One edge of the current loop is the gate . The triangle on the other side of the gate is , and is its tip. The encoder looks up neighbours with a corner table. The five cases:
- C: is new. The loop gets the vertex between and .
- L: is the vertex just before on the loop, so the triangle to the left is visited. The vertex leaves the loop.
- R: is the vertex just after , so the triangle to the right is visited. The vertex leaves the loop.
- E: both; the loop was the triangle and it closes.
- S: is elsewhere on the loop. The loop splits into a right loop and a left loop . The encoder finishes the right loop first and keeps the left one on a stack.
ENCODE(M, f_0)- 1
mark f_0 and its vertices a, b, c; push the triangle across the edge a → b; for each triangle t = (b, a, x) taken from the stack or reached by "go on", with gate a → b, mark t and do: - 2
if x is not marked then write C; mark x; go on across x → b - 3
else if the triangles across a x and across x b are both marked then write E; take the next triangle from the stack - 4
else if the triangle across a x is marked then write L; go on across x → b - 5
else if the triangle across x b is marked then write R; go on across a → x - 6
else write S; push the triangle across a → x; go on across x → b DECODE(symbols)- 7
ℓ_i ← the length of the right loop of each S, from the counts of the symbols up to its E; faces ← (0, 1, 2); loop ← 0 → 1 → 2 → 0; gate ← 0 → 1; then for each symbol s_i, with the gate a → b: - 8
if s_i = C then x ← the next new vertex; insert x between a and b; gate ← x → b - 9
if s_i = L then x ← the vertex before a; remove a from the loop; gate ← x → b - 10
if s_i = R then x ← the vertex after b; remove b from the loop; gate ← a → x - 11
if s_i = E then x ← the vertex before a; the loop a → b → x closes; gate ← the gate taken from the stack (none at the end) - 12
if s_i = S then x ← the vertex ℓ_i − 1 steps after b; split the loop into x → b → … → x and a → x → … → a; gate ← x → b - 13
push the gate a → x - 14
append the face (b, a, x) - 15
return faces
The bits. The code is C = 0, S = 100, R = 101, L = 110, E = 111. It is a prefix code, so the bit string splits back into symbols without separators.
Line L7. The decoder must know where the tip of an S is. The encoder does not send it: the decoder finds it from the symbols that follow. Let a loop have edges. Then C adds one edge, L and R remove one, S makes edges in two loops, and E removes a loop of 3 edges. The right loop of the S at position is finished by the symbols from to the E at which, for the first time, the number of E symbols is one more than the number of S symbols. If these symbols have C, L, R and S, then . The code finds all the ends in one pass with a stack.
Degenerate cases. The encoder rejects a face that repeats a vertex, a directed edge used twice, a boundary edge, , and a mesh that is not connected. The smallest valid input is the pillow: two triangles and on the same three vertices, coded as the single symbol E.
Example
Take the octahedron with the faces , , , , , , , , so and . Start at . The encoder writes CCRCRRE and meets the vertices in the order , so maps them to . The decoder sees only the symbols:
| step | symbol | gate | tip | face | loop after |
|---|---|---|---|---|---|
| L7 | |||||
| 1 | C | new 3 | |||
| 2 | C | new 4 | |||
| 3 | R | 2, after 1 | |||
| 4 | C | new 5 | |||
| 5 | R | 0, after 2 | |||
| 6 | R | 3, after 0 | |||
| 7 | E | 4, before 5 | closed |
The eight faces are the input faces in the encoder's order, with each vertex renamed by : for example becomes and becomes . The bit string is 0 0 101 0 101 101 111, which is bits. Every one of the 8 start faces gives the same string CCRCRRE.
An S needs a less regular mesh. The tests make random edge flips on an octahedron, an icosahedron and a subdivided octahedron, and these meshes use all five symbols. On the icosahedron split twice into four and then changed by 200 random flips (seed 0, start face 0), the encoder writes 25 S symbols, and the longest right loop that line L7 finds has 28 edges.
Correctness
The proof in proofs/correctness.md shows four facts for every valid input.
- A valid input is a triangulated sphere. If the mesh is closed, oriented, connected through its edges and has , then no vertex is pinched and the genus is 0.
- Key invariant. Before each step, every unvisited piece is a closed disk bounded by its loop, the loops are simple, and the triangles outside each disk next to its loop are visited. So the five cases are exactly the five places where the tip can be, and the encoder never reaches a visited triangle again.
- The rule of line L7 gives the length of each right loop. With it, after each symbol the decoder has the same loops, gates and stack as the encoder, with each vertex renamed by . So decoding inverts encoding: DECODE(ENCODE()) is renamed by , face by face in the encoder's order.
- Bit bound. There are exactly C symbols and symbols in all, and . So the code has exactly bits.
Fact 1 and the disk facts in fact 2 use the Jordan and Schoenflies theorems, which the proof cites. The rest is proved.
Proof: Edgebreaker decoding inverts encoding on every triangulated sphere, and the code takes exactly 2t - 1 bitsfull
Setting. is a list of triangles, each a triple of three different vertex ids, such that every directed edge is in exactly one triangle and in exactly one other, the triangles are connected through shared edges, and . An edge is a pair of vertices, so each edge has exactly two triangles. ENCODE and DECODE are lines L1 to L15 of the page. For a triangle reached across the gate , the left triangle is the other triangle of the edge and the right triangle is the other triangle of the edge . A vertex is marked once line L1 or L2 marks it; every marked vertex is a vertex of a visited triangle.
Claim.
- is a triangulated sphere: the triangles at each vertex form one cycle around it, and is a closed orientable surface of genus 0.
- ENCODE terminates, visits every triangle exactly once, and before each step the invariant below holds.
- Let number the vertices in the order in which the encoder marks them. Then DECODE(ENCODE()) is the list of the triangles of in the order of their visit, with each vertex replaced by .
- The symbol string has exactly symbols, of which are C, and . The code C = 0, S = 100, R = 101, L = 110, E = 111 has exactly bits.
Facts cited. (F1) Every closed connected orientable surface has for its genus , and means a sphere (the classification of surfaces). (F2) The closure of the complement of an open disk bounded by a polygonal simple closed curve on the sphere is a closed disk (the Schoenflies theorem). (F3) If is a closed disk made of triangles and is a path of edges from a point of to another point of whose edges and inner vertices are not on , then cuts into two closed disks; the boundary of each is followed by one of the two arcs of between the ends of , and every triangle of is in exactly one of them (the theta-curve theorem, a form of the Jordan curve theorem). A closed disk made of triangles is connected through edges, and a disk whose boundary is the boundary of one of its triangles is that triangle.
Proof of 1. At a vertex , join two triangles of when they share an edge at . Each edge has exactly two triangles, so this graph has degree 2 everywhere and is a union of cycles, the fans of . Replace each vertex by copies, one for each fan. The result is a closed surface: every vertex now has one fan, so it has a disk around it. is connected through edges as is, and it is oriented by the same triangles. It has the same edges and triangles and more vertices, so . By (F1) , so every , and .
The invariant. The code does not store loops; they are defined here for the proof. A piece is a set of unvisited triangles with a loop , a cyclic sequence of vertices, such that:
- (I1) the union of the triangles of is a closed disk whose boundary is the closed path , and passes each vertex at most once;
- (I2) an edge of a triangle of is an edge of exactly when its other triangle is not in , and then that other triangle is visited and contains the edge in the direction of ;
- (I3) the gate of the piece is an edge of , and the triangle across it, which contains , is in .
Before each step, the unvisited triangles are split into the pieces of the current gate and of the gates on the stack, one piece for each, with no triangle in two pieces. (For the code, "the stack" holds the triangle across each stored gate; the current gate is the one across which the next triangle is reached.)
Lemma A. In a piece with loop : a vertex on is marked, and a vertex of a triangle of that is not on is not marked.
Proof. A vertex on is on an edge of , which is in a visited triangle by (I2); the vertices of a visited triangle are marked (line L1 marks those of , and a later triangle is visited across a gate whose two ends are on a loop, so marked, while its tip is marked at line L2 or was marked before). Now let be a vertex of a triangle of that is not on . No edge at is an edge of , so by (I2) every edge at that has one triangle in has both in . Going around the single fan of (claim 1), all triangles of are in , so none is visited and is not marked.
Lemma B. For the triangle across the gate of a piece with loop : the left triangle is visited exactly when is the vertex just before on , and the right triangle is visited exactly when is the vertex just after .
Proof. If the left triangle is visited, it is not in , so by (I2) the edge is an edge of in the direction it has in the left triangle. That triangle has , because has . So is an edge of and comes just before . Conversely, if is an edge of , then by (I2) the other triangle of , which is the left triangle, is visited. The right side is the same with replaced by .
Proof of 2. Start. By claim 1 and (F2), the triangles other than form a closed disk with boundary , the directions of . With the gate this is one piece: (I1) holds, the other triangle of each edge of is not and so is in , and (I3) holds because the triangle across contains .
Step. Let be the current piece with loop , gate and tip triangle (I3), so is not visited and the check of the code never fires. The encoder marks . Write . There are five cases, and they are the five branches of lines L2 to L6.
- x not marked (C). By Lemma A, is not on , so the edges and are not on and the path satisfies (F3). It cuts into (the side bounded by ) and with loop . The other triangle of is in by (I2), so in , and the new gate satisfies (I3). (I2) holds on the two new loop edges, because is visited and has , .
- x marked, left and right visited (E). By Lemma B, is just before and just after , so and every edge of is on . is connected through edges, and by (I2) no triangle of shares an edge with , so , and the piece is finished.
- x marked, only the left visited (L). By Lemma B, and is not just after , so is not on . The single edge satisfies (F3) and cuts into and with loop ; the vertex leaves the loop. The gate satisfies (I3) as in case C.
- x marked, only the right visited (R). Symmetric: , the edge cuts off , leaves the loop, and the new gate is .
- x marked, neither visited (S). By Lemma A, is on , so for some , and by Lemma B, and . Neither nor is on , by (I2). By (F3) the edge cuts into with loop and a disk with loop , and the edge cuts that disk into and with loop . Each loop passes each vertex once, since does. The other triangles of and are in and , so the gates (pushed) and (current) satisfy (I3).
In all cases the other pieces are not changed, so the invariant holds again. Each step visits one triangle that was not visited, so ENCODE stops after at most steps. It stops only after an E with an empty stack, when there are no pieces left; then every triangle is visited, and the check "not connected" does not fire.
Proof of 3. The lengths of line L7. Consider the S at position , with right piece and loop of edges. The stack is last in, first out, so the steps that follow visit exactly the triangles of and of the pieces cut from it, and step is the E that finishes the last of them. Count the pieces cut from that are not finished: 1 at the start, plus 1 for each S and minus 1 for each E, so is the first position after where the E symbols are one more than the S symbols. Count also the edges on their loops: from the proof of 2, a C adds 1, an L or R removes 1, an S turns a loop of edges into loops with edges in all, and an E removes a loop of 3 edges. The count goes from to 0, so with , that is , the rule of line L7. The code finds each in one pass: with the number of E minus the number of S so far, the S at sets to some value and waits for ; an S nested inside waits for a smaller value, so the waiting S with the smallest target is always on top of the stack.
Lock step. We show by induction on the number of symbols read that the decoder's loops, current gate, stacked gates and faces are those of the encoder renamed by , and that the next new vertex number is the number of marked vertices. At the start both have the loop , the gate and the face . In a step, the decoder reads the symbol the encoder wrote for the triangle across the same gate, and it computes the same new loops as the proof of 2: for C a new vertex, which is since is the next vertex marked; for L the vertex before ; for R the vertex after ; for E the remaining vertex. For S, the right loop is with edges, so is steps after on , which line L12 finds, and since passes each vertex once the vertex is unique. In each case line L14 appends . Both pop gates in the same order, so the decoder stops after the last symbol, with every triangle of renamed by , in the order of the visit.
Proof of 4. One symbol is written for each triangle other than , so there are . Each C marks one vertex, the other symbols mark none, and by claim 2 every vertex is in a visited triangle, so it is marked; marks 3, so . The number of pieces goes from 1 to 0, up by 1 at each S and down by 1 at each E, so . Each triangle has 3 edges and each edge 2 triangles, so , and gives . The code has bits. It is a prefix code, so the bit string splits back into the same symbols.
Claims 1 to 4 give what the page states: on every closed, oriented, edge-connected triangle mesh with , ENCODE stops, DECODE(ENCODE()) equals up to the renumbering of the vertices, and the code has exactly bits.
Complexity
The encoder builds the corner table with a hash table on the directed edges in expected time and then does a constant amount of work for each triangle, so it takes expected time. The decoder of this page does a constant amount of work for each symbol, plus the walk of line L12, which takes steps for each S. A loop with edges bounds a disk of at least triangles, so a right loop has at most edges, and the walks take each and in all. This is the bound we prove; we did not build a mesh that reaches it. Both use space.
Measured on the code of this page (one run each, start face 0; ico is the icosahedron split times into four, and the last mesh is ico2 after 200 random edge flips with seed 0):
| mesh | C | L | R | S | E | bits per triangle | entropy per triangle | |
|---|---|---|---|---|---|---|---|---|
| icosahedron | 20 | 9 | 0 | 9 | 0 | 1 | 1.950 | 1.183 |
| ico1 | 80 | 39 | 1 | 36 | 1 | 2 | 1.988 | 1.297 |
| ico2 | 320 | 159 | 1 | 156 | 1 | 2 | 1.997 | 1.100 |
| ico3 | 1280 | 639 | 1 | 636 | 1 | 2 | 1.999 | 1.031 |
| ico4 | 5120 | 2559 | 1 | 2556 | 1 | 2 | 2.000 | 1.009 |
| ico2, flipped | 320 | 159 | 17 | 92 | 25 | 26 | 1.997 | 1.820 |
The bits per triangle are , as proved. The last column is the order-0 Shannon entropy of the symbol string divided by , which is about what an ideal arithmetic coder with fixed symbol frequencies would need, not counting the frequencies themselves. On the regular subdivided meshes the string is almost only C and R in turn, the traversal goes round in a spiral, and the entropy falls to about 1 bit per triangle. After random flips it is 1.82.
Properties
- Proved. Decoding inverts encoding for every closed connected oriented triangle mesh with , from every start face.
- Proved. The code takes exactly bits, so at most 2 bits per triangle, and exactly symbols are C.
- Proved. The numbers of S and E symbols satisfy .
- Measured. The tests check DECODE(ENCODE()) from every start face of 17 meshes with up to 80 triangles (the pillow, the tetrahedron, octahedron and icosahedron, their subdivisions, 4 bipyramids, and 6 meshes made by random edge flips with seed 7), and from random starts after random renumbering (seed 11).
- Proved. Each triangle except the first is reached across its gate from a triangle visited before it, so the gates form a spanning tree of the triangles, in which two triangles are joined when they share an edge.
- Lossless. The connectivity comes back exactly; only the vertex numbering changes, and is the order in which the coordinates are sent.
- Connectivity only. The method says nothing about the coordinates. No geometric predicate is used.
Variants and improvements
- Entropy coding. The symbols are far from equally likely, so a Huffman code of symbol pairs or an arithmetic code does better than the fixed 1 and 3 bit code. Rossignac reports less than 1.5 bits per triangle in this way on large meshes. This is measured on his meshes, not a bound.
- A better worst case. King and Rossignac (1999) gave a code with at most bits per vertex, about bits per triangle. By Tutte's count of planar triangulations, about bits per vertex are needed in the worst case.
- Linear time decoders. The Wrap and Zip decoder of Rossignac and Szymczak (1999) puts the S tips in place afterwards by zipping the loops, and the Spirale Reversi decoder of Isenburg and Snoeyink (2000) reads the symbols backwards; both take time.
- Edgebreaker on a corner table. Rossignac, Safonova and Szymczak (2001) wrote both coders in a few lines on the arrays of a corner table.
- Holes and handles. Rossignac's paper also handles meshes with boundaries and meshes of higher genus, with extra bits for each hole and each handle: at a handle an S can hit a loop that is still on the stack and needs extra information. Another way to treat a hole, used by Touma and Gotsman, is to fill it with one extra vertex. The code of this page rejects these meshes.
- Valence coding. Touma and Gotsman (1998) code the degree of each vertex instead of one symbol per triangle; on regular meshes this takes much less than 1 bit per triangle.
- Progressive coding. A progressive mesh sends a coarse mesh first and then vertex splits, which Edgebreaker cannot do: its order is fixed by the traversal.
When to use it
Use Edgebreaker to store or send the connectivity of a large triangle mesh in about 2 bits per triangle, or less with entropy coding, instead of the bits per triangle of an indexed face set. It needs a manifold mesh; a mesh with non-manifold edges or vertices must be cut into manifold pieces first. The whole string must arrive before the mesh can be used. For streaming at several levels of detail, use a progressive mesh. For a guarantee below 2 bits per triangle, use a coder with a better worst case.
Pitfalls
- The wrong side first. After an S the encoder must finish the right loop before the left one, and the decoder must assume the same. If the order or the side of "go on" in lines L2, L4 and L5 differs between the two, the lengths of line L7 are wrong and the decoder silently builds a different mesh.
- Orientation. The cases L and R are told apart by the orientation of the triangles. An input that is not oriented by one rule, for example with one face reversed, makes a directed edge appear twice; the encoder must reject it, and it can be fixed by consistent mesh orientation.
- Duplicate vertices. A mesh whose shared vertices were stored twice, once per triangle, has boundaries everywhere and is rejected. Run vertex welding first.
- Testing only the Euler characteristic. alone is not enough. Two octahedra glued at two vertices also have , but they are not connected through edges, and the encoder must reject them. The tests include this case.
- Visiting a triangle twice. On a valid input the encoder never reaches a visited triangle; on a bad input it can, and without a check it may loop. The code of this page raises an error there.
- Comparing with the input numbering. The decoder numbers the vertices in the order of first visit. A test must rename the input by before it compares faces.
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/edgebreaker/. The authors are listed in prov/5F4MY3.jsonl.
"""Edgebreaker connectivity compression for closed triangle meshes of genus 0 (after Rossignac 1999).
A mesh is a list of faces, each a tuple of three vertex ids, oriented by the
right-hand rule. The encoder walks the triangles from a first triangle and
writes one symbol for each other triangle:
C the tip vertex is new;
L the tip is the vertex just before the gate on the boundary loop;
R the tip is the vertex just after the gate;
E both: the triangle closes the loop;
S the tip is elsewhere on the loop, which splits in two.
The decoder rebuilds the faces, with the vertices numbered in the order in
which the encoder met them. The code C = 0, S = 100, R = 101, L = 110,
E = 111 gives exactly 2T - 1 bits for T triangles on a closed genus 0 mesh.
"""
CODE = {"C": "0", "S": "100", "R": "101", "L": "110", "E": "111"}
DECODE = {v: k for k, v in CODE.items()}
def nxt(c):
return c - c % 3 + (c + 1) % 3
def prv(c):
return c - c % 3 + (c + 2) % 3
def corner_table(faces):
"""The corner table: V[c] is the vertex of corner c, O[c] the opposite corner (or -1)."""
v = [x for tri in faces for x in tri]
facing = {}
for c in range(len(v)):
e = (v[nxt(c)], v[prv(c)])
if e in facing:
raise ValueError("directed edge %r used twice" % (e,))
facing[e] = c
o = [facing.get((v[prv(c)], v[nxt(c)]), -1) for c in range(len(v))]
return v, o
def encode(faces, start=0):
"""(symbols, vertex order, triangle order) for a closed connected genus 0 mesh, starting at face start."""
if any(len(set(tri)) != 3 for tri in faces):
raise ValueError("a face repeats a vertex")
v, o = corner_table(faces)
t = len(faces)
if -1 in o:
raise ValueError("the mesh has a boundary")
nverts = len({x for tri in faces for x in tri})
if nverts - 3 * t // 2 + t != 2:
raise ValueError("V - E + F is not 2: the mesh is not a sphere")
seen_v, seen_t = set(), [False] * t
c0 = 3 * start
order = [v[c0], v[c0 + 1], v[c0 + 2]] # @line L1
seen_v.update(order)
seen_t[start] = True
tri_order = [start]
symbols = []
stack = [o[c0 + 2]] # the triangle across the edge from v[c0] to v[c0 + 1]
while stack:
c = stack.pop()
while True:
# c is the corner at the tip x of the new triangle (b, a, x); the gate is a -> b.
if seen_t[c // 3]:
raise ValueError("the mesh is not a manifold sphere") # never on a valid input
seen_t[c // 3] = True
tri_order.append(c // 3)
left = seen_t[o[nxt(c)] // 3] # the triangle across the edge a x
right = seen_t[o[prv(c)] // 3] # the triangle across the edge x b
if v[c] not in seen_v: # @line L2
symbols.append("C")
seen_v.add(v[c])
order.append(v[c])
c = o[prv(c)]
elif left and right: # @line L3
symbols.append("E")
break
elif left: # @line L4
symbols.append("L")
c = o[prv(c)]
elif right: # @line L5
symbols.append("R")
c = o[nxt(c)]
else: # @line L6
symbols.append("S")
stack.append(o[nxt(c)])
c = o[prv(c)]
if not all(seen_t):
raise ValueError("the mesh is not connected")
return "".join(symbols), order, tri_order
def right_loop_lengths(symbols):
"""For each S at position i, the length of the loop of its right branch (symbols i+1 to its E)."""
count = {s: [0] for s in "CLRSE"}
for s in symbols:
for k in count:
count[k].append(count[k][-1] + (s == k))
# Let D(j) = #E - #S in symbols[0..j]. The right branch of the S at i ends at the
# first E at j > i with D(j) = D(i) + 1. Nested S symbols have smaller targets, so
# the open S with the smallest target is on top of the stack.
out = {}
stack = [] # (target, i) for each S whose right branch is open
d = 0
for j, s in enumerate(symbols):
if s == "S":
d -= 1
stack.append((d + 1, j))
elif s == "E":
d += 1
if stack and stack[-1][0] == d:
i = stack.pop()[1]
n = {k: count[k][j + 1] - count[k][i + 1] for k in count}
out[i] = 3 + 2 * n["S"] - n["C"] + n["L"] + n["R"]
if d != 1 or stack:
raise ValueError("the numbers of S and E symbols do not match")
return out
def decode(symbols):
"""The faces, with vertex ids 0, 1, 2, ... in the order of the encoder, in the encoder's triangle order."""
lengths = right_loop_lengths(symbols) # @line L7
faces = [(0, 1, 2)]
vert = [0, 1, 2] # loop nodes: their vertex, next and previous node
nx = [1, 2, 0]
pv = [2, 0, 1]
nverts = 3
gate = 0 # the gate is the loop edge from node gate to node nx[gate]
stack = []
for i, s in enumerate(symbols):
if gate is None:
raise ValueError("symbols after the last loop was closed")
g, h = gate, nx[gate]
a, b = vert[g], vert[h]
if s == "C": # @line L8
x = nverts
nverts += 1
vert.append(x)
nx.append(h)
pv.append(g)
nx[g] = pv[h] = len(vert) - 1
gate = len(vert) - 1
elif s == "L": # @line L9
p = pv[g]
x = vert[p]
nx[p], pv[h] = h, p
gate = p
elif s == "R": # @line L10
q = nx[h]
x = vert[q]
nx[g], pv[q] = q, g
elif s == "E": # @line L11
x = vert[pv[g]]
if nx[h] != pv[g]:
raise ValueError("E on a loop that is not a triangle")
gate = stack.pop() if stack else None
elif s == "S": # @line L12
k = h
for _ in range(lengths[i] - 1):
k = nx[k]
x = vert[k]
# Right loop: a new node for x, then h ... pv[k]. Left loop: g, k, ...
vert.append(x)
nx.append(h)
pv.append(pv[k])
nx[pv[k]] = len(vert) - 1
pv[h] = len(vert) - 1
nx[g], pv[k] = k, g
stack.append(g) # @line L13
gate = len(vert) - 1
else:
raise ValueError("unknown symbol %r" % (s,))
faces.append((b, a, x)) # @line L14
if gate is not None:
raise ValueError("the symbols end before every loop is closed")
return faces # @line L15
def to_bits(symbols):
return "".join(CODE[s] for s in symbols)
def from_bits(bits):
out, word = [], ""
for ch in bits:
word += ch
if word in DECODE:
out.append(DECODE[word])
word = ""
if word:
raise ValueError("trailing bits")
return "".join(out)
test_edgebreaker.py 202 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/edgebreaker/. The authors are listed in prov/5F4MY3.jsonl.
import random
import pytest
from edgebreaker import decode, encode, from_bits, right_loop_lengths, to_bits
TET = [(0, 2, 1), (0, 1, 3), (1, 2, 3), (2, 0, 3)]
OCTA = [(0, 2, 4), (2, 1, 4), (1, 3, 4), (3, 0, 4), (2, 0, 5), (1, 2, 5), (3, 1, 5), (0, 3, 5)]
ICO = [(0, 11, 5), (0, 5, 1), (0, 1, 7), (0, 7, 10), (0, 10, 11), (1, 5, 9), (5, 11, 4),
(11, 10, 2), (10, 7, 6), (7, 1, 8), (3, 9, 4), (3, 4, 2), (3, 2, 6), (3, 6, 8),
(3, 8, 9), (4, 9, 5), (2, 4, 11), (6, 2, 10), (8, 6, 7), (9, 8, 1)]
def bipyramid(n):
"""n side vertices 0..n-1, apex n and n+1."""
faces = []
for i in range(n):
j = (i + 1) % n
faces.append((i, j, n))
faces.append((j, i, n + 1))
return faces
def subdivide(faces):
"""Split each triangle into four."""
nv = 1 + max(x for t in faces for x in t)
mid = {}
def m(a, b):
nonlocal nv
key = (min(a, b), max(a, b))
if key not in mid:
mid[key] = nv
nv += 1
return mid[key]
out = []
for a, b, c in faces:
ab, bc, ca = m(a, b), m(b, c), m(c, a)
out += [(a, ab, ca), (ab, b, bc), (ca, bc, c), (ab, bc, ca)]
return out
def random_flips(faces, k, rng):
"""k random edge flips that keep the mesh simplicial (no double edge, every degree at least 3)."""
faces = [list(t) for t in faces]
done = 0
for _ in range(50 * k):
if done == k:
break
where = {}
nbr = {}
for f, t in enumerate(faces):
for i in range(3):
where[(t[i], t[(i + 1) % 3])] = (f, t[(i + 2) % 3])
nbr.setdefault(t[i], set()).add(t[(i + 1) % 3])
a, b = rng.choice(sorted(where))
f, c = where[(a, b)]
g, d = where[(b, a)]
if d in nbr[c] or len(nbr[a]) <= 3 or len(nbr[b]) <= 3:
continue
faces[f] = [c, a, d]
faces[g] = [d, b, c]
done += 1
return [tuple(t) for t in faces]
def canon(t):
k = t.index(min(t))
return t[k:] + t[:k]
def relabel(faces, rng):
"""The same mesh with random vertex ids, a random face order and random rotations of each face."""
ids = sorted({x for t in faces for x in t})
new = list(range(100, 100 + len(ids)))
rng.shuffle(new)
lab = dict(zip(ids, new))
out = []
for t in faces:
r = rng.randrange(3)
t = tuple(lab[x] for x in t)
out.append(t[r:] + t[:r])
rng.shuffle(out)
return out
def meshes():
rng = random.Random(7)
out = [("pillow", [(0, 1, 2), (0, 2, 1)]), ("tet", TET), ("octa", OCTA), ("ico", ICO), ("tet1", subdivide(TET)),
("octa1", subdivide(OCTA)), ("ico1", subdivide(ICO))]
out += [("bipyramid%d" % n, bipyramid(n)) for n in (3, 4, 5, 9)]
for i in range(6):
base = [OCTA, ICO, subdivide(OCTA)][i % 3]
out.append(("flipped%d" % i, random_flips(base, 10 + 15 * i, rng)))
return out
def check_round_trip(faces, start):
symbols, order, tri_order = encode(faces, start)
got = decode(symbols)
index = {v: i for i, v in enumerate(order)}
assert sorted(order) == sorted({x for t in faces for x in t})
# Same mesh up to vertex order: the relabelled input is exactly the decoded list, face by face.
want = [tuple(index[x] for x in faces[f]) for f in tri_order]
assert [canon(t) for t in got] == [canon(t) for t in want]
assert sorted(tri_order) == list(range(len(faces)))
return symbols
def test_decode_inverts_encode_from_every_start():
for name, faces in meshes():
for start in range(len(faces)):
check_round_trip(faces, start)
def test_round_trip_after_random_relabelling():
rng = random.Random(11)
for name, faces in meshes():
for _ in range(5):
g = relabel(faces, rng)
check_round_trip(g, rng.randrange(len(g)))
def test_counts_and_bit_bound():
for name, faces in meshes():
t = len(faces)
v = len({x for f in faces for x in f})
assert v - 3 * t // 2 + t == 2
for start in range(len(faces)):
symbols, _, _ = encode(faces, start)
assert len(symbols) == t - 1
assert symbols.count("C") == v - 3
assert symbols.count("E") == symbols.count("S") + 1
bits = to_bits(symbols)
assert len(bits) == 2 * t - 1
assert from_bits(bits) == symbols
def test_all_five_symbols_occur():
seen = set()
for name, faces in meshes():
for start in range(len(faces)):
seen |= set(encode(faces, start)[0])
assert seen == set("CLRSE")
def slow_lengths(symbols):
"""Brute force: for each S, scan forward until its right branch has one more E than S."""
out = {}
for i, s in enumerate(symbols):
if s != "S":
continue
bal, j = 1, i
while bal:
j += 1
bal += {"S": 1, "E": -1}.get(symbols[j], 0)
part = symbols[i + 1:j + 1]
# Each C adds one edge to the loop, L and R remove one, S adds one, E removes three.
size = 0
for x in reversed(part):
size += {"C": -1, "L": 1, "R": 1, "S": -1, "E": 3}[x]
out[i] = size
return out
def test_loop_lengths_match_a_slow_scan():
for name, faces in meshes():
for start in range(0, len(faces), 3):
symbols, order, tri_order = encode(faces, start)
lengths = right_loop_lengths(symbols)
assert lengths == slow_lengths(symbols)
assert sorted(lengths) == [i for i, s in enumerate(symbols) if s == "S"]
assert all(n >= 3 for n in lengths.values())
def test_rejects_meshes_that_are_not_spheres():
with pytest.raises(ValueError):
encode(TET[:3]) # a disk with a boundary
torus = []
m, n = 3, 4
for i in range(m):
for j in range(n):
a, b = i * n + j, i * n + (j + 1) % n
c, d = ((i + 1) % m) * n + j, ((i + 1) % m) * n + (j + 1) % n
torus += [(a, b, d), (a, d, c)]
with pytest.raises(ValueError):
encode(torus)
# Two octahedra glued at two opposite vertices: V - E + F = 10 - 24 + 16 = 2, but not a sphere.
other = {0: 0, 1: 1, 2: 6, 3: 7, 4: 8, 5: 9}
pinched = OCTA + [tuple(other[x] for x in f) for f in OCTA]
with pytest.raises(ValueError):
encode(pinched)
with pytest.raises(ValueError):
encode([(0, 0, 1)] + TET)
with pytest.raises(ValueError):
decode("CCE") # too short for its loops
with pytest.raises(ValueError):
decode("CRSE") # an S without the E of its second loop
History
Jarek Rossignac introduced Edgebreaker in 1999, in IEEE Transactions on Visualization and Computer Graphics, one year after the valence-based coder of Touma and Gotsman. His paper gave the five CLERS symbols, the stack for S and the bound of 2 bits per triangle for meshes with the topology of a sphere. Later papers made the decoder run in linear time, lowered the guaranteed bound, and gave a short implementation on a corner table. Edgebreaker and its variants became a standard part of the compression of 3D triangle meshes.
References
- Jarek Rossignac, Edgebreaker, connectivity compression for triangle meshes, IEEE Transactions on Visualization and Computer Graphics 5(1), pages 47-61, 1999, the five symbols C, L, E, R and S, the traversal with a stack for S, the code with 1 bit for C and 3 bits for the other symbols, the 2t bit bound for meshes with the topology of a sphere, and the measured rates with entropy coding
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 5F4MY3 Edit this page History Report an error Markdown