Algorithm Search⌘K

Algorithmadvanced

Green coordinates

Also called Green cage coordinates.

Cage coordinates from Green's third identity that use both the cage vertices and face normals, giving conformal deformations in 2D.

Time
Θ(N n) allΘ(n) per_point
Space
Θ(n) extra
Where
N = the number of points to deform; n = the number of cage vertices and edges
Properties
deterministicexactonlineiterative

Green coordinates are cage coordinates with two kinds of weights: one weight ϕi\phi_i per cage vertex and one weight ψj\psi_j per cage edge, or per face in 3D. A point η\eta inside the cage moves to ∑iϕi(η)vi′+∑jψj(η)sjnj′\sum_i \phi_i(\eta)v'_i + \sum_j \psi_j(\eta)s_jn'_j, where vi′v'_i are the moved vertices, nj′n'_j the moved edge normals, and sjs_j the factor by which edge jj grew. The weights come from Green's third identity applied to the coordinate functions, and they have closed forms. Yaron Lipman, David Levin and Daniel Cohen-Or (2008) introduced them. The normal terms make the difference: in 2D the deformation is a conformal map, so small shapes inside the cage keep their angles, where other cage coordinates shear them.

In plain words

Other cage methods move a point by a weighted mix of the cage corners. Green coordinates also listen to the sides of the cage: how each side turns, and how much it stretches. If a side turns, the points near it turn with it, and if it gets longer, the shape near it grows in both directions, not only along the side. That is why a small circle drawn inside the shape stays a small circle, only moved, turned and resized, even when the cage bends. The price is that the shape no longer touches the cage exactly: the moved cage is a guide, not a hard wall.

The problem

The input is a cage, a simple polygon v0,…,vn−1v_0, \dots, v_{n-1} in counterclockwise order, with edge jj from vjv_j to vj+1v_{j+1} and its outward unit normal njn_j, and a point η\eta inside it. The output is the 2n2n weights ϕi(η)\phi_i(\eta) and ψj(η)\psi_j(\eta) such that

η=∑iϕi(η)vi+∑jψj(η)njand∑iϕi(η)=1,\eta = \sum_i \phi_i(\eta)v_i + \sum_j \psi_j(\eta)n_j \quad\text{and}\quad \sum_i \phi_i(\eta) = 1,

and the deformed point for a moved cage v′v'. With G(ξ,η)=12πln⁡∣ξ−η∣G(\xi, \eta) = \frac{1}{2\pi}\ln|\xi - \eta| and the hat function Γi\Gamma_i of vertex ii on the boundary, the weights are

ϕi(η)=∫∂ΩΓi(ξ) ∂G∂n(ξ,η) ds(ξ),ψj(η)=−∫ejG(ξ,η) ds(ξ).\phi_i(\eta) = \int_{\partial\Omega} \Gamma_i(\xi)\,\frac{\partial G}{\partial n}(\xi, \eta)\,ds(\xi), \qquad \psi_j(\eta) = -\int_{e_j} G(\xi, \eta)\,ds(\xi).

The algorithm

