Algorithm Search⌘K

Algorithmadvanced

Curvature tensor estimation

Also called normal cycle curvature estimation, Taubin curvature tensor.

Estimates principal curvatures and directions at mesh vertices, by Taubin's average of edge normal curvatures or by Cohen-Steiner and Morvan's tensor of dihedral angles.

Time
Θ(n) worst
Space
Θ(n) extra
Where
n = the number of vertices and faces of the mesh
Properties
deterministicnot exactiterative
Origin
Gabriel Taubin, David Cohen Steiner, Jean Marie Morvan, 1995

Curvature tensor estimation finds, at each vertex of a triangle mesh, the two principal curvatures k1≥k2k_1 \ge k_2 and the two principal directions of the surface that the mesh approximates. The mean curvature gives only 12(k1+k2)\frac{1}{2}(k_1 + k_2). The tensor also tells in which direction the surface bends most, which is what feature lines, curvature-aligned remeshing and shape analysis need. This page shows two methods. Taubin (1995) takes a normal curvature from each edge at the vertex, averages these samples as a tensor in the tangent plane, and corrects its eigenvalues by a fixed linear map. Cohen-Steiner and Morvan (2003) sum, over the edges in a region around the vertex, the dihedral angle times the length times the outer product of the edge direction, and divide by the area. Neither method is exact on a general mesh. Both are exact in known cases, which the correctness section states.

In plain words

Stand on a curved surface and walk a short step in some direction. The ground drops away from your feet by some amount. If it drops a lot, the surface bends strongly in that direction. On a ball it drops the same amount in every direction. On a pipe it drops when you walk around the pipe, not when you walk along it.

On a mesh, each edge from a corner is a short step. The first method measures how much the ground drops along each edge, writes down that number with the direction of the edge, and finds the two directions in which the bending is largest and smallest. The second method looks at the folds between neighbouring triangles. A sharp fold across a direction means strong bending across it. Adding up the folds near a corner gives the same two directions and their bending.

The problem

The input is a triangle polygon mesh with vertex positions x1,…,xnx_1, \ldots, x_n that sample a smooth surface, and optionally a unit normal NiN_i at each vertex. The output, at each inner vertex ii, is k1≥k2k_1 \ge k_2 and unit tangent vectors d1⊥d2d_1 \perp d_2, estimates of the principal curvatures and principal directions at xix_i. The sign convention: a curvature is positive where the surface bends away from NiN_i, so a sphere with outward normals has k1=k2=1/rk_1 = k_2 = 1/r. A vertex on the border, or whose region meets the border, gets no estimate.

The algorithm

Taubin's method:

  1. TAUBIN-CURVATURE(x[1 .. n], faces)
  2. 1N_i ← unit(Σ over faces f at i of area(f) n_f) for each vertex i
  3. 2for each inner vertex i do
  4. 3for each neighbour j of i do
  5. 4T_ij ← unit((I − N_i N_iᵀ)(x_i − x_j)); κ_ij ← 2 N_i·(x_i − x_j) / |x_i − x_j|²
  6. 5w_ij ← total area of the faces that hold the edge ij
  7. 6M_i ← Σ_j w_ij κ_ij T_ij T_ijᵀ / Σ_j w_ij
  8. 7m1 ≥ m2 ← eigenvalues of M_i in the tangent plane, with unit eigenvectors d1, d2
  9. 8k1 ← 3m1 − m2; k2 ← 3m2 − m1
  10. return (k1, k2, d1, d2) for each inner vertex

Line L4 is the curvature of the circle through xix_i and xjx_j that is tangent to the plane normal to NiN_i at xix_i. Its direction TijT_{ij} is the edge projected to that plane. Line L6 averages the samples as a 2×22 \times 2 symmetric tensor in the tangent plane, and L7 finds its eigenvalues in closed form. Line L8 is the correction. If the samples were the exact normal curvatures κ(θ)=k1cos⁡2θ+k2sin⁡2θ\kappa(\theta) = k_1\cos^2\theta + k_2\sin^2\theta spread evenly over all directions, the average would have the eigenvalues 3k1+k28\frac{3k_1 + k_2}{8} and k1+3k28\frac{k_1 + 3k_2}{8}, and L8 inverts this map. The code uses the sign convention of the problem statement.

The edge tensor of Cohen-Steiner and Morvan replaces lines L3 to L6. For a region BB around vertex ii,

Tˉ(B)=1∣B∣∑eβ(e) ∣e∩B∣ eˉ eˉ⊤,\bar T(B) = \frac{1}{|B|}\sum_{e} \beta(e)\,|e \cap B|\,\bar e\,\bar e^{\top},

where β(e)\beta(e) is the signed angle between the normals of the two faces at the edge ee, positive at a convex edge, ∣e∩B∣|e \cap B| is the length of the edge inside BB, and eˉ\bar e is the unit edge direction. The code takes for BB the mixed Voronoi cell of the vertex, which holds half of each edge at the vertex, or with rings = r the union of the cells of the vertices at most rr edges away. A fold along eˉ\bar e bends the surface across eˉ\bar e, so the eigenvalue of the eigenvector eˉ\bar e is the curvature in the tangent direction Ni×eˉN_i \times \bar e. The two directions swap. The sign of β\beta comes from an exact orientation test on the four corners of the two faces, so it never flips by rounding.

Example

A sphere. On icospheres of radius r=2r = 2, where k1=k2=0.5k_1 = k_2 = 0.5, the largest error of k1k_1 and k2k_2 over all vertices is, at 162, 642 and 2562 vertices:

method 162 642 2562
Taubin 0.0520.052 0.1040.104 0.1210.121
edge tensor, the cell of the vertex 0.0360.036 0.0310.031 0.0300.030
edge tensor, the cells of the vertex and its neighbours 0.0310.031 0.01150.0115 0.00610.0061

