Algorithmcore
Isotropic remeshing
Also called incremental remeshing, Botsch-Kobbelt remeshing.
Makes a mesh with nearly equal edges and good angles by repeating edge splits, collapses, flips toward valence six and tangential smoothing.
- Time
- O(k n² log n) worst
- Space
- Θ(n) extra
- Where
- k = the number of rounds; n = the largest number of vertices during the run
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Mario Botsch, Leif Kobbelt, 2004
Isotropic remeshing turns a triangle mesh with triangles of all sizes and shapes into one whose edges are all close to a target length and whose triangles are close to equilateral, while the surface stays the same up to a small error. It repeats a short loop of four local steps. It splits every edge longer than and collapses every edge shorter than . It flips edges so that the valences move toward 6. Then it moves each vertex toward the centroid of its neighbours, inside its tangent plane, and projects it back onto the input surface. Each step only changes a few triangles at a time, so the method is simple to write on a half-edge structure, and a few rounds are enough.
In plain words
A scanned or converted mesh often has long thin triangles next to tiny ones. Many later steps, such as smoothing, simulation or computing distances, work badly on such triangles. Remeshing replaces them by triangles of one size and a nice shape, on the same surface.
The method keeps a goal length in mind and repeats four simple fixes. If an edge is too long, cut it in the middle. If an edge is too short, shrink it to a point, which merges its two ends. If a corner has too many or too few edges around it, turn an edge in a four-sided patch the other way, so that the corners move toward six edges each. Finally, nudge every corner toward the middle of its neighbours, but only along the surface, and put it back on the surface. After a few rounds, all edges are about the goal length.
The problem
The input is a manifold triangle mesh, a target edge length , a number of rounds , and optionally a projection onto a reference surface, usually the input mesh itself. The output is a manifold triangle mesh with the same topology, the same border curve, edge lengths mostly in , angles near and valences near 6 (4 on the border). This is a quality goal, not an optimization with a unique answer. The page proves what each step keeps and measures the final quality.
The algorithm
The valence excess of a set of vertices is with for an inner vertex and for a border vertex.
ISOTROPIC-REMESH(mesh, L, k, project)- 1
for r ← 1 to k do - 2
while the longest edge uv has |uv| > 4L/3 do split uv at its midpoint - 3
for each edge uv with |uv| < 4L/5 do collapse uv to its midpoint if it is safe - 4
while some inner edge uv has a legal flip that lowers the valence excess of its four vertices do flip uv - 5
for each inner vertex v do x_v ← project(x_v + (I − n_v n_vᵀ)(c_v − x_v)) - 6
return the mesh
Split (line L2). The edge with faces and gets a new vertex at its midpoint, and the faces become , , , . A border edge has one face and gets two. The code always splits the longest edge, from a priority queue.
Collapse (line L3). Vertex is merged into at the midpoint, and the two faces of vanish. The code allows it only if the collapse is safe. Neither nor may be a border vertex. The link condition must hold: the common neighbours of and are exactly and . Both and must have valence at least 4. No edge at the new vertex may be longer than . No remaining face may turn its normal by or more.
Flip (line L4). The faces and become and , as in an edge flip. A flip is legal if is not a border edge, is not already an edge, and have valence at least 4, and neither new face folds over the old pair. It is made only if it lowers the valence excess of , where lose one edge and gain one.
Relaxation (line L5). is the centroid of the neighbours of and the unit normal, the normalized sum of the face normals. The move is the tangential part of the Laplacian smoothing step with factor 1, so the vertices spread evenly without shrinking the shape, and the projection puts them back on the surface.
Example
The split phase on a square. Take the unit square as two triangles, cut by the diagonal from to , with , so the split threshold is . The longest edge is the diagonal, . Splitting it at gives four triangles, with four sides of length 1 and four half-diagonals of length . The sides are now the longest. Each is split at its midpoint, which adds a spoke of length to the center. Then the half-diagonals, , are the longest, and each is split, for example at , with new edges of length . After these 9 splits the mesh has 13 vertices and 16 faces, and every edge has length or . The tests check these counts.
A noisy sphere. Take the icosphere with 162 vertices, move each vertex by up to in each coordinate and put it back on the unit sphere. Then remesh with , half the input edge length, for 5 rounds, with projection onto the sphere. The measured result has 619 vertices, a mean edge length of , percent of the edges in , 563 of the 619 vertices of valence 6, and a smallest angle of , against in the noisy input at twice the edge length. The Euler characteristic stays 2.
A rectangle of thin triangles. An rectangle cut into 32 triangles of size has a smallest angle of . Five rounds with give 164 vertices, 102 of the 116 inner vertices of valence 6, and a measured smallest angle of . The area stays exactly , the corners stay, and every border edge lies on a side of the rectangle.
Correctness
These are proved in the correctness file:
- The split loop stops, and then every edge is at most . The loop splits the longest edge, which is the longest edge of both its faces, so every split is a longest-side bisection. By the theorem of Rosenberg and Stenger, every triangle made in this way has all its angles at least half the smallest angle of the input. So a triangle with an edge longer than has area at least a fixed amount, and a counting argument bounds the number of splits.
- Splits keep the surface. A midpoint lies on the old edge, so the new faces cover exactly the old ones, with the same area.
- The collapse loop stops and keeps the bound. Each collapse removes a vertex. The guard keeps every edge at most .
- The flip loop stops at a local optimum. Each flip lowers the integer valence excess of the whole mesh by at least 1. When it stops, no legal flip lowers the excess, which the tests check by a scan of all edges.
- The mesh stays a manifold with the same topology. Splits and flips keep a manifold with the same Euler characteristic. A collapse under the link condition, away from the border, also keeps the manifold and the Euler characteristic. The tests recompute the topology from scratch after random operations.
- The border stays. No border vertex moves, no border edge is collapsed or flipped, and a split of a border edge puts the new vertex on that edge.
The upper bound holds after line L3, but flips and relaxation can create longer edges. Edges shorter than can remain where a collapse is not safe. So the final length distribution, the angles and the valences are only measured, as in the examples.
Proof: Each phase of isotropic remeshing stops, the split phase leaves every edge at most 4L/3, the collapse guard keeps this bound, the flip phase ends at a local optimum of the valence excess, and the mesh keeps its topology and borderfull
Setup. The input is an oriented manifold triangle mesh, possibly with border, in which every face has positive area. is the target length, and . A vertex is a border vertex if it lies on a border edge, an edge with only one face. The valence is the number of neighbours of , and the valence excess is with on the border and inside. The claims are about the combinatorics of the operators and the exact geometry of the midpoints. The floating-point length tests only decide which operator runs, and do not change the arguments.
Lemma 1 (a split keeps the surface and the topology). Splitting the edge at its midpoint gives a manifold mesh with the same oriented surface, the same border curve and the same Euler characteristic.
Proof. Each face that contains the directed edge , with , is replaced by and . Since lies on the segment , these two triangles lie in the plane of the old one, keep its orientation, and cover it with no overlap, so the surface and the area do not change. Every other face is untouched. The star of is a disk (two faces from each old face, joined along ), or a half-disk if was a border edge, and the stars of , and the opposite vertices only replace one edge by another. For an inner edge, grows by 1, by 3 (the halves , and two spokes) and by 2. For a border edge, grows by 1, by 2 and by 1. In both cases is the same. The border curve is the same point set, because a border edge becomes the border edges and .
Lemma 2 (longest-first splits are longest-side bisections). In line L2, every split cuts each of its one or two faces through a longest side of that face.
Proof. The heap holds every edge longer than , with stale entries skipped, and a split pushes every new edge longer than . So the popped edge is a longest edge of the whole mesh, and so a longest side of each face that contains it.
Theorem 1 (the split phase stops and bounds the edges). Line L2 makes finitely many splits, and when it stops every edge has length at most .
Proof. Let be the smallest angle of the mesh when line L2 starts, and . Every face made in line L2 comes from a face of the starting mesh by repeated bisection through a longest side (Lemma 2). By the theorem of Rosenberg and Stenger, every triangle made in this way from has all its angles at least half the smallest angle of , so at least . Their argument allows either side when two sides are equally long.
Take a face that is split. Its longest side has length . Let be the angles at the ends of that side and the height of the opposite vertex above it. Both and are at most the third angle, so they are acute, and the foot of the height splits the side into parts and with . So . The function grows in each of , and , so and the area is at least .
A bisection halves the area. So a face made by bisections from has area , and it can be split only if , that is, . Each split bisects one or two faces, and each face is bisected at most once, because the face disappears. So the number of splits is at most the number of faces ever made at a depth that can be split, which is finite. When the heap is empty, no edge is longer than .
Lemma 3 (a safe collapse keeps the manifold and the topology). If is an inner edge with faces and , neither nor is a border vertex, and the link condition holds, then merging into gives an oriented manifold mesh with the same Euler characteristic and the same border.
Proof. The two faces of vanish, and every other face of gets in place of . Since and are inner vertices, their stars are disks, with link cycles around and around . The new link of is the first cycle with removed, joined at and to the second cycle with removed. The link condition says that these two paths share only and , so the join is a single simple cycle, and the new star of is a disk. A vertex in the link of is not a neighbour of , so its link changes only by the name and stays a cycle. The vertices and each lose one neighbour ( merges into ) and keep a link cycle of length , because the guard asks . No directed edge is used twice: a repeated directed edge would need a common neighbour of and other than and . The faces keep their vertex order, so the orientation stays. The counts change by , (the edge , and , merge into , ) and , so is the same. No border vertex is involved, so the border does not change. This is the inner case of the result of Dey, Edelsbrunner, Guha and Nekhayev on topology-preserving edge contraction.
Theorem 2 (the collapse phase stops and keeps the bound). Line L3 makes fewer than collapses, where is the vertex count at its start. If every edge is at most at the start, this still holds at the end.
Proof. Each collapse removes one vertex and adds none, and a mesh with faces keeps at least 3 vertices, so there are fewer than collapses. Each sweep over the edges either collapses one or ends the loop. The new edges of a collapse are the edges from the midpoint to the old neighbours of and , and the guard refuses the collapse if one of them is longer than . All other edges keep their length.
Lemma 4 (a flip keeps the topology and changes four valences). Flipping a legal inner edge with faces and into and gives an oriented manifold mesh with the same , and , the same border, and new valences , , , , all others unchanged.
Proof. The legality test asks and that is not an edge, so the new edge is new and no directed edge is used twice. The four outer edges , , , keep one face each on the same side. The edge leaves and comes in, so the counts stay. and keep valence at least 3, because the test asks at least 4 before the flip. Border status depends only on border edges, which flips do not touch, so the targets do not change.
Theorem 3 (the flip phase stops at a local optimum). Line L4 makes at most flips, where is the valence excess at its start. When it stops, no legal flip lowers the excess.
Proof. A flip is made only if it lowers . By Lemma 4 no other term of changes, so drops by this positive integer, at least 1. Since , there are at most flips. The loop ends after a sweep with no flip, and in that sweep every edge was tested, so no legal flip lowers .
Theorem 4 (topology and border are kept). The output is an oriented manifold mesh with the Euler characteristic and the border curve of the input, and every vertex of the input border that was there at the start is still in place.
Proof. Lines L2, L3 and L4 keep both by Lemmas 1, 3 and 4. Line L5 moves only inner vertices, and does not change the faces. Border vertices are never moved, never collapsed, and border edges are only split at their midpoints, so the border curve is the same point set in every round.
Termination. Each round stops by Theorems 1, 2 and 3, and line L5 is one pass over the vertices, so the rounds stop.
What is not proved here. The upper bound of Theorem 1 holds after line L3, but flips and the relaxation of line L5 can make edges longer than again, and edges shorter than remain where no collapse is safe. Line L5 can also, in principle, move a vertex so far that a face turns over. That the final edge lengths, angles and valences are close to the targets, and that the faces stay oriented, is measured in the tests and the examples, not proved. Theorem 1 uses exact midpoints, and the Rosenberg and Stenger bound gives no useful count of the splits beyond finiteness.
Complexity
With a half-edge structure, or the edge and face maps of the code, each local operator costs time for the valences involved, which is on a mesh of bounded valence. Assume bounded valence. In one round, line L2 makes at most splits, each with a priority queue operation of , and line L5 takes time plus the cost of the projection. Lines L3 and L4 sweep the sorted edge list, per sweep, until a sweep changes nothing. Every sweep but the last makes a collapse or a flip, and the proofs bound these by collapses and by the valence excess, which is , flips. This gives the worst case . In the measured runs the loops end after a few sweeps, so a round costs about in practice. Projection onto the input mesh needs a spatial search structure, about per query. In practice to rounds are used. The extra space is .
Properties
- Local and simple. Four operators and two thresholds.
- The thresholds fit together. and are chosen so that splitting an edge just above gives halves above , and collapsing the shortest edges does not make edges longer than the split threshold, so the steps do not undo each other.
- Uniform, not adaptive. All edges aim at one length. Fine details smaller than are lost, and flat regions get as many triangles as curved ones.
- Topology is kept. The Euler characteristic, the number of border loops and the orientation stay.
- Not exact. The midpoints, normals and projections use floating point.
Variants and improvements
- Adaptive remeshing. Make depend on the position, smaller where the curvature is high, so that the error stays the same with fewer triangles.
- Feature edges. Mark sharp edges and corners, and never collapse or flip across them. Relax feature vertices only along the feature curve.
- Area-weighted relaxation. Use the centroid of the neighbours weighted by the areas of their faces, which spreads the vertices according to the area.
- Delaunay flips. Flip toward the intrinsic Delaunay condition, the angles opposite each edge summing to at most , as in the Lawson flip algorithm, instead of toward valence 6.
- Quadric collapses. For coarsening only, collapse by the quadric error metric of mesh simplification, which keeps the shape better than midpoint collapses.
- Global methods. Centroidal Voronoi tessellations and parameterization-based remeshers optimize the vertex positions as a whole, at a higher cost.
When to use it
Use it to clean a mesh before simulation, smoothing, parameterization or geodesic computations, all of which need well-shaped triangles, and to bring a scanned or converted mesh to a known resolution. Several mesh libraries include it. For planar domains with guaranteed angle bounds, use Delaunay refinement, such as Ruppert's algorithm. To reduce the triangle count while keeping the shape, use mesh simplification. To measure how far the result is from the input, use Metro.
Pitfalls
- No projection. Without line L5's projection, the tangential moves still drift off a curved surface, and the shape slowly changes.
- Unsafe collapses. A collapse without the link condition can glue two sheets together, or make a vertex whose star is not a disk.
- Collapsing into long edges. Without the guard, a collapse can make edges that the next round splits again, and the loop does not settle.
- Moving the border. Relaxing border vertices like inner ones pulls the border inward.
- Features. Sharp edges are rounded unless they are marked and kept.
- A target too large. If is larger than the size of a thin part, collapses close it up or the link condition blocks them, and the mesh stays poor there.
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/isotropic-remeshing/. The authors are listed in prov/0E9HMJ.jsonl.
"""Isotropic remeshing in the style of Botsch and Kobbelt (SGP 2004).
Each round, for a target edge length L:
1. split the longest edge while it is longer than 4/3 L,
2. collapse edges shorter than 4/5 L into their midpoint, when the collapse is
safe (link condition, no border vertex, no new edge longer than 4/3 L, no
flipped face),
3. flip edges while a flip lowers the valence excess (target 6 inside,
4 on the border),
4. move each inner vertex toward the centroid of its neighbours, inside its
tangent plane, and
5. optionally project the vertices onto a reference surface.
Border vertices never move and border edges are never collapsed or flipped, so
the border keeps its shape (border edges may still be split at their midpoints).
The mesh is a small half-edge-like structure: directed edge -> face, and
vertex -> faces.
"""
import heapq
from math import sqrt
from typing import Callable, Optional, Sequence
Vec = tuple
def sub(a, b):
return (a[0] - b[0], a[1] - b[1], a[2] - b[2])
def dot(a, b):
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def cross(a, b):
return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])
def length(a):
return sqrt(dot(a, a))
def mid(a, b):
return ((a[0] + b[0]) / 2, (a[1] + b[1]) / 2, (a[2] + b[2]) / 2)
class Mesh:
def __init__(self, points: Sequence[Sequence[float]], faces: Sequence[Sequence[int]]):
self.P: list[Vec] = [tuple(p) for p in points]
self.F: dict[int, tuple[int, int, int]] = {}
self.he: dict[tuple[int, int], int] = {}
self.vf: list[set[int]] = [set() for _ in self.P]
self.next_id = 0
for f in faces:
self.add_face(*f)
# ---- basic operations ----
def add_face(self, a, b, c) -> int:
fid = self.next_id
self.next_id += 1
self.F[fid] = (a, b, c)
for u, v in ((a, b), (b, c), (c, a)):
if (u, v) in self.he:
raise ValueError("non-manifold or badly oriented: directed edge used twice")
self.he[(u, v)] = fid
for v in (a, b, c):
self.vf[v].add(fid)
return fid
def remove_face(self, fid):
a, b, c = self.F.pop(fid)
for u, v in ((a, b), (b, c), (c, a)):
del self.he[(u, v)]
for v in (a, b, c):
self.vf[v].discard(fid)
def opposite(self, u, v):
"""The third vertex of the face with the directed edge u -> v, or None."""
fid = self.he.get((u, v))
if fid is None:
return None
f = self.F[fid]
return next(w for w in f if w != u and w != v)
def neighbours(self, v) -> set[int]:
return {w for fid in self.vf[v] for w in self.F[fid] if w != v}
def is_border_edge(self, u, v) -> bool:
return ((u, v) in self.he) != ((v, u) in self.he)
def is_border_vertex(self, v) -> bool:
return any(self.is_border_edge(v, w) for w in self.neighbours(v))
def edges(self) -> list[tuple[int, int]]:
return sorted({(min(u, v), max(u, v)) for u, v in self.he})
def elen(self, u, v) -> float:
return length(sub(self.P[u], self.P[v]))
def face_normal(self, f, P=None):
P = P or self.P
a, b, c = f
return cross(sub(P[b], P[a]), sub(P[c], P[a]))
def valence_target(self, v) -> int:
return 4 if self.is_border_vertex(v) else 6
# ---- the three local operators ----
def split(self, u, v) -> int:
"""Split the edge u-v at its midpoint m; each face (u, v, w) becomes (u, m, w) and (m, v, w)."""
m = len(self.P)
self.P.append(mid(self.P[u], self.P[v]))
self.vf.append(set())
for a, b in ((u, v), (v, u)):
fid = self.he.get((a, b))
if fid is not None:
w = self.opposite(a, b)
self.remove_face(fid)
self.add_face(a, m, w)
self.add_face(m, b, w)
return m
def can_collapse(self, u, v, high) -> bool:
if self.is_border_edge(u, v) or self.is_border_vertex(u) or self.is_border_vertex(v):
return False
c, d = self.opposite(u, v), self.opposite(v, u)
if self.neighbours(u) & self.neighbours(v) != {c, d}: # the link condition
return False
if len(self.neighbours(c)) <= 3 or len(self.neighbours(d)) <= 3:
return False
p = mid(self.P[u], self.P[v])
if any(length(sub(p, self.P[w])) > high for w in (self.neighbours(u) | self.neighbours(v)) - {u, v}):
return False
P = list(self.P)
P[u] = P[v] = p
for fid in self.vf[u] | self.vf[v]:
f = self.F[fid]
if u in f and v in f:
continue
if dot(self.face_normal(f), self.face_normal(f, P)) <= 0: # the face would flip or degenerate
return False
return True
def collapse(self, u, v):
"""Merge v into u at the midpoint. The two faces of the edge disappear."""
p = mid(self.P[u], self.P[v])
old = [self.F[fid] for fid in self.vf[v]]
for fid in list(self.vf[v]):
self.remove_face(fid)
for f in old:
if u not in f:
self.add_face(*(u if w == v else w for w in f))
self.P[u] = p
def flip_gain(self, u, v) -> int:
"""How much a flip of u-v lowers the valence excess at its four vertices (0 if not allowed)."""
if self.is_border_edge(u, v):
return 0
c, d = self.opposite(u, v), self.opposite(v, u)
if c == d or d in self.neighbours(c):
return 0
val = {w: len(self.neighbours(w)) for w in (u, v, c, d)}
if val[u] <= 3 or val[v] <= 3:
return 0
tgt = {w: self.valence_target(w) for w in (u, v, c, d)}
before = sum(abs(val[w] - tgt[w]) for w in (u, v, c, d))
after = (abs(val[u] - 1 - tgt[u]) + abs(val[v] - 1 - tgt[v]) +
abs(val[c] + 1 - tgt[c]) + abs(val[d] + 1 - tgt[d]))
if after >= before:
return 0
n_old = tuple(x + y for x, y in zip(self.face_normal((u, v, c)), self.face_normal((v, u, d))))
for f in ((u, d, c), (d, v, c)):
if dot(self.face_normal(f), n_old) <= 0: # the new face would fold over
return 0
return before - after
def flip(self, u, v):
"""Faces (u, v, c) and (v, u, d) become (u, d, c) and (d, v, c)."""
c, d = self.opposite(u, v), self.opposite(v, u)
self.remove_face(self.he[(u, v)])
self.remove_face(self.he[(v, u)])
self.add_face(u, d, c)
self.add_face(d, v, c)
# ---- output ----
def compact(self) -> tuple[list[Vec], list[tuple[int, int, int]]]:
used = sorted({w for f in self.F.values() for w in f})
new = {v: i for i, v in enumerate(used)}
return [self.P[v] for v in used], [tuple(new[w] for w in self.F[fid]) for fid in sorted(self.F)]
def split_long_edges(mesh: Mesh, high: float) -> int:
"""Split the longest edge while it is longer than high. Returns the number of splits."""
heap = [(-mesh.elen(u, v), u, v) for u, v in mesh.edges() if mesh.elen(u, v) > high]
heapq.heapify(heap)
count = 0
while heap:
neg, u, v = heapq.heappop(heap)
if ((u, v) not in mesh.he and (v, u) not in mesh.he) or mesh.elen(u, v) != -neg:
continue
m = mesh.split(u, v)
count += 1
for w in mesh.neighbours(m):
if mesh.elen(m, w) > high:
heapq.heappush(heap, (-mesh.elen(m, w), min(m, w), max(m, w)))
return count
def collapse_short_edges(mesh: Mesh, low: float, high: float) -> int:
count = 0
changed = True
while changed:
changed = False
for u, v in mesh.edges():
if (u, v) not in mesh.he and (v, u) not in mesh.he:
continue
if mesh.elen(u, v) < low and mesh.can_collapse(u, v, high):
mesh.collapse(u, v)
count += 1
changed = True
return count
def equalize_valences(mesh: Mesh) -> int:
count = 0
changed = True
while changed:
changed = False
for u, v in mesh.edges():
if (u, v) not in mesh.he:
u, v = v, u
if (u, v) in mesh.he and mesh.flip_gain(u, v) > 0:
mesh.flip(u, v)
count += 1
changed = True
return count
def tangential_relaxation(mesh: Mesh, project: Optional[Callable] = None):
live = sorted({w for f in mesh.F.values() for w in f})
new = {}
for v in live:
if mesh.is_border_vertex(v):
continue
nb = mesh.neighbours(v)
q = tuple(sum(mesh.P[w][k] for w in nb) / len(nb) for k in range(3))
n = (0.0, 0.0, 0.0)
for fid in mesh.vf[v]:
n = tuple(x + y for x, y in zip(n, mesh.face_normal(mesh.F[fid])))
ln = length(n)
d = sub(q, mesh.P[v])
if ln > 0:
n = tuple(x / ln for x in n)
d = tuple(d[k] - dot(d, n) * n[k] for k in range(3))
p = tuple(mesh.P[v][k] + d[k] for k in range(3))
new[v] = project(p) if project else p
for v, p in new.items():
mesh.P[v] = p
def isotropic_remeshing(points: Sequence[Sequence[float]], faces: Sequence[Sequence[int]], target: float,
iterations: int = 5, project: Optional[Callable] = None):
"""Remesh toward edges of length `target`. Returns (points, faces) of the new mesh."""
mesh = Mesh(points, faces)
low, high = 4 * target / 5, 4 * target / 3
for _ in range(iterations): # @line L1
split_long_edges(mesh, high) # @line L2
collapse_short_edges(mesh, low, high) # @line L3
equalize_valences(mesh) # @line L4
tangential_relaxation(mesh, project) # @line L5
return mesh.compact() # @line L6
test_isotropic_remeshing.py 219 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/isotropic-remeshing/. The authors are listed in prov/0E9HMJ.jsonl.
import random
from math import acos, degrees, sqrt
from isotropic_remeshing import (Mesh, collapse_short_edges, cross, dot, equalize_valences, isotropic_remeshing,
length, split_long_edges, sub)
def sphere(p):
n = sqrt(dot(p, p))
return tuple(c / n for c in p)
def icosphere(level):
t = (1 + sqrt(5)) / 2
raw = [(-1, t, 0), (1, t, 0), (-1, -t, 0), (1, -t, 0), (0, -1, t), (0, 1, t),
(0, -1, -t), (0, 1, -t), (t, 0, -1), (t, 0, 1), (-t, 0, -1), (-t, 0, 1)]
pts = [sphere(p) for p in raw]
faces = [(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)]
for _ in range(level):
memo = {}
def m(i, j):
k = (min(i, j), max(i, j))
if k not in memo:
pts.append(sphere(tuple((a + b) / 2 for a, b in zip(pts[i], pts[j]))))
memo[k] = len(pts) - 1
return memo[k]
faces = [g for a, b, c in faces for g in
((a, m(a, b), m(c, a)), (b, m(b, c), m(a, b)), (c, m(c, a), m(b, c)), (m(a, b), m(b, c), m(c, a)))]
return pts, faces
def rectangle():
"""An 8 x 4 rectangle cut into 32 long thin triangles (cells 4 x 0.5)."""
pts = [(4.0 * i, 0.5 * j, 0.0) for j in range(9) for i in range(3)]
faces = []
for j in range(8):
for i in range(2):
a, b, c, d = 3 * j + i, 3 * j + i + 1, 3 * (j + 1) + i + 1, 3 * (j + 1) + i
faces += [(a, b, c), (a, c, d)]
return pts, faces
# ---- brute force: the topology recomputed from the face list ----
def check_manifold(points, faces, closed):
directed = {}
for f in faces:
assert len(set(f)) == 3
for k in range(3):
e = (f[k], f[(k + 1) % 3])
assert e not in directed # consistent orientation, no edge used twice
directed[e] = f
if closed:
assert all((v, u) in directed for u, v in directed)
for v in {w for f in faces for w in f}: # the link of each vertex is one cycle or one path
nxt = {}
for f in faces:
if v in f:
k = f.index(v)
nxt[f[(k + 1) % 3]] = f[(k + 2) % 3]
starts = set(nxt) - set(nxt.values())
assert len(starts) <= 1
start = next(iter(starts)) if starts else next(iter(nxt))
seen, w = 0, start
while w in nxt and seen <= len(nxt):
w = nxt[w]
seen += 1
if w == start:
break
assert seen == len(nxt)
def euler(points, faces):
es = {(min(f[k], f[(k + 1) % 3]), max(f[k], f[(k + 1) % 3])) for f in faces for k in range(3)}
return len({w for f in faces for w in f}) - len(es) + len(faces)
def area(points, faces):
return sum(length(cross(sub(points[b], points[a]), sub(points[c], points[a]))) / 2 for a, b, c in faces)
def edge_lengths(points, faces):
es = {(min(f[k], f[(k + 1) % 3]), max(f[k], f[(k + 1) % 3])) for f in faces for k in range(3)}
return [length(sub(points[i], points[j])) for i, j in es]
def test_square_example() -> None:
p = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0), (0.0, 1.0, 0.0)]
mesh = Mesh(p, [(0, 1, 2), (0, 2, 3)])
assert split_long_edges(mesh, 4 * 0.5 / 3) == 9 # the diagonal, the 4 sides, the 4 half-diagonals
P, F = mesh.compact()
assert (len(P), len(F)) == (13, 16)
assert sorted(set(round(x, 12) for x in edge_lengths(P, F))) == [round(sqrt(2) / 4, 12), 0.5]
assert (0.5, 0.5, 0.0) in P and (0.25, 0.25, 0.0) in P
def test_split_bounds_every_edge_and_keeps_the_surface() -> None:
for (p, f), L in ((icosphere(0), 0.3), (rectangle(), 0.5)):
mesh = Mesh(p, f)
a0 = area(p, f)
k = split_long_edges(mesh, 4 * L / 3)
P, F = mesh.compact()
assert max(edge_lengths(P, F)) <= 4 * L / 3
assert abs(area(P, F) - a0) < 1e-9 * a0 # midpoints stay in the planes of the faces
assert euler(P, F) == euler(p, f)
assert len(F) >= len(f) + k # each split adds one or two faces
check_manifold(P, F, closed=(len(p) == 12))
def test_collapse_respects_the_upper_bound() -> None:
p, f = icosphere(2)
L = 0.5 # the edges of the input are about 0.3
mesh = Mesh(p, f)
split_long_edges(mesh, 4 * L / 3)
n0 = len({w for g in mesh.F.values() for w in g})
k = collapse_short_edges(mesh, 4 * L / 5, 4 * L / 3)
P, F = mesh.compact()
assert k > 0 and len(P) == n0 - k # each collapse removes one vertex
assert max(edge_lengths(P, F)) <= 4 * L / 3
assert euler(P, F) == 2
check_manifold(P, F, closed=True)
def test_flips_reach_a_local_optimum() -> None:
rng = random.Random(5)
p, f = icosphere(2)
p = [sphere(tuple(c + 0.04 * (rng.random() - 0.5) for c in v)) for v in p]
mesh = Mesh(p, f)
for u, v in rng.sample(sorted(mesh.he), 60): # scramble the valences first
if (u, v) in mesh.he and mesh.opposite(u, v) != mesh.opposite(v, u):
c, d = mesh.opposite(u, v), mesh.opposite(v, u)
if d not in mesh.neighbours(c) and len(mesh.neighbours(u)) > 3 and len(mesh.neighbours(v)) > 3:
mesh.flip(u, v)
def excess():
live = {w for g in mesh.F.values() for w in g}
return sum(abs(len(mesh.neighbours(w)) - 6) for w in live)
e0 = excess()
equalize_valences(mesh)
assert excess() < e0
for u, v in mesh.he: # the brute-force scan: no improving flip is left
assert mesh.flip_gain(u, v) == 0
P, F = mesh.compact()
check_manifold(P, F, closed=True)
def test_random_operations_keep_a_manifold() -> None:
rng = random.Random(11)
p, f = icosphere(1)
mesh = Mesh(p, f)
for _ in range(150):
u, v = rng.choice(sorted(mesh.he))
op = rng.randrange(3)
if op == 0:
mesh.split(u, v)
elif op == 1 and mesh.can_collapse(u, v, float("inf")):
mesh.collapse(u, v)
elif op == 2 and mesh.flip_gain(u, v) > 0:
mesh.flip(u, v)
P, F = mesh.compact()
check_manifold(P, F, closed=True)
assert euler(P, F) == 2
def test_sphere_is_remeshed_to_the_target_length() -> None:
rng = random.Random(3)
p, f = icosphere(2)
p = [sphere(tuple(c + 0.05 * (rng.random() - 0.5) for c in v)) for v in p]
L = 0.15
P, F = isotropic_remeshing(p, f, L, 5, project=sphere)
check_manifold(P, F, closed=True)
assert euler(P, F) == 2
assert all(abs(length(q) - 1) < 1e-12 for q in P)
vol = sum(dot(P[a], cross(P[b], P[c])) for a, b, c in F) / 6
assert vol > 0 # the orientation is kept
ls = edge_lengths(P, F)
mean = sum(ls) / len(ls)
assert abs(mean / L - 1) < 0.05 # measured: 1.021
assert sum(1 for x in ls if 4 * L / 5 <= x <= 4 * L / 3) / len(ls) > 0.98 # measured: 0.995
angles = []
for t in F:
for k in range(3):
a, b, c = P[t[k]], P[t[(k + 1) % 3]], P[t[(k + 2) % 3]]
x, y = sub(b, a), sub(c, a)
angles.append(degrees(acos(dot(x, y) / (length(x) * length(y)))))
assert min(angles) > 35 # measured: 41 degrees, from 44 in the input
def test_border_is_kept() -> None:
p, f = rectangle()
P, F = isotropic_remeshing(p, f, 0.5, 5)
check_manifold(P, F, closed=False)
assert euler(P, F) == 1
assert abs(area(P, F) - 32) < 1e-9
assert all(q[2] == 0.0 for q in P)
for q in p:
if q[0] in (0.0, 8.0) and q[1] in (0.0, 4.0):
assert q in P # the corners stay
directed = {(t[k], t[(k + 1) % 3]) for t in F for k in range(3)}
for u, v in directed:
if (v, u) not in directed: # a border edge lies on the rectangle
a, b = P[u], P[v]
assert (a[0] == b[0] and a[0] in (0.0, 8.0)) or (a[1] == b[1] and a[1] in (0.0, 4.0))
angles = []
for t in F:
for k in range(3):
a, b, c = P[t[k]], P[t[(k + 1) % 3]], P[t[(k + 2) % 3]]
x, y = sub(b, a), sub(c, a)
angles.append(degrees(acos(dot(x, y) / (length(x) * length(y)))))
assert min(angles) > 20 # measured: 27 degrees, from 7 in the input
History
Remeshing by local operators grew out of the mesh optimization work of the 1990s, which used splits, collapses and swaps to fit a mesh to data. Surazhsky and Gotsman described explicit remeshing by local operators in 2003. In 2004 Botsch and Kobbelt, in a paper on multiresolution modeling, reduced the method to a loop of four steps with the thresholds and , and this simple form became the standard one in teaching and in libraries. The termination of the split step rests on the 1975 theorem of Rosenberg and Stenger on the angles of longest-side bisection.
References
- Mario Botsch and Leif Kobbelt, A remeshing approach to multiresolution modeling, Eurographics Symposium on Geometry Processing (SGP), 2004, 189 to 196, the remeshing loop of splits, collapses, flips and tangential relaxation, with the thresholds 4/3 and 4/5 of the target edge length
- Ivo G. Rosenberg and Frank Stenger, A lower bound on the angles of triangles constructed by bisecting the longest side, Mathematics of Computation 29(130), 1975, 390 to 395, the theorem that repeated longest-side bisection keeps every angle at least half the smallest angle of the first triangle
- Mario Botsch, Leif Kobbelt, Mark Pauly, Pierre Alliez and Bruno Lévy, Polygon Mesh Processing, AK Peters, 2010, Chapter 6, Remeshing (incremental isotropic remeshing and the local operators)
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 0E9HMJ Edit this page History Report an error Markdown