Algorithmadvanced
Laplacian surface editing
Also called differential coordinates editing.
Sorkine and coauthors' editing that keeps the Laplacian coordinates of a mesh in least squares while handle vertices are moved, preserving local detail.
- Time
- O(n^3) worst
- Space
- Θ(n^2) extra
- Where
- n = the number of vertices
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Olga Sorkine, Daniel Cohen Or, Yaron Lipman, Marc Alexa, Christian Rössl, Hans Peter Seidel, 2004
Laplacian surface editing changes the shape of a triangle mesh by moving a few handle vertices, and it keeps the small detail of the surface. It does not store the positions of the vertices but their Laplacian coordinates: for each vertex, the difference between the vertex and the mean of its neighbours. This vector is near the normal and its length follows the local curvature, so it encodes the detail. Olga Sorkine and coauthors (2004) moved the handles and then found the positions whose Laplacian coordinates are as close as possible, in least squares, to the old ones. That is one sparse linear solve. Because the Laplacian coordinates do not turn with the surface, they also fitted to each vertex a linearized similarity, a scale and a small rotation that depend linearly on the new positions, and turned each Laplacian coordinate by it. The energy stays a quadratic, and the solve stays linear. With the handles left at their rest positions the solve returns the input mesh.
In plain words
Describe each corner of a mesh not by where it is, but by how it sits relative to its neighbours: a little above them, a little to the side. These small offsets hold the bumps and wrinkles of the surface.
Now pull a few corners to new places. Find new places for all the other corners so that each corner sits relative to its neighbours almost as it did before, and so that the pulled corners land near where they were pulled. This is one large least squares problem, and one solve answers it.
The offsets are fixed arrows, so if part of the surface turns, the old arrows point the wrong way. The method therefore lets each corner also turn and scale its own arrow a little, by the amount its neighbours suggest. This works well for small turns.
The problem
The input is a connected triangle mesh with rest positions , a nonempty set of handle vertices with targets , and a weight . With the neighbours of vertex , the uniform Laplacian is , and the Laplacian coordinates are . The output is the positions that minimize
In the plain form . With rotations, , where , and is the least squares fit of over the ring . The handles are soft constraints: a larger pulls them closer to their targets.
The algorithm
LAPLACIAN-EDIT(rest positions p, handles H with targets h, weight λ, rotations)- 1
δ_i ← p_i − (1/d_i) Σ_j p_j for each vertex i - 2
if rotations: for each vertex i, write (s_i, h_i) of the fit of its rest ring as a linear function of q - 3
a row L(q)_i − T_i(q) δ_i for each vertex i, with T_i = I without rotations - 4
a row λ (q_k − h_k) for each handle k - 5
N ← Mᵀ M and b ← Mᵀ r, for the rows M x − r of lines L3 and L4 - 6
solve N x = b by Cholesky - 7
return the positions q in x
Line L1 computes the Laplacian coordinates. In the plain form, lines L3 to L6 separate into three problems, one for each coordinate, with the same matrix . With rotations, line L2 solves, for each vertex, the normal equations of the fit of its rest ring. Their solution is , where holds the new positions of the ring, so and are fixed linear combinations of the unknowns. Then is linear in too, line L3 couples the three coordinates, and the system has unknowns. The translation of the fit is not applied, because is a difference of points. The matrix depends only on the rest mesh and on which vertices are handles, so an interactive editor factors it once and, as the user drags the handles, only changes .
Example
The input comes back. Take the grid of points on the square with the bump , cut into 32 triangles, and three corners as handles at their rest positions. Solved exactly with rational numbers, the plain form returns the input exactly. The form with rotations does the same on the grid of the bump. On that grid, moving the three handles by moves every vertex by the same vector, exactly, in both forms.
Turning the border. Take the grid of the same bump, with 81 vertices and 128 triangles, and the 32 border vertices as handles with . Turn the targets of the border by an angle about the axis. A perfect edit would turn the whole patch rigidly. The table gives the largest distance of an inner vertex from that rigid turn, and the height of the centre of the bump along the turned normal, which is at rest.
| plain: error | ||||
| plain: height | ||||
| rotations: error | ||||
| rotations: height |
In the plain form the Laplacian coordinates keep pointing up, so the bump leans as the border turns, and at it is flat: its height along the new normal is 0. The linearized similarities fix most of this for small angles, but the error grows with the angle, because is a rotation only to first order. With the border vertices are at most from their targets instead of , and the inner errors do not change in the first three digits.
Correctness
The proof file shows these facts.
- The solve is the least squares minimum. is a convex quadratic, its minima solve the normal equations of line L5, and the minimum is unique when the matrix is positive definite.
- The plain matrix is positive definite. On a connected mesh only for a constant , because each value is then the mean of its neighbours and the largest value spreads. A handle makes that constant 0.
- The unconstrained solve returns the input. With the handles at their rest positions, : the Laplacian coordinates of are , and the fit of a rest ring to itself is , . By uniqueness the solve returns , exactly in rational arithmetic.
- No handle, no unique answer. Without handles the plain minima are exactly plus a constant vector. With rotations, all linearized similarities of have energy 0, and three handles not on a line remove them.
- A translation is kept. If all handles move by the same vector, the whole mesh moves by it.
With rotations, that the matrix is positive definite once three handles are not on a line is not proved. The code reports a singular matrix, and the tests check the matrix on their meshes. How much detail survives large turns is measured, not proved.
Proof: The Laplacian editing solve is the unique least squares minimum, and with the handles at rest it returns the input meshfull
Setup. The mesh is connected, with rest positions , and is the set of the neighbours of vertex . The uniform Laplacian is , applied to each coordinate, and the Laplacian coordinates are . The handles are a set of vertices with targets , and is the weight of the handles. The energy is
Without rotations, . With rotations, , where , and is the least squares solution of for in the ring . The algorithm writes as for a matrix , forms the normal equations , and solves them. It needs no loop.
Lemma 1 (the kernel of the Laplacian). For a scalar function on the vertices, if and only if is constant.
Proof. A constant gives . Conversely, let , so each is the mean of its neighbours. Let be the largest value of and . A mean of values at most equals only if all of them equal , so all neighbours of have the value . The mesh is connected, so by induction along paths every vertex has the value .
Lemma 2 (the solve gives the unique minimum). is a quadratic function, and its minima are the solutions of the normal equations . If is positive definite, the minimum is unique and the solve returns it.
Proof. has the gradient , and is positive semidefinite, so is convex and its minima are exactly its critical points. If is positive definite, the system has one solution, and its Cholesky factorization exists. On rational input, Gaussian elimination solves it exactly.
Lemma 3 (the matrix without rotations). Without rotations and with , the coordinates separate, and the matrix of each one is . It is positive definite.
Proof. For a scalar , . If it is 0, then , so is constant by Lemma 1, and at a handle, so .
Lemma 4 (the fit of a ring). Suppose the ring of vertex is not contained in a line. Then the fit has exactly one solution , and it is a linear function of the new positions of the ring. If the new ring is for a scalar and a vector , the fit is .
Proof. The map is linear. Suppose it gives 0. Subtracting the equation at gives for each . The matrix sends a vector to , and . So if , it sends no nonzero vector to 0, and all , which is false. So , and means is parallel to every . The ring is not in a line, so two of these vectors are independent, and . Then . So the map is injective, its normal matrix is invertible, and the fit is linear in the right side . For the new ring , the choice fits with residual 0, so it is the unique least squares solution.
In a triangle mesh, the ring of a vertex holds the corners of a triangle, so it is not in a line when the triangles are not degenerate.
Theorem 1 (the unconstrained solve returns the input). Let every handle stay at its rest position, , with . Then , so is a minimum of . Without rotations the solve returns . With rotations it returns whenever is positive definite. On rational input the result is exactly.
Proof. Without rotations, by the definition of . With rotations, Lemma 4 with and gives , so again . The handle terms are . So , the least possible value. By Lemma 3 without rotations, and by the assumption with rotations, the minimum is unique, and by Lemma 2 the solve returns it.
Theorem 2 (no handles). Without rotations and without handles, the minima of are exactly the positions for a constant vector . So the system is singular, and one handle is enough to fix the result.
Proof. , which is 0 exactly when , that is, by Lemma 1, when is constant.
Theorem 3 (a translation of the handles). Let for all , with . Then the solve returns , without rotations always, and with rotations whenever is positive definite.
Proof. sends the constant to 0, so . With rotations, Lemma 4 with gives . The handle terms are 0. So , and uniqueness gives the result as in Theorem 1.
The kernel with rotations. With rotations and without handles, is 0 at every , because is linear and kills constants, so , and is linear in , so by Lemma 4 applied term by term . These are 7 dimensions. Three handles whose rest positions are not on a line remove them: if at the three handles, then sends two independent differences of their rest positions to 0, and the argument of Lemma 4 gives , and then . That no other direction of the kernel remains is not proved here. The code lets the Cholesky factorization, or the exact elimination, report a singular matrix, and the tests check that the matrix is positive definite on their meshes.
Termination. The algorithm builds a fixed number of rows and does one direct solve, so it stops.
How well the rotations keep the detail under large turns of the handles is measured on the page, not proved. The linearized is a rotation only to first order in the angle.
Complexity
Let be the number of vertices. The rows of lines L1 to L4 have entries each on a mesh of bounded degree, with rows in all, and each fit of line L2 is a solve, so building costs . The code stores as a dense matrix of size or , so the factorization costs and the extra space is , on the real RAM. is sparse, and a sparse Cholesky decomposition with a fill-reducing order factors it much faster in practice. After the factorization, each new position of the handles costs one pair of triangular solves.
Properties
- One linear solve. No iteration and no starting guess.
- Exact. On rational input the solve is exact, and the input comes back exactly.
- Invariant under translation. Moving all handles by a vector moves the result by it.
- Not invariant under rotation. The plain Laplacian coordinates do not turn. The linearized similarities turn them correctly only for small angles.
- Soft handles. The handles reach their targets only approximately, more closely as grows.
- One factorization. The matrix depends on the rest mesh and on the set of handles, not on the targets.
Variants and improvements
- Cotangent weights. The cotangent Laplacian makes the Laplacian coordinates depend on the shape and not on how the mesh is cut, at the cost of weights that can be negative on obtuse triangles.
- Hard handles. Remove the handle vertices from the unknowns and move their known values to the right side. The handles then hit their targets exactly.
- Explicit rotations. Estimate the rotation of each vertex from a first solve, turn the Laplacian coordinates by it, and solve again, as Lipman and coauthors did. As-rigid-as-possible deformation iterates this with exact rotations and handles large angles.
- Gradient-domain editing. Edit the gradients of the coordinate functions instead and solve a Poisson equation, as Poisson image editing does for images.
- Higher order. Minimizing the bending, the squared Laplacian of the displacement, gives smooth deformations without detail, and detail can then be added back on top.
When to use it
Use Laplacian surface editing for interactive edits of a detailed mesh with handles where the parts move or turn by small amounts, and for transferring detail from one surface to another, because the whole edit is one precomputed linear solve. For large rotations, such as bending a limb, use as-rigid-as-possible deformation, which costs a few more solves for each frame. To smooth a mesh instead of keeping its detail, use Laplacian smoothing or implicit fairing.
Pitfalls
- No handle. The plain system is singular, because a translation does not change Laplacian coordinates. With rotations, use at least three handles that are not on a line.
- Large rotations. In the example, at a turn of the plain form flattens the bump completely, and the linearized form still leaves an error of on a patch of width 2.
- Weak handles. With soft constraints and a small , the handles do not reach their targets. Raise or eliminate the handles from the unknowns.
- Normal equations. squares the condition number of . For fine meshes or large , a QR decomposition of is more accurate.
- Degenerate rings. The fit of line L2 needs a ring that is not in a line. A vertex whose triangles are all degenerate breaks it.
- Uniform weights on irregular meshes. The uniform Laplacian coordinates have tangential parts on an irregular mesh, so the result depends on how the mesh is cut into triangles.
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/laplacian-surface-editing/. The authors are listed in prov/44KQTR.jsonl.
"""Laplacian surface editing (Sorkine, Cohen-Or, Lipman, Alexa, Roessl and Seidel, SGP 2004).
The Laplacian coordinates of the rest mesh are delta_i = p_i - (1/d_i) sum_j p_j,
with the uniform Laplacian and d_i the degree of vertex i. The edited positions q
minimize
E(q) = sum_i |L(q)_i - T_i(q) delta_i|^2 + lam^2 sum_{k in H} |q_k - h_k|^2,
where H is the set of handles with targets h_k. Without rotations T_i = I, and
the three coordinates are solved apart with one matrix. With rotations,
T_i(q) = s_i I + [h_i]_x is the linearized similarity that best maps the rest
ring of vertex i (i and its neighbours) to the new ring. Its coefficients are
linear in q, so E stays a quadratic and one linear solve gives q.
The solve uses the normal equations. On Fraction input it is exact
(Gaussian elimination); on float input it uses a Cholesky factorization.
"""
from fractions import Fraction
from mx1mesh import cholesky, cholesky_solve, neighbours, solve_dense
def is_exact(points):
return all(isinstance(x, (int, Fraction)) for p in points for x in p)
def laplacian_rows(nb):
"""Row i of the uniform Laplacian as a dict {column: value}: L(q)_i = q_i - (1/d_i) sum_j q_j."""
rows = []
for i, ring in enumerate(nb):
r = {i: Fraction(1)}
for j in ring:
r[j] = -Fraction(1, len(ring))
rows.append(r)
return rows
def apply_rows(rows, points):
return [tuple(sum(w * points[j][c] for j, w in r.items()) for c in range(3)) for r in rows]
def cross_rows(v):
"""The 3 x 4 matrix K(v) with K(v) (s, h1, h2, h3) = s v + h x v."""
x, y, z = v
return [[x, 0, z, -y], [y, -z, 0, x], [z, y, -x, 0]]
def similarity_rows(points, i, ring):
"""The 4 rows that give (s, h1, h2, h3) of the best map x -> s x + h cross x + t of the rest ring to a new ring.
Each row is a dict {(vertex, coordinate): coefficient}, so (s, h) is linear in the new positions.
The fit is the least squares solution of A (s, h, t) = b, where A has 3 rows for each vertex of the ring.
"""
A, keys = [], []
for j in [i] + list(ring):
K = cross_rows(points[j])
for c in range(3):
A.append(K[c] + [int(c == 0), int(c == 1), int(c == 2)])
keys.append((j, c))
G = [[sum(a[r] * a[s] for a in A) for s in range(7)] for r in range(7)]
rows = []
for r in range(4):
g = solve_dense(G, [int(k == r) for k in range(7)]) # row r of G^-1, as G is symmetric
rows.append({keys[m]: sum(g[k] * A[m][k] for k in range(7)) for m in range(len(A))})
return rows
def least_squares_rows(points, faces, handles, weight=1, rotations=False):
"""The rows (dict {column: value}, right sides) of E. Columns are vertices without rotations, 3 i + c with them."""
nb = neighbours(len(points), faces)
Lrows = laplacian_rows(nb)
delta = apply_rows(Lrows, points) # @line L1
if not rotations:
rows = [(r, list(delta[i])) for i, r in enumerate(Lrows)] # @line L3
rows += [({k: weight}, [weight * x for x in h]) for k, h in handles.items()] # @line L4
return rows
rows = []
for i, r in enumerate(Lrows):
S = similarity_rows(points, i, nb[i]) # @line L2
K = cross_rows(delta[i])
for c in range(3):
row = {3 * j + c: w for j, w in r.items()}
for t in range(4):
if K[c][t]:
for (j, cc), g in S[t].items():
row[3 * j + cc] = row.get(3 * j + cc, 0) - K[c][t] * g
rows.append((row, [0]))
for k, h in handles.items():
for c in range(3):
rows.append(({3 * k + c: weight}, [weight * h[c]]))
return rows
def columns(q, rotations):
"""The unknowns as columns: one list for each coordinate without rotations, one flat list with them."""
if rotations:
return [[x for p in q for x in p]]
return [[p[c] for p in q] for c in range(3)]
def energy(points, faces, q, handles, weight=1, rotations=False):
total = 0
cols = columns(q, rotations)
for row, rhs in least_squares_rows(points, faces, handles, weight, rotations):
for x, r in zip(cols, rhs):
total += (sum(v * x[j] for j, v in row.items()) - r) ** 2
return total
def laplacian_edit(points, faces, handles, weight=1, rotations=False):
"""The positions q that keep the Laplacian coordinates of points while the handles go to their targets."""
n = len(points)
exact = is_exact(points) and is_exact(handles.values())
rows = least_squares_rows(points, faces, handles, weight, rotations)
size = 3 * n if rotations else n
N = [[0] * size for _ in range(size)]
b = [[0] * size for _ in rows[0][1]]
for row, rhs in rows:
items = list(row.items())
for a, x in items:
for c, y in items:
N[a][c] += x * y
for k, r in enumerate(rhs):
b[k][a] += x * r # @line L5
if exact:
x = [solve_dense(N, bk) for bk in b] # @line L6
else:
L = cholesky(N) # raises ValueError when N is not positive definite
x = [cholesky_solve(L, bk) for bk in b]
if rotations:
return [(x[0][3 * i], x[0][3 * i + 1], x[0][3 * i + 2]) for i in range(n)]
return [(x[0][i], x[1][i], x[2][i]) for i in range(n)] # @line L7
mx1mesh.py 515 lines
# SPDX-License-Identifier: MIT
# Shared helper of the mx1 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small tools for triangle meshes and dense linear algebra, used by the mx1 pages.
Points are tuples of three numbers. Faces are tuples of three vertex indices,
counterclockwise when seen from outside, so that the face normals point out.
Only the standard library is used. The geometric signs (an obtuse angle, the
side of a plane) are decided exactly, with Fraction, from the float input.
The linear solvers work on float input and on Fraction input.
"""
import math
from fractions import Fraction
# ---------------------------------------------------------------- vectors
def add(a, b):
return tuple(x + y for x, y in zip(a, b))
def sub(a, b):
return tuple(x - y for x, y in zip(a, b))
def scale(s, a):
return tuple(s * x for x in a)
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
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 norm(a):
return math.sqrt(dot(a, a))
def unit(a):
n = norm(a)
return tuple(x / n for x in a)
def exact(p):
"""The exact rational value of a point with float or Fraction coordinates."""
return tuple(Fraction(x) for x in p)
def sign(x):
return (x > 0) - (x < 0)
def dot_sign(a, b, c):
"""The exact sign of (b - a) . (c - a): positive for an acute angle at a, negative for an obtuse one."""
a, b, c = exact(a), exact(b), exact(c)
return sign(dot(sub(b, a), sub(c, a)))
def orient3d(a, b, c, d):
"""The exact sign of det(b - a, c - a, d - a): positive when d lies on the side of the plane abc that its normal points to."""
a, b, c, d = exact(a), exact(b), exact(c), exact(d)
return sign(dot(cross(sub(b, a), sub(c, a)), sub(d, a)))
# ---------------------------------------------------------------- topology
def edges(faces):
"""The undirected edges as sorted pairs, in sorted order."""
s = set()
for f in faces:
for k in range(3):
i, j = f[k], f[(k + 1) % 3]
s.add((min(i, j), max(i, j)))
return sorted(s)
def neighbours(n, faces):
nb = [set() for _ in range(n)]
for f in faces:
for k in range(3):
i, j = f[k], f[(k + 1) % 3]
nb[i].add(j)
nb[j].add(i)
return [sorted(s) for s in nb]
def edge_faces(faces):
"""Map each undirected edge to the list of the faces that hold it."""
m = {}
for t, f in enumerate(faces):
for k in range(3):
i, j = f[k], f[(k + 1) % 3]
m.setdefault((min(i, j), max(i, j)), []).append(t)
return m
def face_adjacency(faces):
"""For each face, the sorted list of the faces that share an edge with it."""
adj = [set() for _ in faces]
for fs in edge_faces(faces).values():
for a in fs:
for b in fs:
if a != b:
adj[a].add(b)
return [sorted(s) for s in adj]
def boundary_vertices(faces):
b = set()
for (i, j), fs in edge_faces(faces).items():
if len(fs) == 1:
b.update((i, j))
return b
def vertex_faces(n, faces):
vf = [[] for _ in range(n)]
for t, f in enumerate(faces):
for i in f:
vf[i].append(t)
return vf
# ---------------------------------------------------------------- face geometry
def face_cross(points, f):
"""cross(b - a, c - a): twice the area times the unit normal."""
a, b, c = (points[i] for i in f)
return cross(sub(b, a), sub(c, a))
def face_area(points, f):
return norm(face_cross(points, f)) / 2
def face_normal(points, f):
return unit(face_cross(points, f))
def centroid(points, f):
a, b, c = (points[i] for i in f)
return tuple((x + y + z) / 3 for x, y, z in zip(a, b, c))
def cot_at(a, b, c):
"""The cotangent of the angle at a in the triangle a, b, c."""
u, v = sub(b, a), sub(c, a)
return dot(u, v) / norm(cross(u, v))
def cotan_weights(points, faces):
"""w_ij = (cot alpha_ij + cot beta_ij) / 2, with alpha and beta the angles opposite the edge ij."""
w = {}
for f in faces:
for k in range(3):
i, j, o = f[k], f[(k + 1) % 3], f[(k + 2) % 3]
e = (min(i, j), max(i, j))
w[e] = w.get(e, 0.0) + cot_at(points[o], points[i], points[j]) / 2
return w
def stiffness_rows(n, weights):
"""The cotangent stiffness matrix C = -L as a list of dict rows: C_ij = -w_ij, C_ii = sum of w_ij."""
C = [dict() for _ in range(n)]
for (i, j), w in weights.items():
C[i][j] = C[i].get(j, 0) - w
C[j][i] = C[j].get(i, 0) - w
C[i][i] = C[i].get(i, 0) + w
C[j][j] = C[j].get(j, 0) + w
return C
def barycentric_area(points, faces):
A = [0.0] * len(points)
for f in faces:
a = face_area(points, f) / 3
for i in f:
A[i] += a
return A
def mixed_area(points, faces):
"""The mixed Voronoi area of Meyer, Desbrun, Schroeder and Barr (2003).
A triangle with no obtuse angle gives each corner its Voronoi part,
(|ij|^2 cot k + |ik|^2 cot j) / 8. An obtuse triangle gives half its area
to the obtuse corner and a quarter to each other corner.
"""
A = [0.0] * len(points)
for f in faces:
P = [points[i] for i in f]
obtuse = [dot_sign(P[k], P[(k + 1) % 3], P[(k + 2) % 3]) < 0 for k in range(3)]
area = face_area(points, f)
for k in range(3):
i, pj, pk, pi = f[k], P[(k + 1) % 3], P[(k + 2) % 3], P[k]
if not any(obtuse):
eij, eik = sub(pj, pi), sub(pk, pi)
A[i] += (dot(eij, eij) * cot_at(pk, pi, pj) + dot(eik, eik) * cot_at(pj, pi, pk)) / 8
else:
A[i] += area / 2 if obtuse[k] else area / 4
return A
def mean_curvature_normal(points, faces, area="mixed"):
"""K_i = (1 / (2 A_i)) sum_j (cot alpha_ij + cot beta_ij)(x_i - x_j), which is 2 H n_i with outward n_i."""
A = mixed_area(points, faces) if area == "mixed" else barycentric_area(points, faces)
w = cotan_weights(points, faces)
K = [[0.0, 0.0, 0.0] for _ in points]
for (i, j), wij in w.items():
d = sub(points[i], points[j])
for c in range(3):
K[i][c] += wij * d[c]
K[j][c] -= wij * d[c]
return [tuple(x / A[i] for x in K[i]) for i in range(len(points))]
def area_gradient(points, faces):
"""The gradient of the total area with respect to each vertex, summed face by face.
For a face with corner i and other corners j, k, the gradient at i is
(cot k (x_i - x_j) + cot j (x_i - x_k)) / 2, where cot j is the cotangent of the angle at j.
"""
g = [[0.0, 0.0, 0.0] for _ in points]
for f in faces:
for k in range(3):
i, j, l = f[k], f[(k + 1) % 3], f[(k + 2) % 3]
pi, pj, pl = points[i], points[j], points[l]
cl, cj = cot_at(pl, pi, pj), cot_at(pj, pi, pl)
for c in range(3):
g[i][c] += (cl * (pi[c] - pj[c]) + cj * (pi[c] - pl[c])) / 2
return [tuple(v) for v in g]
def total_area(points, faces):
return sum(face_area(points, f) for f in faces)
# ---------------------------------------------------------------- dense linear algebra
def identity(n, one=1):
return [[one if i == j else 0 * one for j in range(n)] for i in range(n)]
def transpose(A):
return [list(r) for r in zip(*A)]
def mat_mul(A, B):
Bt = transpose(B)
return [[sum(a * b for a, b in zip(r, c)) for c in Bt] for r in A]
def mat_vec(A, x):
return [sum(a * b for a, b in zip(r, x)) for r in A]
def det3(A):
return dot(A[0], cross(A[1], A[2]))
def solve_dense(A, b):
"""Solve A x = b by Gaussian elimination with partial pivoting. Exact on Fraction input."""
n = len(A)
M = [list(A[i]) + [b[i]] for i in range(n)]
for c in range(n):
p = max(range(c, n), key=lambda r: abs(M[r][c]))
if M[p][c] == 0:
raise ValueError("singular matrix")
M[c], M[p] = M[p], M[c]
for r in range(c + 1, n):
f = M[r][c] / M[c][c]
if f:
for k in range(c, n + 1):
M[r][k] -= f * M[c][k]
x = [0] * n
for r in range(n - 1, -1, -1):
x[r] = (M[r][n] - sum(M[r][k] * x[k] for k in range(r + 1, n))) / M[r][r]
return x
def cholesky(A):
"""The lower triangular L with A = L L^T, for a symmetric positive definite A."""
n = len(A)
L = [[0.0] * n for _ in range(n)]
for j in range(n):
d = A[j][j] - sum(L[j][k] ** 2 for k in range(j))
if d <= 0:
raise ValueError("matrix is not positive definite")
L[j][j] = math.sqrt(d)
for i in range(j + 1, n):
L[i][j] = (A[i][j] - sum(L[i][k] * L[j][k] for k in range(j))) / L[j][j]
return L
def cholesky_solve(L, b):
n = len(L)
y = [0.0] * n
for i in range(n):
y[i] = (b[i] - sum(L[i][k] * y[k] for k in range(i))) / L[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
x[i] = (y[i] - sum(L[k][i] * x[k] for k in range(i + 1, n))) / L[i][i]
return x
def _rotation(theta):
"""c, s of the Jacobi rotation for the cotangent theta of twice its angle."""
t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1))
c = 1 / math.sqrt(1 + t * t)
return c, t * c
def jacobi_eigen(A, tol=1e-15, sweeps=100):
"""Eigenvalues (ascending) and unit eigenvectors of a symmetric matrix, by cyclic Jacobi rotations."""
n = len(A)
a = [[float(x) for x in r] for r in A]
v = identity(n, 1.0)
for _ in range(sweeps):
off = sum(a[i][j] ** 2 for i in range(n) for j in range(i + 1, n))
if off <= tol * tol * sum(a[i][i] ** 2 for i in range(n)) or off == 0:
break
for p in range(n):
for q in range(p + 1, n):
if a[p][q] == 0:
continue
c, s = _rotation((a[q][q] - a[p][p]) / (2 * a[p][q]))
for k in range(n):
akp, akq = a[k][p], a[k][q]
a[k][p], a[k][q] = c * akp - s * akq, s * akp + c * akq
for k in range(n):
apk, aqk = a[p][k], a[q][k]
a[p][k], a[q][k] = c * apk - s * aqk, s * apk + c * aqk
for k in range(n):
vkp, vkq = v[k][p], v[k][q]
v[k][p], v[k][q] = c * vkp - s * vkq, s * vkp + c * vkq
order = sorted(range(n), key=lambda k: a[k][k])
return [a[k][k] for k in order], [[v[i][k] for i in range(n)] for k in order]
def svd3(A, sweeps=60):
"""A = U diag(s) V^T for a 3 x 3 matrix, with s descending and U, V orthogonal (one-sided Jacobi)."""
U = [[float(x) for x in r] for r in A]
V = identity(3, 1.0)
for _ in range(sweeps):
done = True
for p, q in ((0, 1), (0, 2), (1, 2)):
al = sum(U[i][p] ** 2 for i in range(3))
be = sum(U[i][q] ** 2 for i in range(3))
ga = sum(U[i][p] * U[i][q] for i in range(3))
if ga == 0 or abs(ga) <= 1e-15 * math.sqrt(al * be):
continue
done = False
c, s = _rotation((be - al) / (2 * ga))
for M in (U, V):
for i in range(3):
mp, mq = M[i][p], M[i][q]
M[i][p], M[i][q] = c * mp - s * mq, s * mp + c * mq
if done:
break
sig = [math.sqrt(sum(U[i][k] ** 2 for i in range(3))) for k in range(3)]
order = sorted(range(3), key=lambda k: -sig[k])
s = [sig[k] for k in order]
cols = [[U[i][k] for i in range(3)] for k in order]
vcols = [[V[i][k] for i in range(3)] for k in order]
tiny = 1e-13 * max(s[0], 1e-300)
u = [tuple(x / s[k] for x in cols[k]) for k in range(3) if s[k] > tiny]
while len(u) < 3: # complete U where A has a null direction
if not u:
u.append((1.0, 0.0, 0.0))
elif len(u) == 1:
e = min(((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)), key=lambda t: abs(dot(t, u[0])))
u.append(unit(cross(u[0], e)))
else:
u.append(cross(u[0], u[1]))
Um = [[u[k][i] for k in range(3)] for i in range(3)]
Vm = [[vcols[k][i] for k in range(3)] for i in range(3)]
return Um, s, Vm
def best_rotation(S):
"""The rotation R (det 1) that maximizes trace(R S): with S = U diag(s) V^T, R = V diag(1, 1, d) U^T, d = det(V U^T)."""
U, _, V = svd3(S)
d = 1.0 if det3(mat_mul(V, transpose(U))) > 0 else -1.0
return mat_mul(mat_mul(V, [[1.0, 0, 0], [0, 1.0, 0], [0, 0, d]]), transpose(U))
def rotation_matrix(axis, angle):
"""The rotation by angle about the unit vector axis (Rodrigues)."""
x, y, z = unit(axis)
c, s = math.cos(angle), math.sin(angle)
C = 1 - c
return [[c + x * x * C, x * y * C - z * s, x * z * C + y * s],
[y * x * C + z * s, c + y * y * C, y * z * C - x * s],
[z * x * C - y * s, z * y * C + x * s, c + z * z * C]]
# ---------------------------------------------------------------- test meshes
def orient_outward(points, faces):
"""Flip each face of a mesh around the origin so that its normal points away from the origin (exact test)."""
out = []
o = (0, 0, 0)
for f in faces:
a, b, c = (points[i] for i in f)
out.append(tuple(f) if orient3d(a, b, c, o) < 0 else (f[0], f[2], f[1]))
return out
def octahedron():
p = [(1.0, 0.0, 0.0), (-1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, -1.0)]
f = [(0, 2, 4), (2, 1, 4), (1, 3, 4), (3, 0, 4), (2, 0, 5), (1, 2, 5), (3, 1, 5), (0, 3, 5)]
return p, orient_outward(p, f)
def icosahedron():
t = (1 + math.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)]
p = [unit(tuple(float(x) for x in q)) for q in raw]
f = [(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)]
return p, orient_outward(p, f)
def icosphere(level, radius=1.0):
"""The icosahedron with each triangle cut into four `level` times, projected to the sphere."""
p, f = icosahedron()
p = list(p)
for _ in range(level):
mid = {}
def m(i, j):
e = (min(i, j), max(i, j))
if e not in mid:
mid[e] = len(p)
p.append(unit(scale(0.5, add(p[i], p[j]))))
return mid[e]
nf = []
for a, b, c in f:
ab, bc, ca = m(a, b), m(b, c), m(c, a)
nf += [(a, ab, ca), (b, bc, ab), (c, ca, bc), (ab, bc, ca)]
f = nf
return [scale(radius, q) for q in p], f
def cylinder(radius, height, m, k, twisted=False):
"""An open tube of m vertices around and k + 1 rings, axis z, centred at the origin, normals outward.
Plain: each rectangle is cut by the same diagonal. Twisted: ring l is turned by l half steps,
so that each vertex has six neighbours, as in a grid of near-equilateral triangles.
"""
p = []
for l in range(k + 1):
z = height * l / k - height / 2
for s in range(m):
th = 2 * math.pi * (s + (l / 2 if twisted else 0)) / m
p.append((radius * math.cos(th), radius * math.sin(th), z))
f = []
for l in range(k):
for s in range(m):
a, b = l * m + s, l * m + (s + 1) % m
c, d = b + m, a + m
if twisted: # the ring above is turned half a step forward
f += [(a, b, d), (b, c, d)]
else:
f += [(a, b, c), (a, c, d)]
return p, f
def box_mesh(size, div):
"""The closed surface of the box [-a/2, a/2] x [-b/2, b/2] x [-c/2, c/2], each side a grid of div cells.
size = (a, b, c) may hold Fractions, div = (na, nb, nc) are the numbers of cells along each axis.
Each grid cell is cut into two triangles. The normals point out.
"""
index, p, f = {}, [], []
def vid(key):
if key not in index:
index[key] = len(p)
p.append(tuple(size[a] * Fraction(key[a], div[a]) - Fraction(size[a]) / 2 for a in range(3)))
return index[key]
for ax in range(3):
u, w = [a for a in range(3) if a != ax]
for side in (0, div[ax]):
out = 1 if side else -1
eu = [0, 0, 0]
ew = [0, 0, 0]
eu[u], ew[w] = 1, 1
flip = cross(eu, ew)[ax] != out
for s in range(div[u]):
for t in range(div[w]):
q = []
for ds, dt in ((0, 0), (1, 0), (1, 1), (0, 1)):
key = [0, 0, 0]
key[ax], key[u], key[w] = side, s + ds, t + dt
q.append(vid(tuple(key)))
tris = [(q[0], q[1], q[2]), (q[0], q[2], q[3])]
f += [(a, c, b) if flip else (a, b, c) for a, b, c in tris]
return p, f
def to_float(points):
return [tuple(float(x) for x in q) for q in points]
test_laplacian_surface_editing.py 100 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/laplacian-surface-editing/. The authors are listed in prov/44KQTR.jsonl.
import math
import random
from fractions import Fraction
import pytest
from laplacian_surface_editing import energy, laplacian_edit, neighbours, similarity_rows
from mx1mesh import add, dot, mat_vec, norm, rotation_matrix, sub, to_float
def patch(m, amp=Fraction(1, 2)):
"""The grid of (m + 1)^2 points on [-1, 1]^2 with the bump z = amp (1 - x^2)(1 - y^2), cut into triangles."""
p = []
for a in range(m + 1):
for b in range(m + 1):
x, y = Fraction(2 * a, m) - 1, Fraction(2 * b, m) - 1
p.append((x, y, amp * (1 - x * x) * (1 - y * y)))
f = []
for a in range(m):
for b in range(m):
i = a * (m + 1) + b
f += [(i, i + m + 1, i + m + 2), (i, i + m + 2, i + 1)]
return p, f
def border(m):
return [a * (m + 1) + b for a in range(m + 1) for b in range(m + 1) if a in (0, m) or b in (0, m)]
@pytest.mark.parametrize("m, rotations", [(4, False), (3, True)])
def test_the_unconstrained_solve_returns_the_input(m, rotations) -> None:
p, f = patch(m)
corners = {k: p[k] for k in (0, m, (m + 1) * m)} # handles left at their rest positions
assert laplacian_edit(p, f, corners, rotations=rotations) == p # exact, with Fraction
p, f = patch(8)
p = to_float(p)
q = laplacian_edit(p, f, {k: p[k] for k in (0, 8, 72)}, rotations=rotations) # the same in floating point
assert max(norm(sub(a, b)) for a, b in zip(q, p)) < 1e-12
def test_without_a_handle_the_solution_is_not_unique() -> None:
p, f = patch(3)
with pytest.raises(ValueError): # q and q + t give the same Laplacian coordinates
laplacian_edit(p, f, {})
@pytest.mark.parametrize("rotations", [False, True])
def test_a_translation_of_the_handles_moves_the_whole_mesh(rotations) -> None:
p, f = patch(3)
t = (Fraction(3, 10), Fraction(-1, 5), Fraction(1))
handles = {k: add(p[k], t) for k in (0, 3, 12)}
assert laplacian_edit(p, f, handles, rotations=rotations) == [add(x, t) for x in p]
def test_the_similarity_of_the_rest_ring_is_the_identity() -> None:
p, f = patch(3)
nb = neighbours(len(p), f)
for i in range(len(p)):
S = similarity_rows(p, i, nb[i])
for q, expect in ((p, (1, 0, 0, 0)), ([add(x, (5, -1, 2)) for x in p], (1, 0, 0, 0)),
([tuple(2 * c for c in x) for x in p], (2, 0, 0, 0))):
assert tuple(sum(g * q[j][c] for (j, c), g in row.items()) for row in S) == expect
@pytest.mark.parametrize("rotations", [False, True])
def test_the_solve_is_a_least_squares_minimum(rotations) -> None:
rng = random.Random(7)
p, f = patch(6)
p = to_float(p)
R = rotation_matrix((1, 0, 0), 0.5)
handles = {k: tuple(mat_vec(R, p[k])) for k in border(6)}
q = laplacian_edit(p, f, handles, rotations=rotations)
e = energy(p, f, q, handles, rotations=rotations)
for _ in range(10):
q2 = [tuple(x + rng.gauss(0, 1e-3) for x in v) for v in q]
assert energy(p, f, q2, handles, rotations=rotations) >= e - 1e-12
def test_rotations_keep_the_detail() -> None:
m = 8
p, f = patch(m)
p = to_float(p)
centre = (m // 2) * (m + 1) + m // 2
errors = {}
for th in (0.1, 0.5, math.pi / 2):
R = rotation_matrix((1, 0, 0), th)
handles = {k: tuple(mat_vec(R, p[k])) for k in border(m)}
target = [tuple(mat_vec(R, x)) for x in p]
for rotations in (False, True):
q = laplacian_edit(p, f, handles, rotations=rotations)
errors[th, rotations] = max(norm(sub(a, b)) for k, (a, b) in enumerate(zip(q, target)) if k not in handles)
if th == math.pi / 2: # height of the bump along the turned normal: 0.5 at rest
h = dot(q[centre], mat_vec(R, (0, 0, 1)))
assert (abs(h) < 1e-9) if not rotations else (abs(h - 0.5) < 1e-3)
assert errors[0.1, True] < 0.002 < 0.04 < errors[0.1, False]
assert errors[0.5, True] < 0.04 < 0.2 < errors[0.5, False]
assert errors[math.pi / 2, True] < errors[math.pi / 2, False]
History
Differential coordinates for meshes go back to Taubin's work on mesh smoothing in the 1990s, where the Laplacian of the positions acted as a filter. In 2004 Lipman, Sorkine, Cohen-Or, Levin, Rössl and Seidel edited meshes through these coordinates and estimated local rotations from the result, and in the same year Sorkine, Cohen-Or, Lipman, Alexa, Rössl and Seidel gave Laplacian surface editing, with the linearized similarity at each vertex built into one least squares solve. Botsch and Sorkine compared the linear deformation methods in 2008 and showed that none of them handles large rotations well, which led to nonlinear methods such as as-rigid-as-possible deformation.
References
- Olga Sorkine, Daniel Cohen-Or, Yaron Lipman, Marc Alexa, Christian Rössl and Hans-Peter Seidel, Laplacian surface editing, Proceedings of the Eurographics/ACM SIGGRAPH Symposium on Geometry Processing, 2004, 175 to 184, the Laplacian coordinates with uniform weights, the least squares energy with soft handle constraints, and the implicit transformation of each vertex as a linearized similarity fit to its ring
- Yaron Lipman, Olga Sorkine, Daniel Cohen-Or, David Levin, Christian Rössl and Hans-Peter Seidel, Differential coordinates for interactive mesh editing, Proceedings of Shape Modeling International, 2004, 181 to 190, editing with differential coordinates and the estimate of local rotations from the edited surface
- Mario Botsch and Olga Sorkine, On linear variational surface deformation methods, IEEE Transactions on Visualization and Computer Graphics 14(1), 2008, 213 to 230, the comparison of the linear deformation methods, and their trouble with large rotations
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 | W2 basic |
|
Tag 44KQTR Edit this page History Report an error Markdown