Taubin's error does not go down. Its mean 12(k1+k2)\frac{1}{2}(k_1 + k_2) is good, within 0.0080.008 with the normals of the mesh at 2562 vertices. With the true normals the mean is exact at every vertex, and both values are exact at the 12 vertices of valence 5. The error is in the split between k1k_1 and k2k_2 at the vertices of valence 6, whose six edge directions are not evenly spaced. The edge tensor on one cell does not converge either. On the larger region it does, at about first order in the edge length.

A cylinder. On a cylinder of radius 1 with mm columns of rectangles, each cut by the same diagonal into two right triangles, the edge tensor gives exactly k1=π/msin⁡(π/m)k_1 = \frac{\pi/m}{\sin(\pi/m)} around the axis and k2=0k_2 = 0 along it: 1.026171.02617, 1.006451.00645, 1.001611.00161, 1.000401.00040 for m=8,16,32,64m = 8, 16, 32, 64. Taubin's method gives 1.2211.221 and −0.221-0.221 at m=8m = 8, and 1.245001.24500 and −0.24500-0.24500 at m=64m = 64, near the limit 12±53≈1.2454,−0.2454\frac{1}{2} \pm \frac{\sqrt 5}{3} \approx 1.2454, -0.2454. The mean is right, and the split is wrong at every resolution, because the six edge directions of each vertex are 0°, 45° and 90° (each two times), not evenly spaced. On a twisted cylinder, where each ring of vertices is turned by half a column so that the six directions are nearly 60° apart, Taubin gives k1=1.00000k_1 = 1.00000 and k2=0.00979k_2 = 0.00979, 0.002420.00242, 0.000600.00060, 0.000150.00015 for m=8,16,32,64m = 8, 16, 32, 64.

A saddle. On the grid of spacing 1/k1/k on z=12(x2−y2)z = \frac{1}{2}(x^2 - y^2), cut by the diagonal of direction (1,1)(1, 1), the true values at the origin are ±1\pm 1. At k=4,8,16,32k = 4, 8, 16, 32, Taubin gives ±1.3128\pm 1.3128, ±1.3281\pm 1.3281, ±1.3320\pm 1.3320, ±1.3330\pm 1.3330, which tends to ±43\pm\frac{4}{3}, and the edge tensor on one cell gives ±0.9574\pm 0.9574, ±0.9890\pm 0.9890, ±0.9972\pm 0.9972, ±0.9993\pm 0.9993. Both put k1k_1 along the yy axis, where the surface bends down, away from the upward normal.

Correctness

Neither method is exact on a general mesh. The proof file shows these facts:

  • The edge samples. On a circle of radius ρ\rho through xix_i with center xi−ρNix_i - \rho N_i, line L4 gives exactly 1/ρ1/\rho. On a smooth surface with the true normal, it gives the normal curvature in the direction TijT_{ij} up to O(∣xi−xj∣)O(|x_i - x_j|).
  • Exact for balanced directions. If the samples are exact normal curvatures and the weighted directions satisfy ∑jwje2iθj=∑jwje4iθj=0\sum_j w_j e^{2\mathrm{i}\theta_j} = \sum_j w_j e^{4\mathrm{i}\theta_j} = 0, then lines L6 to L8 return the exact k1k_1, k2k_2 and directions. Evenly spaced directions with equal weights satisfy this for every number of directions except 1, 2 and 4. Four do not: for k1=1k_1 = 1, k2=0k_2 = 0 and directions on the principal axes, the output is 32\frac{3}{2} and −12-\frac{1}{2}.
  • The mean is always the weighted mean of the samples. 12(k1+k2)=∑jwjκij/∑jwj\frac{1}{2}(k_1 + k_2) = \sum_j w_j\kappa_{ij} / \sum_j w_j, because each TijTij⊤T_{ij}T_{ij}^\top has trace 1. So on a sphere with the true normals the mean is exact on every mesh.
  • A bias that refinement keeps. On the grid with one diagonal, the limits are ±43\pm\frac{4}{3} on the saddle and 12±53\frac{1}{2} \pm \frac{\sqrt 5}{3} on the cylinder, as the example measures.
  • The edge tensor on a cylinder. The closed form above holds for every region made of whole cells away from the border.
  • Exact signs and rigid motions. The sign of each dihedral angle is exact. A rotation and a translation of the mesh do not change k1k_1 and k2k_2, and rotate the directions.

Cohen-Steiner and Morvan prove an error bound for the edge tensor on restricted Delaunay triangulations, when the region is large compared with the triangles. The page does not prove that bound. The convergence on the sphere is measured, not proved. The method stops: every loop is over a finite set, and the eigenvalues of a 2×22 \times 2 symmetric matrix have a closed form.

Proof: Taubin's edge samples are exact on circles and consistent on smooth surfaces, his eigenvalue step is exact for balanced directions and biased otherwise, and the edge tensor has a closed form on a cylinderfull

Setup. Fix an inner vertex ii with position xix_i, unit normal NN, and neighbours jj. For a neighbour jj, let dj=xi−xjd_j = x_i - x_j, let TjT_j be the unit vector along the projection of djd_j to the plane normal to NN, and let κj=2 N⋅dj/∣dj∣2\kappa_j = 2\,N \cdot d_j / |d_j|^2. The weights wj>0w_j > 0 sum to 1. In a basis E1,E2E_1, E_2 of the tangent plane, write Tj=(cos⁡θj,sin⁡θj)T_j = (\cos\theta_j, \sin\theta_j). The algorithm forms M=∑jwjκjTjTj⊤M = \sum_j w_j\kappa_j T_jT_j^\top, takes its eigenvalues m1≥m2m_1 \ge m_2, and returns k1=3m1−m2k_1 = 3m_1 - m_2 and k2=3m2−m1k_2 = 3m_2 - m_1. The sign convention is: the curvature is positive where the surface bends away from NN. Each loop of the pseudocode runs over a finite set, and the eigenvalues of a 2×22 \times 2 symmetric matrix have a closed form, so the algorithm stops.

Lemma 1 (exact on a circle). If xjx_j lies on a circle of radius ρ\rho through xix_i whose center is xi−ρNx_i - \rho N, then κj=1/ρ\kappa_j = 1/\rho. So on a sphere of radius rr with the true normals, every κj=1/r\kappa_j = 1/r.

