import Accelerate import simd /// Accelerate's sparse Cholesky factor of a symmetric positive definite matrix. final class SparseCholesky { private let factor: SparseOpaqueFactorization_Double let size: Int /// `lower` holds the entries on and below the diagonal, keyed by (row, column). init(size: Int, lower: [SIMD2: Double]) { self.size = size let keys = lower.keys.sorted { ($0.y, $0.x) < ($1.y, $1.x) } let rows = keys.map { Int32($0.x) }, columns = keys.map { Int32($0.y) }, values = keys.map { lower[$0]! } var attributes = SparseAttributes_t() attributes.triangle = SparseLowerTriangle attributes.kind = SparseSymmetric let matrix = SparseConvertFromCoordinate(Int32(size), Int32(size), keys.count, 1, attributes, rows, columns, values) defer { SparseCleanup(matrix) } factor = SparseFactor(SparseFactorizationCholesky, matrix) precondition(factor.status == SparseStatusOK, "normal matrix not positive definite") } deinit { SparseCleanup(factor) } func solve(_ values: inout [Double], columns: Int) { values.withUnsafeMutableBufferPointer { buffer in let b = DenseMatrix_Double(rowCount: Int32(size), columnCount: Int32(columns), columnStride: Int32(size), attributes: SparseAttributes_t(), data: buffer.baseAddress!) SparseSolve(factor, b) } } } /// Least squares over the mesh's triangle edges, Σ |x_j − x_i − d_ij|², with the `fixed` vertices /// held where the given positions have them (decision 0002's normal equations, uniform weights). final class EdgeFit { let mesh: Mesh let fixed: [Bool] let row: [Int] let free: [Int] private let factor: SparseCholesky? init(mesh: Mesh, fixed: Set) { self.mesh = mesh self.fixed = mesh.rest.indices.map { fixed.contains($0) } free = mesh.rest.indices.filter { !fixed.contains($0) } var row = Array(repeating: -1, count: mesh.rest.count) for (r, v) in free.enumerated() { row[v] = r } self.row = row var matrix: [SIMD2: Double] = [:] for t in mesh.triangles { for (i, j) in [(t.x, t.y), (t.y, t.z), (t.z, t.x)] { for (v, o) in [(i, j), (j, i)] where row[v] >= 0 { matrix[SIMD2(row[v], row[v]), default: 0] += 1 if row[o] >= 0, row[o] < row[v] { matrix[SIMD2(row[v], row[o]), default: 0] -= 1 } } } } factor = free.isEmpty ? nil : SparseCholesky(size: free.count, lower: matrix) } /// The positions fitting per-triangle edge targets `d[t][k]` for the edge from corner k to /// corner k + 1, holding fixed vertices at `x`'s positions. func fit(_ x: [V3], targets d: [E3]) -> [V3] { guard let factor else { return x } let n = free.count var rhs = [Double](repeating: 0, count: 3 * n) func add(_ r: Int, _ v: V3) { rhs[r] += v.x rhs[n + r] += v.y rhs[2 * n + r] += v.z } for (k, t) in mesh.triangles.enumerated() { let c = [t.x, t.y, t.z], e = [d[k].e0, d[k].e1, d[k].e2] for m in 0..<3 { let i = c[m], j = c[(m + 1) % 3] if row[i] >= 0 { add(row[i], -e[m]) if row[j] < 0 { add(row[i], x[j]) } } if row[j] >= 0 { add(row[j], e[m]) if row[i] < 0 { add(row[j], x[i]) } } } } factor.solve(&rhs, columns: 3) var out = x for (r, v) in free.enumerated() { out[v] = V3(rhs[r], rhs[n + r], rhs[2 * n + r]) } return out } /// Rest edges of each triangle, corner k to corner k + 1, in 3D. lazy var restEdges: [E3] = mesh.triangles.map { t in let p = [mesh.rest[t.x], mesh.rest[t.y], mesh.rest[t.z]].map { V3($0.x, $0.y, 0) } return E3(p[1] - p[0], p[2] - p[1], p[0] - p[2]) } /// Iterative as-rigid-as-possible: alternate each triangle's best rotation from the flat sheet /// with the least-squares fit. Returns the positions and the last change. func arap(_ start: [V3], iterations: Int, tolerance: Double = 0) -> (x: [V3], change: Double) { var x = start var change = 0.0 for _ in 0.. [simd_double3x3] { mesh.triangles.enumerated().map { k, t in bestRotation(rest: restEdges[k], [x[t.x], x[t.y], x[t.z]]) } } } /// The rotation taking a flat triangle (edges `rest`, in z = 0, counterclockwise) to the best fit /// of the triangle `q`: its normal onto q's normal, then the in-plane angle fitted in least squares. func bestRotation(rest: E3, _ q: [V3]) -> simd_double3x3 { let e = [q[1] - q[0], q[2] - q[1], q[0] - q[2]] var n = cross(e[0], -e[2]) let l = length(n) guard l > 1e-300 else { return matrix_identity_double3x3 } n /= l let u = normalize(e[0]), v = cross(n, u) // 2D covariance between rest (x, y) and current (u, v) coordinates var a = 0.0, b = 0.0 for (r, c) in zip([rest.e0, rest.e1, rest.e2], e) { let cu = dot(c, u), cv = dot(c, v) a += r.x * cu + r.y * cv // cos part b += r.x * cv - r.y * cu // sin part } let theta = atan2(b, a) let ex = cos(theta) * u + sin(theta) * v, ey = -sin(theta) * u + cos(theta) * v return simd_double3x3(columns: (ex, ey, n)) } /// Per-triangle rotation from pose a to pose b (both best fits from the flat sheet). func relativeRotations(_ fit: EdgeFit, _ a: [V3], _ b: [V3]) -> [simd_quatd] { zip(fit.rotations(a), fit.rotations(b)).map { ra, rb in var q = simd_quatd(rb * ra.transpose) if q.real < 0 { q = simd_quatd(vector: -q.vector) } return q } } /// Decision 0002's pop generalised to bent poses: at s each triangle's edges are a blend of its /// edges in `a` and in `b` (turned back), turned by s of its rotation from a to b; positions by /// least squares with `fit`'s fixed vertices held. Exact at s = 0 and 1 when both poses agree on /// the fixed vertices. struct Blend { let fit: EdgeFit let a: [V3] let b: [V3] let turns: [simd_quatd] let ea: [E3] let eb: [E3] init(_ fit: EdgeFit, from a: [V3], to b: [V3], turns: [simd_quatd]? = nil) { self.fit = fit self.a = a self.b = b self.turns = turns ?? relativeRotations(fit, a, b) func edges(_ x: [V3]) -> [E3] { fit.mesh.triangles.map { t in E3(x[t.y] - x[t.x], x[t.z] - x[t.y], x[t.x] - x[t.z]) } } ea = edges(a) eb = edges(b) } func at(_ s: Double) -> [V3] { let id = simd_quatd(ix: 0, iy: 0, iz: 0, r: 1) let d = turns.indices.map { k -> E3 in let q = turns[k], qs = simd_slerp(id, q, s), back = q.inverse func one(_ x: V3, _ y: V3) -> V3 { qs.act((1 - s) * x + s * back.act(y)) } return E3(one(ea[k].e0, eb[k].e0), one(ea[k].e1, eb[k].e1), one(ea[k].e2, eb[k].e2)) } // fixed vertices move linearly (they agree in both poses in every use here) var x = a for v in a.indices where fit.fixed[v] { x[v] = (1 - s) * a[v] + s * b[v] } return fit.fit(x, targets: d) } } /// A triangle's three edge vectors, corner k to corner k + 1. struct E3 { var e0: V3, e1: V3, e2: V3 init(_ e0: V3, _ e1: V3, _ e2: V3) { (self.e0, self.e1, self.e2) = (e0, e1, e2) } }