Packages/FoldKit/Sources/Folding/Bending.swift
170 lines · 8827 bytes
1import Accelerate
2import simd
3import Synchronization
4
5/// As-rigid-as-possible interpolation on a render mesh between two rigid poses of the FOLD faces
6/// (decision 0002's pop). At `s` each triangle's edges are its edges in the first pose turned by
7/// its target, and the mesh vertices are the least-squares fit to those edges, with the vertices of
8/// held faces kept where the first pose has them. A triangle's target is `s` of its face's
9/// rotation from the first pose to the second (slerp); for a triangle in `blends` (decision 0003's
10/// band) it is slerp(mid, own, w), where own is that slerp, mid = slerp(own, other, ½), other is
11/// the slerp of the partner face's rotation, and w = weight + (1 − weight)(1 − 4s(1 − s)). At
12/// `s = 0` and `s = 1` every target is the face's own rotation and the fit is exact, so it
13/// reproduces both poses. Tied vertices are one unknown, so they move together.
14struct Bending: Sendable {
15 /// A triangle whose turn is blended toward its partner face's.
16 struct Blend: Sendable {
17 let triangle: Int
18 let partner: Int
19 /// 1 where the triangle keeps its own turn throughout.
20 let weight: Double
21 }
22
23 /// The mesh vertices in the first pose.
24 private let rest: [SIMD3<Double>]
25 /// Per FOLD face, its rotation from the first pose to the second.
26 private let turns: [simd_quatd]
27 /// The blended triangles' faces, partners and weights; the k-th takes target `turns.count + k`.
28 private let blends: [(face: Int, partner: Int, weight: Double)]
29 /// The mesh vertices that move, in the solve's row order, one per tied group.
30 private let free: [Int]
31 /// Per mesh vertex, its row in the solve, or −1 when held.
32 private let rows: [Int]
33 /// Per row and target, the signed sum of the rest edge vectors of that target's triangles at
34 /// the row's vertex; the right-hand side adds each turned by the target at `s`. Targets are the
35 /// FOLD faces, then the blended triangles.
36 private let terms: [(row: Int, target: Int, vector: SIMD3<Double>)]
37 /// Per row, what the held vertices contribute to the normal equation's right-hand side.
38 private let held: [SIMD3<Double>]
39 private let factor: SparseCholesky
40
41 /// - Parameters:
42 /// - first, second: the FOLD vertex positions of two rigid poses.
43 /// - heldFaces: FOLD faces placed alike in both poses, whose mesh vertices stay put.
44 /// - blends: triangles whose turns blend toward a partner face's.
45 /// - ties: groups of mesh vertices solved as one unknown; a group with a held vertex is held.
46 init(mesh: RenderMesh, faces: [[Int]], from first: [SIMD3<Double>], to second: [SIMD3<Double>],
47 heldFaces: Set<Int>, blends: [Blend] = [], ties: [[Int]] = []) {
48 rest = mesh.pose(first)
49 turns = faces.map { corners in
50 // one corner triple for both poses, chosen on the flat sheet so ties cannot split
51 let flat = corners.map { mesh.vertices[mesh.meshVertexOf[$0]] }
52 let c = widestCorners(flat).map { corners[$0] }
53 var q = simd_quatd(frame(c.map { second[$0] }) * frame(c.map { first[$0] }).transpose)
54 if q.real < 0 { q = simd_quatd(vector: -q.vector) }
55 return q
56 }
57 self.blends = blends.map { (mesh.faceOf[$0.triangle], $0.partner, $0.weight) }
58 var target = mesh.faceOf
59 for (k, blend) in blends.enumerated() { target[blend.triangle] = faces.count + k }
60
61 var isHeld = Array(repeating: false, count: mesh.vertices.count)
62 for (t, (a, b, c)) in mesh.triangles.enumerated() where heldFaces.contains(mesh.faceOf[t]) {
63 (isHeld[a], isHeld[b], isHeld[c]) = (true, true, true)
64 }
65 for group in ties where group.contains(where: { isHeld[$0] }) {
66 for v in group { isHeld[v] = true }
67 }
68 var representative = Array(mesh.vertices.indices)
69 for group in ties {
70 for v in group { representative[v] = group[0] }
71 }
72 free = mesh.vertices.indices.filter { !isHeld[$0] && representative[$0] == $0 }
73 var row = Array(repeating: -1, count: mesh.vertices.count)
74 for (r, v) in free.enumerated() { row[v] = r }
75 for v in mesh.vertices.indices where !isHeld[v] { row[v] = row[representative[v]] }
76 rows = row
77
78 // Σ over triangle edges (i, j) of |x_j − x_i − d_ij|²: the normal matrix is the edge
79 // Laplacian; held vertices move to the right-hand side.
80 var matrix: [SIMD2<Int>: Double] = [:]
81 var sums: [SIMD2<Int>: SIMD3<Double>] = [:]
82 var held = Array(repeating: SIMD3<Double>.zero, count: free.count)
83 for (t, (a, b, c)) in mesh.triangles.enumerated() {
84 for (i, j) in [(a, b), (b, c), (c, a)] where row[i] < 0 || row[i] != row[j] {
85 let d = rest[j] - rest[i]
86 for (v, other, sign) in [(i, j, -1.0), (j, i, 1.0)] where row[v] >= 0 {
87 matrix[SIMD2(row[v], row[v]), default: 0] += 1
88 sums[SIMD2(row[v], target[t]), default: .zero] += sign * d
89 if row[other] >= 0 {
90 if row[other] < row[v] { matrix[SIMD2(row[v], row[other]), default: 0] -= 1 }
91 } else {
92 held[row[v]] += rest[other]
93 }
94 }
95 }
96 }
97 terms = sums.keys.sorted { ($0.x, $0.y) < ($1.x, $1.y) }.map { ($0.x, $0.y, sums[$0]!) }
98 self.held = held
99 factor = SparseCholesky(size: free.count, lower: matrix)
100 }
101
102 /// The mesh vertex positions at `s` in 0...1.
103 func positions(at s: Double) -> [SIMD3<Double>] {
104 let identity = simd_quatd(ix: 0, iy: 0, iz: 0, r: 1)
105 var turned = turns.map { simd_slerp(identity, $0, s) }
106 let middle = 1 - 4 * s * (1 - s)
107 turned += blends.map { face, partner, weight in
108 let own = turned[face]
109 return simd_slerp(simd_slerp(own, turned[partner], 0.5), own, weight + (1 - weight) * middle)
110 }
111 let n = free.count
112 var rhs = [Double](repeating: 0, count: 3 * n)
113 for (r, h) in held.enumerated() {
114 rhs[r] = h.x
115 rhs[n + r] = h.y
116 rhs[2 * n + r] = h.z
117 }
118 for (r, target, vector) in terms {
119 let d = turned[target].act(vector)
120 rhs[r] += d.x
121 rhs[n + r] += d.y
122 rhs[2 * n + r] += d.z
123 }
124 factor.solve(&rhs, columns: 3)
125 var result = rest
126 for (v, r) in rows.enumerated() where r >= 0 { result[v] = SIMD3(rhs[r], rhs[n + r], rhs[2 * n + r]) }
127 return result
128 }
129}
130
131/// An orthonormal frame fixed to the triangle `p`: along its first side, across it in its plane,
132/// and along its normal.
133private func frame(_ p: [SIMD3<Double>]) -> simd_double3x3 {
134 let along = normalize(p[1] - p[0]), normal = normalize(cross(p[1] - p[0], p[2] - p[0]))
135 return simd_double3x3(columns: (along, cross(normal, along), normal))
136}
137
138/// Accelerate's sparse Cholesky factor of a symmetric positive definite matrix. Solves are
139/// serialised: Accelerate does not document concurrent `SparseSolve` calls on one factor as safe.
140private final class SparseCholesky: @unchecked Sendable {
141 private let factor: SparseOpaqueFactorization_Double
142 private let size: Int
143 private let lock = Mutex(())
144
145 /// `lower` holds the entries on and below the diagonal, keyed by (row, column).
146 init(size: Int, lower: [SIMD2<Int>: Double]) {
147 self.size = size
148 let keys = lower.keys.sorted { ($0.y, $0.x) < ($1.y, $1.x) }
149 let rows = keys.map { Int32($0.x) }, columns = keys.map { Int32($0.y) }, values = keys.map { lower[$0]! }
150 var attributes = SparseAttributes_t()
151 attributes.triangle = SparseLowerTriangle
152 attributes.kind = SparseSymmetric
153 let matrix = SparseConvertFromCoordinate(Int32(size), Int32(size), keys.count, 1, attributes,
154 rows, columns, values)
155 defer { SparseCleanup(matrix) }
156 factor = SparseFactor(SparseFactorizationCholesky, matrix)
157 precondition(factor.status == SparseStatusOK, "the pop's normal matrix is not positive definite")
158 }
159
160 deinit { SparseCleanup(factor) }
161
162 /// Solves in place for `columns` right-hand sides of `size` values each, one after another.
163 func solve(_ values: inout [Double], columns: Int) {
164 values.withUnsafeMutableBufferPointer { buffer in
165 let b = DenseMatrix_Double(rowCount: Int32(size), columnCount: Int32(columns), columnStride: Int32(size),
166 attributes: SparseAttributes_t(), data: buffer.baseAddress!)
167 lock.withLock { _ in SparseSolve(factor, b) }
168 }
169 }
170}