Proof. The center is c=xi−ρNc = x_i - \rho N, and ∣xj−c∣2=ρ2|x_j - c|^2 = \rho^2. Write xj−c=−dj+ρNx_j - c = -d_j + \rho N. Then ∣dj∣2−2ρ N⋅dj+ρ2=ρ2|d_j|^2 - 2\rho\,N \cdot d_j + \rho^2 = \rho^2, so N⋅dj=∣dj∣2/(2ρ)N \cdot d_j = |d_j|^2 / (2\rho) and κj=1/ρ\kappa_j = 1/\rho. On a sphere with the outward normal, every point of the sphere is on the great circle through xix_i and that point, whose center is xi−rNx_i - rN. □\square

Lemma 2 (consistent on a smooth surface). Let the vertices lie on a smooth surface with principal curvatures k1,k2k_1, k_2 at xix_i, and let NN be the true normal. Then κj=κn(Tj)+O(∣dj∣)\kappa_j = \kappa_n(T_j) + O(|d_j|), where κn(T)=k1cos⁡2θ+k2sin⁡2θ\kappa_n(T) = k_1\cos^2\theta + k_2\sin^2\theta is the normal curvature in the direction TT at the angle θ\theta from the first principal direction.

Proof. Put xix_i at the origin, NN on the zz axis, and the principal directions on the xx and yy axes. Near xix_i the surface is the graph z=−12(k1x2+k2y2)+O(ρ3)z = -\frac{1}{2}(k_1x^2 + k_2y^2) + O(\rho^3) with ρ2=x2+y2\rho^2 = x^2 + y^2, and the minus sign is the sign convention. For xj=(x,y,z)x_j = (x, y, z), N⋅dj=−z=12(k1x2+k2y2)+O(ρ3)N \cdot d_j = -z = \frac{1}{2}(k_1x^2 + k_2y^2) + O(\rho^3) and ∣dj∣2=ρ2+O(ρ4)|d_j|^2 = \rho^2 + O(\rho^4). So κj=(k1x2+k2y2)/ρ2+O(ρ)\kappa_j = (k_1x^2 + k_2y^2)/\rho^2 + O(\rho). The direction of (x,y)(x, y) is ±Tj\pm T_j, and the sign does not change cos⁡2\cos^2 and sin⁡2\sin^2. □\square

Lemma 3 (the continuous average). For κ(θ)=k1cos⁡2θ+k2sin⁡2θ\kappa(\theta) = k_1\cos^2\theta + k_2\sin^2\theta and t(θ)=(cos⁡θ,sin⁡θ)t(\theta) = (\cos\theta, \sin\theta),

12π∫02πκ(θ) t(θ) t(θ)⊤dθ=(3k1+k2800k1+3k28).\frac{1}{2\pi}\int_0^{2\pi}\kappa(\theta)\,t(\theta)\,t(\theta)^\top d\theta = \begin{pmatrix} \frac{3k_1 + k_2}{8} & 0 \\ 0 & \frac{k_1 + 3k_2}{8} \end{pmatrix}.

So if MM equals this average, then 3m1−m2=k13m_1 - m_2 = k_1 and 3m2−m1=k23m_2 - m_1 = k_2 (with m1m_1 the entry for k1≥k2k_1 \ge k_2), and the eigenvectors are the principal directions.

Proof. The averages of cos⁡4\cos^4, cos⁡2sin⁡2\cos^2\sin^2 and sin⁡4\sin^4 over a period are 38\frac{3}{8}, 18\frac{1}{8} and 38\frac{3}{8}, and the averages of cos⁡3sin⁡\cos^3\sin and cos⁡sin⁡3\cos\sin^3 are 0. The diagonal entries are 38k1+18k2\frac{3}{8}k_1 + \frac{1}{8}k_2 and 18k1+38k2\frac{1}{8}k_1 + \frac{3}{8}k_2. Then 3(38k1+18k2)−(18k1+38k2)=k13(\frac{3}{8}k_1 + \frac{1}{8}k_2) - (\frac{1}{8}k_1 + \frac{3}{8}k_2) = k_1, and the other formula follows the same way. □\square

Theorem 1 (balanced directions are exact). Let κj=κn(Tj)\kappa_j = \kappa_n(T_j) for every jj. If the weighted directions satisfy

∑jwje2iθj=0and∑jwje4iθj=0,\sum_j w_j e^{2\mathrm{i}\theta_j} = 0 \quad\text{and}\quad \sum_j w_j e^{4\mathrm{i}\theta_j} = 0,

then MM is the continuous average of Lemma 3, so k1,k2k_1, k_2 and the principal directions are exact. In general, without the two conditions, m1+m2=∑jwjκjm_1 + m_2 = \sum_j w_j\kappa_j, so 12(k1+k2)=∑jwjκj\frac{1}{2}(k_1 + k_2) = \sum_j w_j\kappa_j is the weighted mean of the samples.

Proof. Let ϕ\phi be the angle of the first principal direction, H=12(k1+k2)H = \frac{1}{2}(k_1 + k_2) and D=12(k1−k2)D = \frac{1}{2}(k_1 - k_2). Then κ(θ)=H+Dcos⁡(2θ−2ϕ)\kappa(\theta) = H + D\cos(2\theta - 2\phi) and t t⊤=12I+12R(2θ)t\,t^\top = \frac{1}{2}I + \frac{1}{2}R(2\theta) with R(ψ)=(cos⁡ψsin⁡ψsin⁡ψ−cos⁡ψ)R(\psi) = \begin{pmatrix}\cos\psi & \sin\psi \\ \sin\psi & -\cos\psi\end{pmatrix}. The product is

κ t t⊤=12H I+12H R(2θ)+12Dcos⁡(2θ−2ϕ) I+14D (R(4θ−2ϕ)+R(2ϕ)),\kappa\,t\,t^\top = \tfrac{1}{2}H\,I + \tfrac{1}{2}H\,R(2\theta) + \tfrac{1}{2}D\cos(2\theta - 2\phi)\,I + \tfrac{1}{4}D\,\big(R(4\theta - 2\phi) + R(2\phi)\big),