On edge jj with a=vja = v_j and b=vj+1b = v_{j+1}, let q(t)=∣a+t(b−a)−η∣2=Qt2+Rt+Sq(t) = |a + t(b - a) - \eta|^2 = Qt^2 + Rt + S. The integrals I0=∫01dt/qI_0 = \int_0^1 dt/q, I1=∫01t dt/qI_1 = \int_0^1 t\,dt/q and Λ=∫01ln⁡q dt\Lambda = \int_0^1 \ln q\,dt have closed forms with one arctangent and two logarithms.

  1. GREEN(η, v)
  2. 1φ ← 0, ψ ← 0
  3. 2for each edge j from a = v_j to b = v_{j+1} do
  4. 3n_j ← the outward unit normal of edge j
  5. 4h ← (a - η) · n_j
  6. 5compute I_0, I_1 and Λ for edge j
  7. 6φ_j ← φ_j + (h|b - a|/2π)(I_0 - I_1); φ_{j+1} ← φ_{j+1} + (h|b - a|/2π) I_1
  8. 7ψ_j ← -(|b - a|/4π) Λ
  9. 8return φ, ψ
  10. DEFORM(η, v, v')
  11. 9return Σ_i φ_i v'_i + Σ_j ψ_j s_j n'_j, with s_j = |v'_{j+1} - v'_j| / |v_{j+1} - v_j|

Line L4 uses that (ξ−η)⋅nj=h(\xi - \eta) \cdot n_j = h is the same for every ξ\xi on edge jj, so ∂G/∂n=h/(2πq)\partial G/\partial n = h/(2\pi q) there. Line L6 splits the integral of line L4 between the two ends of the edge with the hat functions 1−t1 - t and tt. Line L7 uses ln⁡∣ξ−η∣=12ln⁡q\ln|\xi - \eta| = \frac12\ln q. With D=4QS−R2=2∣(b−a)×(a−η)∣D = \sqrt{4QS - R^2} = 2|(b - a) \times (a - \eta)| and A=(arctan⁡2Q+RD−arctan⁡RD)/DA = (\arctan\frac{2Q + R}{D} - \arctan\frac{R}{D})/D: I0=2AI_0 = 2A, I1=12Qln⁡Q+R+SS−RQAI_1 = \frac{1}{2Q}\ln\frac{Q + R + S}{S} - \frac{R}{Q}A, and Λ=ln⁡(Q+R+S)+R2Qln⁡Q+R+SS−2+(4S−R2Q)A\Lambda = \ln(Q + R + S) + \frac{R}{2Q}\ln\frac{Q + R + S}{S} - 2 + (4S - \frac{R^2}{Q})A. If η\eta is on the line of the edge, h=0h = 0 and only Λ\Lambda is needed, without the term in AA.

Example

For the unit square and its center η=(1/2,1/2)\eta = (1/2, 1/2), symmetry gives ϕi=1/4\phi_i = 1/4 for every vertex, and every edge has ψj=−14π∫01ln⁡((t−12)2+14) dt≈0.0893138\psi_j = -\frac{1}{4\pi}\int_0^1 \ln((t - \frac12)^2 + \frac14)\,dt \approx 0.0893138. The four normals sum to 0, so ∑ϕivi+∑ψjnj=(1/2,1/2)\sum\phi_iv_i + \sum\psi_jn_j = (1/2, 1/2), as it must. Now shear the cage by (x,y)↦(x+y/2,y)(x, y) \mapsto (x + y/2, y). The center goes to (0.75,0.5)(0.75, 0.5), which is the sheared center. But the point (0.25,0.3)(0.25, 0.3) goes to about (0.44685,0.36097)(0.44685, 0.36097), not to the sheared point (0.4,0.3)(0.4, 0.3): a shear is not conformal, so Green coordinates cannot reproduce it. A rotation with a scale and a translation of the cage, on the other hand, moves every inside point by exactly the same map; the tests check this on an L-shaped cage.

Correctness

The proof proves the following. Green's third identity says that a function uu that is harmonic inside Ω\Omega satisfies u(η)=∫∂Ω(u ∂G/∂n−G ∂u/∂n) dsu(\eta) = \int_{\partial\Omega}(u\,\partial G/\partial n - G\,\partial u/\partial n)\,ds. For u=1u = 1 this gives ∑iϕi=1\sum_i \phi_i = 1, and for u(ξ)=ξu(\xi) = \xi, with ∂u/∂n=n\partial u/\partial n = n and ξ=∑iΓi(ξ)vi\xi = \sum_i \Gamma_i(\xi)v_i on the boundary, it gives η=∑iϕivi+∑jψjnj\eta = \sum_i\phi_iv_i + \sum_j\psi_jn_j. If the moved cage is v′=Mv+cv' = Mv + c with MM a rotation times a scale λ>0\lambda > 0, then sj=λs_j = \lambda and nj′=Mnj/λn'_j = Mn_j/\lambda, so line L9 returns Mη+cM\eta + c: similarities are reproduced. In complex notation, the map of line L9 equals the Cauchy integral 12πi∮g(ξ)/(ξ−η) dξ\frac{1}{2\pi i}\oint g(\xi)/(\xi - \eta)\,d\xi of the piecewise linear map gg of the cage onto the moved cage, by an integration by parts on each edge. A Cauchy integral is holomorphic inside the cage, so the deformation is conformal wherever its derivative is not 0. The tests check the closed forms against Gauss-Legendre quadrature, the equality with the Cauchy integral, and the Cauchy-Riemann equations by finite differences.

Proof: Green coordinates reproduce the point and the constants, reproduce similarities, and give a holomorphic map in 2Dfull

We use the notation of the page. Ω\Omega is the inside of the cage, η∈Ω\eta \in \Omega, and G(ξ,η)=12πln⁡∣ξ−η∣G(\xi, \eta) = \frac{1}{2\pi}\ln|\xi - \eta|, which satisfies ΔξG=δη\Delta_\xi G = \delta_\eta. On edge jj we write ξ=a+td\xi = a + td with d=b−ad = b - a and t∈[0,1]t \in [0, 1], so ds=∣d∣ dtds = |d|\,dt.

The closed forms of lines L4 to L7

Lemma 1. On edge jj, (ξ−η)⋅nj=h(\xi - \eta) \cdot n_j = h for every ξ\xi on the edge, ∂G∂n(ξ,η)=h2πq(t)\frac{\partial G}{\partial n}(\xi, \eta) = \frac{h}{2\pi q(t)}, and G(ξ,η)=14πln⁡q(t)G(\xi, \eta) = \frac{1}{4\pi}\ln q(t).

Proof. (ξ−η)⋅nj=(a−η)⋅nj+t d⋅nj(\xi - \eta) \cdot n_j = (a - \eta) \cdot n_j + t\,d \cdot n_j, and d⋅nj=0d \cdot n_j = 0. ∇ξG=ξ−η2π∣ξ−η∣2\nabla_\xi G = \frac{\xi - \eta}{2\pi|\xi - \eta|^2}, so ∂G/∂n=∇ξG⋅nj=h/(2πq)\partial G/\partial n = \nabla_\xi G \cdot n_j = h/(2\pi q). The last claim is ln⁡∣ξ−η∣=12ln⁡q\ln|\xi - \eta| = \frac12\ln q. □\square

So ϕj\phi_j gets ∫01(1−t)h2πq∣d∣ dt=h∣d∣2π(I0−I1)\int_0^1 (1 - t)\frac{h}{2\pi q}|d|\,dt = \frac{h|d|}{2\pi}(I_0 - I_1) from edge jj, and ϕj+1\phi_{j+1} gets h∣d∣2πI1\frac{h|d|}{2\pi}I_1, which is line L6. And ψj=−∫0114πln⁡q ∣d∣ dt=−∣d∣4πΛ\psi_j = -\int_0^1 \frac{1}{4\pi}\ln q\,|d|\,dt = -\frac{|d|}{4\pi}\Lambda, which is line L7. The antiderivatives of 1/q1/q, t/qt/q and ln⁡q\ln q for a quadratic qq with no real zero are standard; the tests compare the closed forms with Gauss-Legendre quadrature on 384 points per edge.

Reproduction

Theorem 1. For every η∈Ω\eta \in \Omega: ∑iϕi(η)=1\sum_i \phi_i(\eta) = 1 and ∑iϕi(η)vi+∑jψj(η)nj=η\sum_i \phi_i(\eta)v_i + \sum_j \psi_j(\eta)n_j = \eta.

Proof. Green's second identity on Ω\Omega for a function uu that is harmonic on a neighbourhood of the closure of Ω\Omega, and for G(⋅,η)G(\cdot, \eta), gives Green's third identity:

u(η)=∫∂Ω(u(ξ)∂G∂n(ξ,η)−G(ξ,η)∂u∂n(ξ))ds(ξ).u(\eta) = \int_{\partial\Omega}\Big(u(\xi)\frac{\partial G}{\partial n}(\xi, \eta) - G(\xi, \eta)\frac{\partial u}{\partial n}(\xi)\Big)ds(\xi).

For u=1u = 1 the second term is 0, and 1=∑iΓi1 = \sum_i\Gamma_i on the boundary, so 1=∑i∫Γi ∂G/∂n ds=∑iϕi1 = \sum_i\int\Gamma_i\,\partial G/\partial n\,ds = \sum_i\phi_i. For u(ξ)=ξu(\xi) = \xi, applied to each coordinate, ∂u/∂n=nj\partial u/\partial n = n_j on edge jj, and ξ=∑iΓi(ξ)vi\xi = \sum_i\Gamma_i(\xi)v_i on the boundary, because Γj=1−t\Gamma_j = 1 - t and Γj+1=t\Gamma_{j+1} = t on edge jj. So η=∑ivi∫Γi ∂G/∂n ds−∑jnj∫ejG ds=∑iϕivi+∑jψjnj\eta = \sum_i v_i\int\Gamma_i\,\partial G/\partial n\,ds - \sum_j n_j\int_{e_j}G\,ds = \sum_i\phi_iv_i + \sum_j\psi_jn_j. □\square

Corollary. With v′=vv' = v, line L9 returns η\eta, because then sj=1s_j = 1 and nj′=njn'_j = n_j.

Similarities

Theorem 2. Let vi′=Mvi+cv'_i = Mv_i + c for every ii, where M=λQM = \lambda Q with a rotation QQ and λ>0\lambda > 0. Then line L9 returns Mη+cM\eta + c.

Proof. Every edge vector becomes MdMd, so sj=∣Md∣/∣d∣=λs_j = |Md|/|d| = \lambda, and the outward normal becomes nj′=Qnjn'_j = Qn_j, because QQ is a rotation and keeps the orientation. So sjnj′=λQnj=Mnjs_jn'_j = \lambda Qn_j = Mn_j, and line L9 gives ∑iϕi(Mvi+c)+∑jψjMnj=M(∑iϕivi+∑jψjnj)+c∑iϕi=Mη+c\sum_i\phi_i(Mv_i + c) + \sum_j\psi_jMn_j = M(\sum_i\phi_iv_i + \sum_j\psi_jn_j) + c\sum_i\phi_i = M\eta + c, by Theorem 1. □\square

The map is a Cauchy integral

We identify R2\mathbb{R}^2 with C\mathbb{C}. Let gg be the piecewise linear map of the cage boundary onto the moved cage: on edge jj, g(a+td)=a′+td′g(a + td) = a' + td', with a′=vj′a' = v'_j and d′=vj+1′−vj′d' = v'_{j+1} - v'_j. So g(ξ)=a′+βj(ξ−a)g(\xi) = a' + \beta_j(\xi - a) on edge jj with βj=d′/d\beta_j = d'/d. For a counterclockwise cage, the outward normal of edge jj is nj=−i d/∣d∣n_j = -i\,d/|d|, and then sjnj′=∣d′∣∣d∣⋅(−i)d′∣d′∣=βjnjs_jn'_j = \frac{|d'|}{|d|}\cdot(-i)\frac{d'}{|d'|} = \beta_jn_j.

Lemma 2. On edge jj, with r=∣ξ−η∣r = |\xi - \eta|: ∂G∂nds=12πIm⁡dξξ−η\frac{\partial G}{\partial n}ds = \frac{1}{2\pi}\operatorname{Im}\frac{d\xi}{\xi - \eta} and Re⁡dξξ−η=d(ln⁡r)\operatorname{Re}\frac{d\xi}{\xi - \eta} = d(\ln r), the derivative of ln⁡r\ln r along the edge.

Proof. dξξ−η=d (ξ−η)‾r2dt\frac{d\xi}{\xi - \eta} = \frac{d\,\overline{(\xi - \eta)}}{r^2}dt. Its imaginary part is Im⁡(d (ξ−η)‾)r2dt\frac{\operatorname{Im}(d\,\overline{(\xi - \eta)})}{r^2}dt, and Im⁡(d w‾)=−Im⁡(w d‾)=Re⁡(w⋅id‾)=∣d∣ w⋅nj\operatorname{Im}(d\,\overline{w}) = -\operatorname{Im}(w\,\overline{d}) = \operatorname{Re}(w\cdot i\overline{d}) = |d|\,w \cdot n_j for w=ξ−ηw = \xi - \eta, because nj‾=id‾/∣d∣\overline{n_j} = i\overline{d}/|d| and w⋅n=Re⁡(wn‾)w \cdot n = \operatorname{Re}(w\overline{n}). So the imaginary part is ∣d∣hr2dt=2π∂G∂nds\frac{|d|h}{r^2}dt = 2\pi\frac{\partial G}{\partial n}ds by Lemma 1. Its real part is Re⁡(d w‾)r2dt=d⋅wr2dt=12dqq=d(ln⁡r)\frac{\operatorname{Re}(d\,\overline{w})}{r^2}dt = \frac{d \cdot w}{r^2}dt = \frac{1}{2}\frac{dq}{q} = d(\ln r). □\square

Theorem 3. Line L9 returns f(η)=12πi∮∂Ωg(ξ)ξ−ηdξf(\eta) = \frac{1}{2\pi i}\oint_{\partial\Omega}\frac{g(\xi)}{\xi - \eta}d\xi.

Proof. 12πiw=12π(Im⁡w−iRe⁡w)\frac{1}{2\pi i}w = \frac{1}{2\pi}(\operatorname{Im}w - i\operatorname{Re}w) for every complex ww. So, by Lemma 2,

12πi∫ejg dξξ−η=∫ejg∂G∂nds−i2π∫ejg d(ln⁡r).\frac{1}{2\pi i}\int_{e_j}\frac{g\,d\xi}{\xi - \eta} = \int_{e_j}g\frac{\partial G}{\partial n}ds - \frac{i}{2\pi}\int_{e_j}g\,d(\ln r).

Integrate the last term by parts: ∫ejg d(ln⁡r)=[gln⁡r]vjvj+1−∫ejln⁡r dg\int_{e_j}g\,d(\ln r) = [g\ln r]_{v_j}^{v_{j+1}} - \int_{e_j}\ln r\,dg, and dg=βj dξ=βjd∣d∣ds=iβjnj dsdg = \beta_j\,d\xi = \beta_j\frac{d}{|d|}ds = i\beta_jn_j\,ds. So −i2π∫ejg d(ln⁡r)=−i2π[gln⁡r]vjvj+1−βjnj∫ejG ds=−i2π[gln⁡r]vjvj+1+ψjsjnj′-\frac{i}{2\pi}\int_{e_j}g\,d(\ln r) = -\frac{i}{2\pi}[g\ln r]_{v_j}^{v_{j+1}} - \beta_jn_j\int_{e_j}G\,ds = -\frac{i}{2\pi}[g\ln r]_{v_j}^{v_{j+1}} + \psi_js_jn'_j. Sum over all edges. The bracket terms cancel, because gg and ln⁡r\ln r are continuous at every vertex and the boundary is closed. The first terms add up to ∫∂Ωg ∂G/∂n ds=∑ivi′∫Γi ∂G/∂n ds=∑iϕivi′\int_{\partial\Omega}g\,\partial G/\partial n\,ds = \sum_iv'_i\int\Gamma_i\,\partial G/\partial n\,ds = \sum_i\phi_iv'_i, since g=∑iΓivi′g = \sum_i\Gamma_iv'_i on the boundary. So the sum is ∑iϕivi′+∑jψjsjnj′\sum_i\phi_iv'_i + \sum_j\psi_js_jn'_j, which is line L9. □\square

Corollary (conformal in 2D). ff is holomorphic in Ω\Omega, so it satisfies the Cauchy-Riemann equations, and it keeps angles at every point where f′(η)≠0f'(\eta) \ne 0.

Proof. gg is bounded on the boundary, and 1ξ−η\frac{1}{\xi - \eta} is holomorphic in η\eta with derivatives bounded uniformly for η\eta in a compact subset of Ω\Omega, so differentiation under the integral sign shows that ff is complex differentiable in Ω\Omega. A holomorphic map with f′≠0f' \ne 0 is conformal. □\square

Theorem 3 also explains Theorem 2 and the shear of the example: if gg extends to a holomorphic map g^\hat g on Ω\Omega, Cauchy's formula gives f=g^f = \hat g; a similarity ξ↦Mξ+c\xi \mapsto M\xi + c is holomorphic, while a shear ξ↦ξ+12Im⁡ξ\xi \mapsto \xi + \frac12\operatorname{Im}\xi is not, and it is not reproduced.

Complexity

Each edge costs O(1)O(1), with two logarithms and two arctangents, so the 2n2n weights of one point take Θ(n)\Theta(n) time and line L9 takes Θ(n)\Theta(n). NN points cost Θ(Nn)\Theta(Nn); storing the weights takes Θ(Nn)\Theta(Nn) memory, and the work per point needs Θ(n)\Theta(n). There is no precomputation beyond the weights: unlike harmonic coordinates there is no grid and no solve.

Properties

  • Reproduction and partition of unity (proved). η=∑ϕivi+∑ψjnj\eta = \sum\phi_iv_i + \sum\psi_jn_j and ∑ϕi=1\sum\phi_i = 1, so the rest cage gives the identity.
  • Similarities reproduced (proved). Rotating, scaling and moving the cage does the same to the shape.
  • Conformal in 2D (proved). The map is holomorphic inside the cage; it keeps angles wherever its derivative is not 0.
  • General affine maps not reproduced (proved by the example). A shear or a scale in one direction of the cage is not a conformal map, so the inside follows it only roughly.
  • Not interpolating. The deformed shape does not pass through the moved cage vertices, and points near the cage do not follow the cage boundary exactly. A Cauchy integral has the boundary values gg only when gg extends to a holomorphic map, as for a similarity.
  • Signed weights (measurement). ϕi\phi_i can be negative for concave cages: on a grid of step 0.050.05 inside the L-shaped cage of the tests, the smallest ϕi\phi_i is about −0.032-0.032. ψj\psi_j has no fixed sign. Because of the normal terms, the weights are not barycentric coordinates in the strict sense.
  • 3D quasi-conformal (stated by the paper, not checked here). In 3D, with triangle faces in place of edges, Lipman, Levin and Cohen-Or describe the map as quasi-conformal; no 3D code or proof is on this page.

Variants and improvements

  • 3D cages. The same identity with triangle faces gives weights per vertex and per face, with closed forms over triangles.
  • Complex coordinates. In 2D, writing the map as a Cauchy integral leads to complex-valued cage coordinates, and to other holomorphic choices of the boundary map than the piecewise linear one.
  • Harmonic and mean value coordinates. Harmonic coordinates and mean value coordinates use vertex weights only; they reproduce all affine maps and interpolate the cage, but do not keep angles.
  • Rigid shapes by optimization. As-rigid-as-possible shape manipulation keeps local shapes by a solve over a mesh instead of a closed form.

When to use it

Use Green coordinates when a cage should bend a shape while keeping its details from shearing, as for the face of a cartoon character, text on a curved band or a pattern on a surface. They cost the same as other closed-form cage coordinates. Do not use them when the shape must follow the cage exactly, or when the user expects an affine edit of the cage, such as a stretch along one axis, to stretch the shape the same way.

Pitfalls

  • Orientation. The formulas assume a counterclockwise cage with outward normals; a clockwise cage flips the signs of hh and of the normals.
  • Points on the boundary. On an edge, qq has a zero and ln⁡q\ln q a singularity, and the weights are not defined. Keep the shape strictly inside the cage.
  • Cancellation. Compute DD as 2∣(b−a)×(a−η)∣2|(b - a) \times (a - \eta)|, not as 4QS−R2\sqrt{4QS - R^2}, which loses many digits near the line of the edge.
  • Forgetting sjs_j. Without the edge stretch sjs_j, a uniformly scaled cage no longer scales the shape.
  • Large edits. Conformal maps can grow or shrink a region a lot; a cage that is pinched hard shrinks the shape near the pinch strongly.

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.

green_coordinates.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/green-coordinates/. The authors are listed in prov/2QKV5N.jsonl.
"""2D Green coordinates (Lipman, Levin and Cohen-Or 2008).

The cage is a simple polygon v_0..v_{n-1} in counterclockwise order. Edge j
runs from v_j to v_{j+1} and has the outward unit normal n_j. For a point
eta inside the cage, Green's third identity applied to the coordinate
functions gives

    eta = sum_i phi_i(eta) v_i + sum_j psi_j(eta) n_j,

with G(xi, eta) = (1 / 2 pi) ln |xi - eta| and

    phi_i = integral over the two edges at v_i of Gamma_i(xi) dG/dn(xi, eta),
    psi_j = - integral over edge j of G(xi, eta),

where Gamma_i is the hat function of v_i on the boundary. The integrals
have closed forms, computed below. The deformed point is

    f(eta) = sum_i phi_i v'_i + sum_j psi_j s_j n'_j,   s_j = |e'_j| / |e_j|.
"""

import math

TWO_PI = 2.0 * math.pi


def outward_normal(a, b):
    """Return the outward unit normal of the edge a -> b of a counterclockwise polygon."""
    dx, dy = b[0] - a[0], b[1] - a[1]
    ln = math.hypot(dx, dy)
    return (dy / ln, -dx / ln)


def edge_integrals(a, b, eta, eps=1e-14):
    """Return (I0, I1, L) for the edge a -> b and the point eta.

    With xi(t) = a + t (b - a) and q(t) = |xi(t) - eta|^2 = Q t^2 + R t + S:
    I0 = int_0^1 dt / q(t), I1 = int_0^1 t dt / q(t), L = int_0^1 ln q(t) dt.
    """
    dx, dy = b[0] - a[0], b[1] - a[1]
    wx, wy = a[0] - eta[0], a[1] - eta[1]
    q = dx * dx + dy * dy
    r = 2.0 * (wx * dx + wy * dy)
    s = wx * wx + wy * wy
    srt = 2.0 * abs(dx * wy - dy * wx)  # sqrt(4 Q S - R^2), computed without cancellation
    l0 = math.log(s)
    l1 = math.log(q + r + s)
    l10 = l1 - l0
    if srt <= eps * q:
        # eta lies on the line of the edge (but not on the edge): h = 0, so
        # I0 and I1 are not needed, and the arctangent term of L vanishes.
        return 0.0, 0.0, l1 + r / (2 * q) * l10 - 2.0
    a10 = (math.atan((2 * q + r) / srt) - math.atan(r / srt)) / srt
    i0 = 2.0 * a10
    i1 = l10 / (2 * q) - (r / q) * a10
    big_l = l1 + r / (2 * q) * l10 - 2.0 + (4 * s - r * r / q) * a10
    return i0, i1, big_l


def green_coordinates(eta, cage):
    """Return (phi, psi): n vertex coordinates and n edge coordinates."""
    n = len(cage)
    phi = [0.0] * n  # @line L1
    psi = [0.0] * n
    for j in range(n):  # @line L2
        a, b = cage[j], cage[(j + 1) % n]
        nx, ny = outward_normal(a, b)  # @line L3
        length = math.hypot(b[0] - a[0], b[1] - a[1])
        h = (a[0] - eta[0]) * nx + (a[1] - eta[1]) * ny  # @line L4
        i0, i1, big_l = edge_integrals(a, b, eta)  # @line L5
        c = h * length / TWO_PI
        phi[j] += c * (i0 - i1)  # @line L6
        phi[(j + 1) % n] += c * i1
        psi[j] = -length / (2 * TWO_PI) * big_l  # @line L7
    return phi, psi  # @line L8


def deform(eta, cage, new_cage):
    """Return f(eta) for the moved cage new_cage."""
    phi, psi = green_coordinates(eta, cage)
    n = len(cage)
    x = sum(p * v[0] for p, v in zip(phi, new_cage))
    y = sum(p * v[1] for p, v in zip(phi, new_cage))
    for j in range(n):
        a, b = cage[j], cage[(j + 1) % n]
        a2, b2 = new_cage[j], new_cage[(j + 1) % n]
        s = math.hypot(b2[0] - a2[0], b2[1] - a2[1]) / math.hypot(b[0] - a[0], b[1] - a[1])
        nx, ny = outward_normal(a2, b2)
        x += psi[j] * s * nx  # @line L9
        y += psi[j] * s * ny
    return (x, y)
test_green_coordinates.py 165 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/green-coordinates/. The authors are listed in prov/2QKV5N.jsonl.
import math
import random

from green_coordinates import deform, edge_integrals, green_coordinates, outward_normal

L_SHAPE = [(0.0, 0.0), (2.0, 0.0), (2.0, 1.0), (1.0, 1.0), (1.0, 2.0), (0.0, 2.0)]
SQUARE = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]


def gauss_legendre(m):
    """Nodes and weights on [0, 1], by Newton's method on the Legendre polynomial."""
    xs, ws = [], []
    for k in range(1, m + 1):
        x = math.cos(math.pi * (k - 0.25) / (m + 0.5))
        for _ in range(100):
            p0, p1 = 1.0, x
            for j in range(2, m + 1):
                p0, p1 = p1, ((2 * j - 1) * x * p1 - (j - 1) * p0) / j
            dp = m * (x * p1 - p0) / (x * x - 1)
            dx = p1 / dp
            x -= dx
            if abs(dx) < 1e-16:
                break
        xs.append((1 - x) / 2)
        ws.append(1 / ((1 - x * x) * dp * dp))
    return xs, ws


GX, GW = gauss_legendre(24)


def quad(f, pieces=16):
    total = 0.0
    for p in range(pieces):
        for x, w in zip(GX, GW):
            total += f((p + x) / pieces) * w / pieces
    return total


def inside_points(rng, cage, count):
    from math import isclose

    out = []
    while len(out) < count:
        p = (rng.uniform(0.05, 1.95), rng.uniform(0.05, 1.95))
        if cage is L_SHAPE and p[0] > 0.95 and p[1] > 0.95:
            continue
        if cage is SQUARE and not (0.05 < p[0] < 0.95 and 0.05 < p[1] < 0.95):
            continue
        if not isclose(p[0], 1.0, abs_tol=0.05) or cage is SQUARE:
            out.append(p)
    return out


def test_closed_form_matches_quadrature():
    rng = random.Random(51)
    for eta in inside_points(rng, L_SHAPE, 8):
        for j in range(len(L_SHAPE)):
            a, b = L_SHAPE[j], L_SHAPE[(j + 1) % len(L_SHAPE)]

            def q(t):
                x, y = a[0] + t * (b[0] - a[0]) - eta[0], a[1] + t * (b[1] - a[1]) - eta[1]
                return x * x + y * y

            i0, i1, big_l = edge_integrals(a, b, eta)
            assert abs(i0 - quad(lambda t: 1 / q(t))) < 1e-10
            assert abs(i1 - quad(lambda t: t / q(t))) < 1e-10
            assert abs(big_l - quad(lambda t: math.log(q(t)))) < 1e-10


def test_point_on_line_of_edge():
    # The point (1, 0.5) lies on the line x = 1 of the edge (1, 1) -> (1, 2), below the edge.
    a, b, eta = (1.0, 1.0), (1.0, 2.0), (1.0, 0.5)
    i0, i1, big_l = edge_integrals(a, b, eta)
    want = quad(lambda t: math.log((0.5 + t) ** 2))
    assert abs(big_l - want) < 1e-10


def test_partition_of_unity_and_reproduction():
    rng = random.Random(52)
    for cage in (L_SHAPE, SQUARE):
        for eta in inside_points(rng, cage, 15):
            phi, psi = green_coordinates(eta, cage)
            assert abs(sum(phi) - 1) < 1e-12
            x = sum(p * v[0] for p, v in zip(phi, cage))
            y = sum(p * v[1] for p, v in zip(phi, cage))
            for j in range(len(cage)):
                nx, ny = outward_normal(cage[j], cage[(j + 1) % len(cage)])
                x += psi[j] * nx
                y += psi[j] * ny
            assert abs(x - eta[0]) < 1e-12 and abs(y - eta[1]) < 1e-12


def similarity(p, ang=0.7, sc=1.6, t=(0.3, -1.2)):
    c, s = math.cos(ang), math.sin(ang)
    return (sc * (c * p[0] - s * p[1]) + t[0], sc * (s * p[0] + c * p[1]) + t[1])


def test_similarity_is_reproduced_and_shear_is_not():
    rng = random.Random(53)
    moved = [similarity(v) for v in L_SHAPE]
    for eta in inside_points(rng, L_SHAPE, 10):
        assert math.dist(deform(eta, L_SHAPE, moved), similarity(eta)) < 1e-11
    sheared = [(x + 0.5 * y, y) for x, y in SQUARE]
    eta = (0.5, 0.5)
    f = deform(eta, SQUARE, sheared)
    assert math.dist(f, (0.75, 0.5)) < 1e-12
    eta = (0.25, 0.3)
    f = deform(eta, SQUARE, sheared)
    assert math.dist(f, (eta[0] + 0.5 * eta[1], eta[1])) > 1e-3


def cauchy(eta, cage, new_cage):
    """Return (1 / 2 pi i) times the integral over the old cage of g(xi) / (xi - eta).

    Here g is the piecewise linear boundary image: g(a + t (b - a)) = a' + t (b' - a').
    """
    z = complex(*eta)
    total = 0j
    n = len(cage)
    for j in range(n):
        a, b = complex(*cage[j]), complex(*cage[(j + 1) % n])
        a2, b2 = complex(*new_cage[j]), complex(*new_cage[(j + 1) % n])
        total += quad(lambda t: ((a2 + t * (b2 - a2)) / (a + t * (b - a) - z)).real) * (b - a)
        total += 1j * quad(lambda t: ((a2 + t * (b2 - a2)) / (a + t * (b - a) - z)).imag) * (b - a)
    return total / (2j * math.pi)


def test_equals_cauchy_integral_of_boundary_image():
    rng = random.Random(54)
    moved = [(x + rng.uniform(-0.3, 0.3), y + rng.uniform(-0.3, 0.3)) for x, y in L_SHAPE]
    for eta in inside_points(rng, L_SHAPE, 6):
        f = deform(eta, L_SHAPE, moved)
        g = cauchy(eta, L_SHAPE, moved)
        assert abs(complex(*f) - g) < 1e-9


def test_cauchy_riemann_so_the_map_is_conformal():
    rng = random.Random(55)
    moved = [(x + rng.uniform(-0.3, 0.3), y + rng.uniform(-0.3, 0.3)) for x, y in L_SHAPE]
    h = 1e-5
    for eta in inside_points(rng, L_SHAPE, 6):
        fx1 = deform((eta[0] + h, eta[1]), L_SHAPE, moved)
        fx0 = deform((eta[0] - h, eta[1]), L_SHAPE, moved)
        fy1 = deform((eta[0], eta[1] + h), L_SHAPE, moved)
        fy0 = deform((eta[0], eta[1] - h), L_SHAPE, moved)
        ux, vx = (fx1[0] - fx0[0]) / (2 * h), (fx1[1] - fx0[1]) / (2 * h)
        uy, vy = (fy1[0] - fy0[0]) / (2 * h), (fy1[1] - fy0[1]) / (2 * h)
        assert abs(ux - vy) < 1e-7
        assert abs(uy + vx) < 1e-7


def test_worked_example():
    # The center of the unit square. By symmetry each phi_i is 1/4.
    phi, psi = green_coordinates((0.5, 0.5), SQUARE)
    assert all(abs(p - 0.25) < 1e-12 for p in phi)
    want = -(1 / (4 * math.pi)) * quad(lambda t: math.log((t - 0.5) ** 2 + 0.25))
    assert all(abs(p - want) < 1e-12 for p in psi)
    assert abs(psi[0] - 0.0893138431) < 1e-9
    # A shear of the cage is not reproduced inside.
    sheared = [(x + 0.5 * y, y) for x, y in SQUARE]
    f = deform((0.25, 0.3), SQUARE, sheared)
    assert abs(f[0] - 0.4468487) < 1e-6 and abs(f[1] - 0.3609747) < 1e-6

History

Lipman, Levin and Cohen-Or presented Green coordinates at SIGGRAPH 2008, after mean value coordinates (Ju, Schaefer and Warren 2005) and harmonic coordinates (Joshi and others 2007) had made cages a common deformation tool. They presented the coordinates as shape preserving: other cage coordinates reproduce affine maps, and so they shear details, while Green coordinates keep angles in 2D. The equality of 2D Green coordinates with a Cauchy integral connects them with complex analysis.

References

  1. Yaron Lipman, David Levin and Daniel Cohen-Or, Green coordinates, SIGGRAPH 2008, ACM Transactions on Graphics 27(3), 2008, the whole paper (the coordinates from Green's third identity, the scaled normals of the deformed cage, and the conformal and quasi-conformal behaviour in 2D and 3D)

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.all
  • a full proof of time.per_point
  • 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
  • History with a source
  • at least three sources
  • a scene preset for the example