spikes/interpolation/Sources/Spike/Bending.swift

181 lines · 7913 bytes

9 symbols in this file
  1import simd
  2
  3/// As-rigid-as-possible interpolation between rigid poses, on a mesh finer
  4/// than the crease pattern. Each small triangle's rotation is interpolated
  5/// (slerp) from one pose to the next, and the vertex positions that best fit
  6/// those rotated edges are solved by least squares. Where the poses cannot be
  7/// joined rigidly, the paper bends and stretches; the strain is the largest
  8/// relative change in an edge's length.
  9struct Bending {
 10    let coarse: Sheet
 11    let kinematics: Kinematics
 12    let fine: Sheet
 13    /// The coarse face each fine face lies in.
 14    let parent: [Int]
 15    let triangles: [(Int, Int, Int)]
 16    let pinned: [Int]
 17    let factor: [[Double]]   // Cholesky factor of the normal matrix
 18
 19    init(_ coarse: Sheet, _ kinematics: Kinematics, spacing: Double, creases: [(V2, V2)], pinFace: Int) {
 20        self.coarse = coarse
 21        self.kinematics = kinematics
 22        let xs = coarse.verts.map(\.x), ys = coarse.verts.map(\.y)
 23        var grid: [(V2, V2)] = []
 24        var x = xs.min()! + spacing
 25        while x < xs.max()! - 1e-9 { grid.append((V2(x, ys.min()!), V2(x, ys.max()!))); x += spacing }
 26        var y = ys.min()! + spacing
 27        while y < ys.max()! - 1e-9 { grid.append((V2(xs.min()!, y), V2(xs.max()!, y))); y += spacing }
 28        let boundary = [V2(xs.min()!, ys.min()!), V2(xs.max()!, ys.min()!), V2(xs.max()!, ys.max()!), V2(xs.min()!, ys.max()!)]
 29        let fine = Sheet(boundary: boundary, creases: creases + grid)
 30        self.fine = fine
 31        let parent = fine.faces.map { f in
 32            let c = f.map { fine.verts[$0] }.reduce(V2.zero, +) / Double(f.count)
 33            return coarse.face(containing: c)
 34        }
 35        self.parent = parent
 36        var tris: [(Int, Int, Int)] = []
 37        for f in fine.faces { for k in 1..<(f.count - 1) { tris.append((f[0], f[k], f[k + 1])) } }
 38        self.triangles = tris
 39        let pinnedSet = Set(fine.faces.indices.filter { parent[$0] == pinFace }.flatMap { fine.faces[$0] })
 40        self.pinned = Array(pinnedSet)
 41
 42        // Normal matrix of Σ |x_j − x_i − d_ij|² + w Σ |x_p − target|², one per coordinate.
 43        let n = fine.verts.count
 44        var A = Array(repeating: [Double](repeating: 0, count: n), count: n)
 45        for (a, b, c) in tris {
 46            for (i, j) in [(a, b), (b, c), (c, a)] {
 47                A[i][i] += 1; A[j][j] += 1; A[i][j] -= 1; A[j][i] -= 1
 48            }
 49        }
 50        for p in pinnedSet { A[p][p] += 1e6 }
 51        self.factor = cholesky(A)
 52    }
 53
 54    /// Fine-vertex positions of a rigid coarse pose.
 55    func pose(_ angles: [Double]) -> [V3] {
 56        let T = kinematics.transforms(angles)
 57        var out = [V3](repeating: .zero, count: fine.verts.count)
 58        for (f, face) in fine.faces.enumerated() {
 59            for v in face { out[v] = T[parent[f]].apply(V3(fine.verts[v], 0)) }
 60        }
 61        return out
 62    }
 63
 64    /// Each coarse face's rotation in a pose.
 65    func rotations(_ angles: [Double]) -> [simd_quatd] { kinematics.transforms(angles).map(\.q) }
 66
 67    /// Positions at s in 0…1 between two rigid poses.
 68    func interpolate(from a: [Double], to b: [Double], at s: Double) -> [V3] {
 69        let qa = rotations(a), qb = rotations(b)
 70        let rest = pose(a)
 71        let target = pose(b)
 72        let pinTarget = rest.indices.map { simd_mix(rest[$0], target[$0], V3(repeating: s)) }
 73        let n = fine.verts.count
 74        var rhs = [V3](repeating: .zero, count: n)
 75        var faceOfTriangle: [Int] = []
 76        for (f, face) in fine.faces.enumerated() { for _ in 1..<(face.count - 1) { faceOfTriangle.append(f) } }
 77        for (t, (a0, b0, c0)) in triangles.enumerated() {
 78            let f = parent[faceOfTriangle[t]]
 79            var q1 = qb[f] * qa[f].inverse
 80            if q1.real < 0 { q1 = simd_quatd(vector: -q1.vector) }
 81            let q = simd_slerp(simd_quatd(ix: 0, iy: 0, iz: 0, r: 1), q1, s)
 82            for (i, j) in [(a0, b0), (b0, c0), (c0, a0)] {
 83                let d = q.act(rest[j] - rest[i])
 84                rhs[j] += d; rhs[i] -= d
 85            }
 86        }
 87        for p in pinned { rhs[p] += 1e6 * pinTarget[p] }
 88        var out = [V3](repeating: .zero, count: n)
 89        for k in 0..<3 {
 90            let col = cholSolve(factor, rhs.map { $0[k] })
 91            for i in 0..<n { out[i][k] = col[i] }
 92        }
 93        return out
 94    }
 95
 96    /// Largest relative change in an edge's length, over edges at least
 97    /// `outside` from `center` on the sheet.
 98    func strain(_ x: [V3], outside: Double = 0, center: V2 = .zero) -> Double {
 99        var worst = 0.0
100        for (a, b, c) in triangles {
101            for (i, j) in [(a, b), (b, c), (c, a)] {
102                if outside > 0, simd_distance((fine.verts[i] + fine.verts[j]) / 2, center) < outside { continue }
103                let rest = simd_distance(fine.verts[i], fine.verts[j])
104                worst = max(worst, abs(simd_distance(x[i], x[j]) - rest) / rest)
105            }
106        }
107        return worst
108    }
109
110    func triangleSoup(_ x: [V3]) -> [[V3]] { triangles.map { [x[$0.0], x[$0.1], x[$0.2]] } }
111}
112
113func cholesky(_ A: [[Double]]) -> [[Double]] {
114    let n = A.count
115    var L = Array(repeating: [Double](repeating: 0, count: n), count: n)
116    for j in 0..<n {
117        var s = A[j][j]
118        for k in 0..<j { s -= L[j][k] * L[j][k] }
119        L[j][j] = s.squareRoot()
120        for i in (j + 1)..<n {
121            var t = A[i][j]
122            for k in 0..<j { t -= L[i][k] * L[j][k] }
123            L[i][j] = t / L[j][j]
124        }
125    }
126    return L
127}
128
129func cholSolve(_ L: [[Double]], _ b: [Double]) -> [Double] {
130    let n = b.count
131    var y = b
132    for i in 0..<n { for k in 0..<i { y[i] -= L[i][k] * y[k] }; y[i] /= L[i][i] }
133    for i in stride(from: n - 1, through: 0, by: -1) { for k in (i + 1)..<n { y[i] -= L[k][i] * y[k] }; y[i] /= L[i][i] }
134    return y
135}
136
137extension Bending {
138    /// Iterative as-rigid-as-possible deformation: hold `handles` at their
139    /// targets and find the least-strained positions for the rest, alternating
140    /// a best-fit rotation per triangle with a least-squares solve.
141    func deform(start x0: [V3], handles: [Int: V3], iterations: Int = 40) -> [V3] {
142        let n = fine.verts.count
143        var A = Array(repeating: [Double](repeating: 0, count: n), count: n)
144        for (a, b, c) in triangles {
145            for (i, j) in [(a, b), (b, c), (c, a)] {
146                A[i][i] += 1; A[j][j] += 1; A[i][j] -= 1; A[j][i] -= 1
147            }
148        }
149        for (h, _) in handles { A[h][h] += 1e6 }
150        let L = cholesky(A)
151        let rest = fine.verts.map { V3($0, 0) }
152        var x = x0
153        for _ in 0..<iterations {
154            var rhs = [V3](repeating: .zero, count: n)
155            for (a, b, c) in triangles {
156                // Best rotation taking the rest triangle to the current one.
157                let p = [rest[a], rest[b], rest[c]], q = [x[a], x[b], x[c]]
158                var M = simd_double3x3()
159                for (i, j) in [(0, 1), (1, 2), (2, 0)] {
160                    let dq = q[j] - q[i], dp = p[j] - p[i]
161                    M += simd_double3x3(columns: (dq * dp.x, dq * dp.y, dq * dp.z))
162                }
163                let nq = simd_normalize(simd_cross(q[1] - q[0], q[2] - q[0]))
164                let scale = simd_length(simd_cross(p[1] - p[0], p[2] - p[0]))
165                M += simd_double3x3(columns: (.zero, .zero, nq * scale))
166                var R = M
167                for _ in 0..<30 { R = 0.5 * (R + R.inverse.transpose) }
168                for (i, j) in [(a, b), (b, c), (c, a)] {
169                    let d = R * (rest[j] - rest[i])
170                    rhs[j] += d; rhs[i] -= d
171                }
172            }
173            for (h, target) in handles { rhs[h] += 1e6 * target }
174            for k in 0..<3 {
175                let col = cholSolve(L, rhs.map { $0[k] })
176                for i in 0..<n { x[i][k] = col[i] }
177            }
178        }
179        return x
180    }
181}