where the last term uses cos⁡(α)R(β)=12(R(β+α)+R(β−α))\cos(\alpha)R(\beta) = \frac{1}{2}(R(\beta + \alpha) + R(\beta - \alpha)), which holds entry by entry by the product formulas for cos⁡\cos and sin⁡\sin. Each entry of R(2θ)R(2\theta), R(4θ−2ϕ)R(4\theta - 2\phi) and cos⁡(2θ−2ϕ)\cos(2\theta - 2\phi) is a real part or an imaginary part of a constant times e2iθe^{2\mathrm{i}\theta} or e4iθe^{4\mathrm{i}\theta}. Under the two conditions, the weighted sums of these terms vanish, and M=12H I+14D R(2ϕ)M = \frac{1}{2}H\,I + \frac{1}{4}D\,R(2\phi). The continuous average has the same form, because the averages of e2iθe^{2\mathrm{i}\theta} and e4iθe^{4\mathrm{i}\theta} over a period are 0. So MM equals the matrix of Lemma 3. For the trace: tr⁡(TjTj⊤)=1\operatorname{tr}(T_jT_j^\top) = 1, so m1+m2=tr⁡M=∑jwjκjm_1 + m_2 = \operatorname{tr} M = \sum_j w_j\kappa_j, and k1+k2=2(m1+m2)k_1 + k_2 = 2(m_1 + m_2). □\square

Corollary 1. For p≥5p \ge 5 equally spaced directions with equal weights, the two sums are sums of pp-th roots of unity raised to the power 2 or 4, which are 0 because pp does not divide 2 or 4. So the estimate is exact for exact samples. For p=4p = 4, ∑e4iθj=4e4iθ0≠0\sum e^{4\mathrm{i}\theta_j} = 4e^{4\mathrm{i}\theta_0} \ne 0, and the estimate is not exact: with k1=1k_1 = 1, k2=0k_2 = 0 and directions along the principal axes, the samples are 1,0,1,01, 0, 1, 0, M=diag⁡(12,0)M = \operatorname{diag}(\frac{1}{2}, 0), and the output is k1=32k_1 = \frac{3}{2}, k2=−12k_2 = -\frac{1}{2}.

Corollary 2 (the sphere). On a sphere of radius rr with the true normals, every κj=1/r\kappa_j = 1/r by Lemma 1, so k1+k2=2/rk_1 + k_2 = 2/r exactly at every vertex, for every mesh. At a vertex with 5 equally spaced neighbour directions and equal weights, such as the 12 vertices of valence 5 of an icosphere, k1=k2=1/rk_1 = k_2 = 1/r exactly.

Theorem 2 (a bias that refinement does not remove). On the grid where each square is cut by the diagonal of direction (1,1)(1, 1), every inner vertex has six neighbours, in the directions 0°,45°,90°,180°,225°,270°0°, 45°, 90°, 180°, 225°, 270°. Up to sign, these are the three directions 0°,45°,90°0°, 45°, 90°, each one two times. All faces have the same area and each inner edge is in two faces, so all weights are equal. When the grid is refined on a smooth surface with this pattern in the tangent plane, the output tends to the value for exact samples (Lemma 2), which is not (k1,k2)(k_1, k_2) in general:

  • On the saddle z=12(x2−y2)z = \frac{1}{2}(x^2 - y^2) at the origin, the principal axes are the grid axes, and the samples tend to 1,−1,1,−11, -1, 1, -1 on the axes (with the sign convention, k1=1k_1 = 1 along yy) and 0,00, 0 on the diagonals. Then M=16diag⁡(2,−2)M = \frac{1}{6}\operatorname{diag}(2, -2) in the frame of yy and xx, so m1,2=±13m_{1,2} = \pm\frac{1}{3} and k1,2=±43k_{1,2} = \pm\frac{4}{3}, not ±1\pm 1.
  • On a cylinder of radius 1 with square cells, the samples tend to 11 around, 00 along the axis and 12\frac{1}{2} on the diagonals. Then 6M=2diag⁡(1,0)+2⋅12⋅12(1111)6M = 2\operatorname{diag}(1, 0) + 2 \cdot \frac{1}{2} \cdot \frac{1}{2}\begin{pmatrix}1 & 1\\ 1 & 1\end{pmatrix}, with eigenvalues of MM equal to 14±512\frac{1}{4} \pm \frac{\sqrt 5}{12}. So k1,2→12±53≈1.245,−0.245k_{1,2} \to \frac{1}{2} \pm \frac{\sqrt 5}{3} \approx 1.245, -0.245, not 11 and 00. The mean 12(k1+k2)=12\frac{1}{2}(k_1 + k_2) = \frac{1}{2} is right, as Theorem 1 says.

Proof. The directions are fixed by the grid, the weights are equal because every edge lies in two faces of the same area, and by Lemma 2 the samples converge to the normal curvatures in these directions. MM is continuous in the samples, and the eigenvalues of a symmetric matrix are continuous in its entries. The two computations are direct. □\square

The tests check Corollary 1, Corollary 2, the two limits of Theorem 2 within 0.010.01, and the twisted cylinder, where every vertex has six near-equal directions, so that the error tends to 0.

Theorem 3 (the edge tensor on a cylinder). Take the cylinder of radius rr with mm columns and rows of height hh, each rectangle cut by the same diagonal, and let BB be the mixed cell of an inner vertex, or the union of the cells of the vertices at most r′r' edges away that does not meet the border. Then the edge tensor, restricted to the tangent plane, has the eigenvalue π/mrsin⁡(π/m)\frac{\pi/m}{r\sin(\pi/m)} along the axis and 00 around the axis. So the method returns k1=π/mrsin⁡(π/m)k_1 = \frac{\pi/m}{r\sin(\pi/m)} in the direction around the axis and k2=0k_2 = 0 along the axis.

Proof. The rectangles are planar, so the diagonals and the ring edges lie between two faces in one plane, with β=0\beta = 0. A vertical edge lies between two columns, whose planes meet at the angle 2π/m2\pi/m, and the edge is convex, so β=2π/m\beta = 2\pi/m. Each cell holds half of each vertical edge at its vertex, and each vertex has two of them, so a cell adds 2⋅2πm⋅h2 z^z^⊤=2πhmz^z^⊤2 \cdot \frac{2\pi}{m}\cdot\frac{h}{2}\,\hat z\hat z^\top = \frac{2\pi h}{m}\hat z\hat z^\top. Every face is a right triangle with legs c=2rsin⁡(π/m)c = 2r\sin(\pi/m) and hh, and each vertex is the right-angle corner of 2 of its 6 faces, No triangle is obtuse, so the mixed cell is the Voronoi cell. The circumcenter of a right triangle is the midpoint of its hypotenuse, so the right-angle corner gets half of the area 12ch\frac{1}{2}ch and each other corner gets a quarter. A vertex gets 2⋅14ch+4⋅18ch=ch2 \cdot \frac{1}{4}ch + 4 \cdot \frac{1}{8}ch = ch. A region of bb cells gives b 2πh/mb chz^z^⊤=π/mrsin⁡(π/m)z^z^⊤\frac{b\,2\pi h/m}{b\,ch}\hat z\hat z^\top = \frac{\pi/m}{r\sin(\pi/m)}\hat z\hat z^\top. Its eigenvector z^\hat z has the eigenvalue above, and the tangent direction around the axis has the eigenvalue 0. The curvature across z^\hat z is in the direction N×z^N \times \hat z, around the axis. □\square

As m→∞m \to \infty, k1→1/rk_1 \to 1/r, with the relative error xsin⁡x−1≈x2/6\frac{x}{\sin x} - 1 \approx x^2/6 for x=π/mx = \pi/m. For general meshes, Cohen-Steiner and Morvan bound the error of the edge tensor over BB for restricted Delaunay triangulations of a smooth surface when BB is large compared with the triangles. The code does not prove that bound. The tests measure it on icospheres: with BB the cells of a vertex and its neighbours, the largest error of k1,k2k_1, k_2 on the sphere of radius 2 falls from 0.0310.031 at 162 vertices to 0.0120.012 at 642 vertices.

Lemma 4 (exact signs). The sign of β\beta comes from the sign of det⁡(b−a,c−a,p−a)\det(b - a, c - a, p - a), where a,b,ca, b, c are the corners of one face and pp the far corner of the other. The code converts the float coordinates to fractions, which is exact, and evaluates the determinant exactly. So a convex edge never gets a negative β\beta from a rounding error, and an edge between two coplanar faces gets β=0\beta = 0.

Lemma 5 (rigid motions). If every position is mapped by x↦Rx+tx \mapsto Rx + t with RR a rotation, then both methods return the same k1,k2k_1, k_2, and the directions are mapped by RR.

Proof. The normals, the face areas, the samples κj\kappa_j and the dihedral angles depend only on differences of positions, dot products and cross products, and a rotation keeps dot products and maps cross products to cross products. The determinant of Lemma 4 is unchanged by a rotation. The tangent basis is a different basis of the rotated plane, but the eigenvalues do not depend on the basis, and the eigenvectors are mapped by RR. □\square

Complexity

Line L1 visits each face once. For each vertex, the loop of L3 to L5 walks the faces at the vertex and adds each face area to the two edges at the vertex that it holds, with a table indexed by the neighbour, so it costs time proportional to the degree. The degrees sum to twice the number of edges, and each edge is in one or two faces, so there are at most 3 edges per face. The total time is Θ(n)\Theta(n) on the real RAM, with nn the number of vertices and faces, and the extra space is Θ(n)\Theta(n) for the normals and the tables. The edge tensor costs Θ(n)\Theta(n) for one cell per vertex, and O(ns)O(ns) when each region holds at most ss vertices.

Properties

  • Not exact. Both methods only approximate the curvature, and the error depends on the shape of the triangles, not only on their size.
  • Taubin's mean is robust. The trace is a weighted mean of the samples, and only the split between k1k_1 and k2k_2 depends on the spacing of the edge directions.
  • Local. Taubin's method and the one-cell edge tensor use only the first ring of each vertex. A larger region trades detail for stability.
  • Invariant under rigid motions. The values do not change under rotations and translations. A uniform scale by ss divides them by ss.
  • Signed. At a concave vertex both curvatures are negative, and at a saddle they have opposite signs.

Variants and improvements

  • Larger regions. Alliez, Cohen-Steiner, Devillers, Lévy and Desbrun average the edge tensor over a disk of fixed geodesic radius, which smooths noise and makes the directions stable enough to trace lines of curvature.
  • Per-face tensors. Rusinkiewicz (2004) fits a second fundamental form on each face from the differences of the vertex normals, then moves the face tensors to the vertex frames and averages them.
  • Fitting. One can fit a quadric or a higher-order polynomial height function to the neighbours in a local frame, by least squares, and read the curvatures from its coefficients. Goldfeather and Interrante (2004) fit a cubic that also uses the normals.
  • From the mean and Gaussian curvatures. k1,2=H±H2−Kk_{1,2} = H \pm \sqrt{H^2 - K}, with HH from the discrete mean curvature and KK from the angle defect. This gives no directions.

When to use it

Use the edge tensor over a region of a few rings when the directions matter, as for curvature-aligned remeshing, lines of curvature or segmentation, and when the mesh is dense compared with the features. Use Taubin's method when speed and simplicity count more than accuracy, and on meshes whose vertices have well-spread edge directions, such as the output of isotropic remeshing. Use a fitting method on noisy scans or when higher derivatives are needed.

Pitfalls

  • Grid meshes. On a regular grid with one diagonal, Taubin's split between k1k_1 and k2k_2 is wrong by a fixed amount however fine the grid, as the cylinder and the saddle show.
  • The region is too small. The edge tensor over one cell need not converge. Use a region that holds several rings.
  • The swap of the directions. The edge tensor's eigenvector eˉ\bar e is the direction of no bending for its eigenvalue. Reporting eˉ\bar e as the direction of that curvature turns the result by 90°.
  • The sign of the normal. If the faces are not consistently oriented, the normals and so the signs of the curvatures flip from vertex to vertex. Orient the mesh first.
  • Dihedral signs from floats. Near-flat edges can get the wrong sign of β\beta from rounding. Decide the sign with an exact orientation test.
  • The border. A vertex on the border has no full ring of edges, and the estimates there are biased. Skip it or use a fitting method.

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.

curvature_tensor_estimation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/curvature-tensor-estimation/. The authors are listed in prov/TJZ7S2.jsonl.

"""Principal curvatures and directions at the vertices of a triangle mesh.

taubin_curvature follows Taubin (ICCV 1995). At each vertex it samples a
normal curvature along each edge, kappa_ij = 2 N.(x_i - x_j) / |x_i - x_j|^2,
averages kappa_ij T T^T over the edge directions T in the tangent plane, and
reads k1 = 3 m1 - m2, k2 = 3 m2 - m1 from the eigenvalues m1 >= m2 of the
average. The sign is chosen so that a sphere with outward normals has
positive curvature.

edge_curvature follows Cohen-Steiner and Morvan (SoCG 2003). It sums
beta(e) |e cap B| e e^T over the edges, with beta the signed dihedral angle,
and divides by the area of a region B around the vertex. Here B is the mixed
Voronoi cell of the vertex, and with rings = r also the cells of the vertices
at most r edges away. Each cell holds half of each edge at its vertex and no
other edge. An eigenvector e of the tensor is a direction of no bending, so
its eigenvalue is the curvature in the tangent direction N x e.

Both functions return, for each vertex, (k1, k2, d1, d2, N) with k1 >= k2,
d1 and d2 the unit principal directions and N the unit normal used. A vertex
whose region meets the border gets None.
"""

import math

from mx1mesh import (boundary_vertices, cross, dot, edge_faces, face_area, face_cross, mixed_area, neighbours, norm,
                     orient3d, scale, sub, unit)


def vertex_normals(points, faces):
    """The unit normal at each vertex: the sum of the face normals weighted by the face areas."""
    acc = [(0.0, 0.0, 0.0) for _ in points]
    for f in faces:
        c = face_cross(points, f)  # twice the area times the unit normal
        for i in f:
            acc[i] = tuple(a + b for a, b in zip(acc[i], c))
    return [unit(a) for a in acc]


def tangent_basis(N):
    """Two unit vectors E1, E2 such that E1, E2, N is a right-handed orthonormal frame."""
    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, N)))
    E1 = unit(cross(N, e))
    return E1, cross(N, E1)


def eigen2(a, b, c):
    """Eigenvalues l1 >= l2 and unit eigenvectors (2-tuples) of the symmetric matrix [[a, b], [b, c]]."""
    mean, half = (a + c) / 2, math.hypot((a - c) / 2, b)
    phi = 0.5 * math.atan2(2 * b, a - c)  # the angle of the eigenvector of l1
    return mean + half, mean - half, (math.cos(phi), math.sin(phi)), (-math.sin(phi), math.cos(phi))


def principal_from_samples(samples):
    """Taubin's step from samples (w, kappa, t1, t2): weight, normal curvature, unit tangent direction in 2D.

    Returns k1 >= k2 and their directions (2-tuples) from the eigenvalues m1 >= m2 of
    M = sum w kappa t t^T / sum w, with k1 = 3 m1 - m2 and k2 = 3 m2 - m1.
    """
    a = b = c = W = 0.0
    for w, kappa, t1, t2 in samples:
        a += w * kappa * t1 * t1  # @line L6
        b += w * kappa * t1 * t2
        c += w * kappa * t2 * t2
        W += w
    m1, m2, v1, v2 = eigen2(a / W, b / W, c / W)  # @line L7
    return 3 * m1 - m2, 3 * m2 - m1, v1, v2  # @line L8


def _lift(E1, E2, v):
    return tuple(v[0] * p + v[1] * q for p, q in zip(E1, E2))


def taubin_curvature(points, faces, normals=None):
    n = len(points)
    N = normals if normals is not None else vertex_normals(points, faces)  # @line L1
    nb = neighbours(n, faces)
    ef = edge_faces(faces)
    border = boundary_vertices(faces)
    out = []
    for i in range(n):  # @line L2
        if i in border or not nb[i]:
            out.append(None)
            continue
        E1, E2 = tangent_basis(N[i])
        samples = []
        for j in nb[i]:  # @line L3
            d = sub(points[i], points[j])
            t = sub(d, scale(dot(d, N[i]), N[i]))  # @line L4
            t1, t2 = dot(t, E1), dot(t, E2)
            tn = math.hypot(t1, t2)
            kappa = 2 * dot(N[i], d) / dot(d, d)
            w = sum(face_area(points, faces[k]) for k in ef[(min(i, j), max(i, j))])  # @line L5
            samples.append((w, kappa, t1 / tn, t2 / tn))
        k1, k2, v1, v2 = principal_from_samples(samples)
        out.append((k1, k2, _lift(E1, E2, v1), _lift(E1, E2, v2), N[i]))
    return out


def dihedral(points, faces, e, f1, f2):
    """The signed angle between the normals of the faces f1 and f2 at the edge e: positive at a convex edge."""
    n1, n2 = unit(face_cross(points, faces[f1])), unit(face_cross(points, faces[f2]))
    angle = math.atan2(norm(cross(n1, n2)), dot(n1, n2))
    opp = next(v for v in faces[f2] if v not in e)
    a, b, c = (points[v] for v in faces[f1])
    # exact sign: at a convex edge the far corner of f2 lies below the plane of f1
    return -angle if orient3d(a, b, c, points[opp]) > 0 else angle


def edge_curvature(points, faces, normals=None, rings=0):
    n = len(points)
    N = normals if normals is not None else vertex_normals(points, faces)
    border = boundary_vertices(faces)
    nb = neighbours(n, faces)
    A = mixed_area(points, faces)
    T = [[0.0] * 6 for _ in range(n)]  # xx, xy, xz, yy, yz, zz of each cell
    for e, fs in edge_faces(faces).items():
        if len(fs) != 2:
            continue
        beta = dihedral(points, faces, e, *fs)
        d = sub(points[e[1]], points[e[0]])
        L = norm(d)
        u = scale(1 / L, d)
        m = (u[0] * u[0], u[0] * u[1], u[0] * u[2], u[1] * u[1], u[1] * u[2], u[2] * u[2])
        for v in e:  # the cell of v holds half of the edge
            for k in range(6):
                T[v][k] += beta * (L / 2) * m[k]
    out = []
    for i in range(n):
        region = {i}
        for _ in range(rings):
            region |= {j for v in region for j in nb[v]}
        if region & border or not nb[i]:
            out.append(None)
            continue
        area = sum(A[v] for v in region)
        xx, xy, xz, yy, yz, zz = (sum(T[v][k] for v in region) / area for k in range(6))
        M = ((xx, xy, xz), (xy, yy, yz), (xz, yz, zz))
        E1, E2 = tangent_basis(N[i])

        def q(p, r):
            return dot(p, tuple(dot(row, r) for row in M))

        l1, l2, v1, v2 = eigen2(q(E1, E1), q(E1, E2), q(E2, E2))
        # the eigenvalue of the direction e is the curvature across e, in the direction N x e
        pairs = [(l1, cross(N[i], _lift(E1, E2, v1))), (l2, cross(N[i], _lift(E1, E2, v2)))]
        (k1, d1), (k2, d2) = sorted(pairs, key=lambda t: -t[0])
        out.append((k1, k2, d1, d2, N[i]))
    return out
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_curvature_tensor_estimation.py 163 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/curvature-tensor-estimation/. The authors are listed in prov/TJZ7S2.jsonl.

import math
import random

from curvature_tensor_estimation import dihedral, edge_curvature, principal_from_samples, taubin_curvature
from mx1mesh import (box_mesh, cylinder, dot, edge_faces, icosphere, mat_vec, neighbours, rotation_matrix, scale,
                     to_float, unit)


def inner(res):
    return [r for r in res if r is not None]


def euler(k1, k2, phi, theta):
    """The normal curvature in the direction theta when k1 is along phi (Euler's formula)."""
    return k1 * math.cos(theta - phi) ** 2 + k2 * math.sin(theta - phi) ** 2


# ---- Taubin's step on exact samples ----


def test_balanced_directions_give_the_exact_curvatures() -> None:
    rng = random.Random(1)
    for count in (5, 6, 7, 8):
        for _ in range(20):
            k1, k2 = sorted((rng.uniform(-3, 3), rng.uniform(-3, 3)), reverse=True)
            phi, start = rng.uniform(0, math.pi), rng.uniform(0, math.pi)
            th = [start + 2 * math.pi * j / count for j in range(count)]
            s = [(1.0, euler(k1, k2, phi, t), math.cos(t), math.sin(t)) for t in th]
            a, b, v1, _ = principal_from_samples(s)
            assert abs(a - k1) < 1e-12 and abs(b - k2) < 1e-12
            if k1 - k2 > 1e-3:
                assert abs(abs(v1[0] * math.cos(phi) + v1[1] * math.sin(phi)) - 1) < 1e-9


def test_four_directions_are_not_enough() -> None:
    # 4 equal directions: sum of e^(4 i theta) is not 0, and the estimate is biased
    k1, k2 = 1.0, 0.0
    s = [(1.0, euler(k1, k2, 0.0, t), math.cos(t), math.sin(t)) for t in (0, math.pi / 2, math.pi, 3 * math.pi / 2)]
    a, b, _, _ = principal_from_samples(s)
    assert abs(a - 1.5) < 1e-12 and abs(b + 0.5) < 1e-12
    assert abs((a + b) / 2 - 0.5) < 1e-12  # the mean is still right
    s = [(1.0, euler(k1, k2, 0.0, t), math.cos(t), math.sin(t)) for t in (math.pi / 4, 3 * math.pi / 4, 5 * math.pi / 4, 7 * math.pi / 4)]
    a, b, _, _ = principal_from_samples(s)
    assert abs(a - 0.5) < 1e-12 and abs(b - 0.5) < 1e-12  # turned by 45 degrees: no split at all


# ---- spheres ----


def test_taubin_on_a_sphere() -> None:
    r = 2.0
    p, f = icosphere(3, r)
    nb = neighbours(len(p), f)
    exact = [unit(q) for q in p]
    res = taubin_curvature(p, f, exact)
    for k1, k2, d1, d2, n in res:
        assert abs(k1 + k2 - 2 / r) < 1e-12  # the trace is exact with the true normals
        assert abs(dot(d1, d2)) < 1e-12 and abs(dot(d1, n)) < 1e-12
    for i in range(len(p)):
        if len(nb[i]) == 5:  # five equal directions: exact
            assert abs(res[i][0] - 1 / r) < 1e-12 and abs(res[i][1] - 1 / r) < 1e-12
    for k1, k2, *_ in taubin_curvature(p, f):  # the normals of the mesh
        assert abs(k1 + k2 - 2 / r) < 0.01


def test_edge_tensor_on_a_sphere_converges_with_a_larger_region() -> None:
    r = 2.0
    errs = []
    for level in (2, 3):
        p, f = icosphere(level, r)
        res = inner(edge_curvature(p, f, rings=1))
        errs.append(max(max(abs(k1 - 1 / r), abs(k2 - 1 / r)) for k1, k2, *_ in res))
    assert errs[1] < errs[0] / 2 and errs[1] < 0.012


# ---- cylinders ----


def test_edge_tensor_on_a_cylinder_has_a_closed_form() -> None:
    for m in (8, 16, 32):
        c = 2 * math.sin(math.pi / m)
        p, f = cylinder(1.0, 6 * c, m, 6)
        exp = (math.pi / m) / math.sin(math.pi / m)
        for rings in (0, 1):
            res = inner(edge_curvature(p, f, rings=rings))
            assert res
            for k1, k2, d1, d2, n in res:
                assert abs(k1 - exp) < 1e-12 and abs(k2) < 1e-12
                assert abs(abs(d2[2]) - 1) < 1e-12 and abs(d1[2]) < 1e-12  # k2 = 0 along the axis


def test_taubin_on_a_twisted_cylinder_converges() -> None:
    err = []
    for m in (16, 32):
        c = 2 * math.sin(math.pi / m)
        p, f = cylinder(1.0, 6 * c * math.sqrt(3) / 2, m, 6, twisted=True)
        res = inner(taubin_curvature(p, f))
        err.append(max(max(abs(k1 - 1), abs(k2)) for k1, k2, *_ in res))
        assert all(abs(abs(d2[2]) - 1) < 1e-9 for _, _, _, d2, _ in res)
    assert err[1] < err[0] / 3 and err[1] < 0.001


def test_taubin_on_the_plain_cylinder_keeps_a_bias() -> None:
    # six unequal directions: the limit is 1/2 + sqrt(5)/3, not 1, while the mean is right
    p, f = cylinder(1.0, 6 * 2 * math.sin(math.pi / 64), 64, 6)
    for k1, k2, *_ in inner(taubin_curvature(p, f)):
        assert abs(k1 - (0.5 + math.sqrt(5) / 3)) < 2e-3
        assert abs((k1 + k2) / 2 - 0.5) < 1e-3


# ---- signs, symmetry, and a saddle ----


def test_a_dent_has_negative_curvature() -> None:
    p, f = icosphere(2)
    f = [(a, c, b) for a, b, c in f]  # the normals now point in
    for fn in (taubin_curvature, edge_curvature):
        for k1, k2, *_ in inner(fn(p, f)):
            assert k1 < 0 and k2 < 0


def test_rotation_moves_the_directions_and_keeps_the_curvatures() -> None:
    rng = random.Random(4)
    p, f = icosphere(2)
    p = [scale(1 + 0.1 * rng.random(), q) for q in p]
    R = rotation_matrix((1, 2, 2), 0.7)
    q = [tuple(mat_vec(R, x)) for x in p]
    for fn in (taubin_curvature, edge_curvature):
        for a, b in zip(fn(p, f), fn(q, f)):
            assert abs(a[0] - b[0]) < 1e-9 and abs(a[1] - b[1]) < 1e-9
            if a[0] - a[1] > 1e-3:
                assert abs(abs(dot(mat_vec(R, a[2]), b[2])) - 1) < 1e-6


def test_saddle() -> None:
    k = 16
    idx, p, f = {}, [], []
    for a in range(-4, 5):
        for b in range(-4, 5):
            idx[(a, b)] = len(p)
            x, y = a / k, b / k
            p.append((x, y, (x * x - y * y) / 2))
    for a in range(-4, 4):
        for b in range(-4, 4):
            A, B, C, D = idx[(a, b)], idx[(a + 1, b)], idx[(a + 1, b + 1)], idx[(a, b + 1)]
            f += [(A, B, C), (A, C, D)]
    o = idx[(0, 0)]
    k1, k2, d1, d2, n = edge_curvature(p, f)[o]
    assert abs(k1 - 1) < 0.01 and abs(k2 + 1) < 0.01 and abs(abs(d1[1]) - 1) < 1e-9
    k1, k2, *_ = taubin_curvature(p, f)[o]
    assert abs(k1 - 4 / 3) < 0.01 and abs(k2 + 4 / 3) < 0.01  # the grid's directions bias it by 4/3


def test_dihedral_signs_on_a_box() -> None:
    p, f = box_mesh((2, 3, 5), (2, 2, 2))
    p = to_float(p)
    for e, fs in edge_faces(f).items():
        b = dihedral(p, f, e, *fs)
        assert b == 0 or abs(b - math.pi / 2) < 1e-12
    assert sum(1 for e, fs in edge_faces(f).items() if dihedral(p, f, e, *fs) > 0) == 12 * 2

History

In 1995 Taubin observed that the curvature of the circle through a vertex and a neighbour, tangent to the vertex normal, is a sample of the normal curvature along the edge. He averaged these samples as a tensor and read the principal curvatures from its eigenvalues by a fixed linear map. In 2003 Cohen-Steiner and Morvan derived a curvature tensor of a polyhedral surface from the theory of normal cycles, as the sum of the dihedral angles of the edges in a region, and proved that it converges to the tensor of a smooth surface for restricted Delaunay triangulations. In the same year Alliez, Cohen-Steiner, Devillers, Lévy and Desbrun used this tensor to trace lines of curvature for anisotropic remeshing. Later methods, by Rusinkiewicz and by Goldfeather and Interrante in 2004, estimate the tensor per face or by fitting.

References

  1. Gabriel Taubin, Estimating the tensor of curvature of a surface from a polyhedral approximation, Proceedings of the Fifth International Conference on Computer Vision (ICCV), 1995, 902 to 907, the normal curvature along an edge from the vertex normal, the weighted average of the edge tensors, and the principal curvatures from its eigenvalues
  2. David Cohen-Steiner and Jean-Marie Morvan, Restricted Delaunay triangulations and normal cycle, Proceedings of the 19th Annual Symposium on Computational Geometry (SoCG), 2003, 312 to 321, the curvature measure from the dihedral angles of the edges in a region, and the error bound for restricted Delaunay triangulations of a smooth surface
  3. Pierre Alliez, David Cohen-Steiner, Olivier Devillers, Bruno Lévy and Mathieu Desbrun, Anisotropic polygonal remeshing, ACM Transactions on Graphics 22(3), 2003, 485 to 493, the edge tensor averaged over a region around each vertex, and its principal directions used to trace lines of curvature for remeshing

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example