import FoldFormat import Folding import simd /// A render mesh on the crease pattern: triangles finer than the FOLD faces, each inside one face, /// counterclockwise on the flat sheet, sharing vertices across creases. struct Mesh { var rest: [V2] var triangles: [SIMD3] /// The FOLD face each triangle lies in. var faceOf: [Int] /// The mesh vertex at each FOLD vertex. var foldVertex: [Int] /// Per mesh vertex: a face containing it and its coordinates on that face's widest corners. var anchors: [(corners: SIMD3, a: Double, b: Double)] = [] init(rest: [V2], triangles: [SIMD3], faceOf: [Int], foldVertex: [Int], model: Model) { self.rest = rest self.faceOf = faceOf self.foldVertex = foldVertex // counterclockwise on the sheet self.triangles = triangles.map { t in cross2(rest[t.y] - rest[t.x], rest[t.z] - rest[t.x]) >= 0 ? t : SIMD3(t.x, t.z, t.y) } var faceOfVertex = Array(repeating: -1, count: rest.count) for (k, t) in self.triangles.enumerated() { for v in [t.x, t.y, t.z] where faceOfVertex[v] < 0 { faceOfVertex[v] = faceOf[k] } } anchors = rest.indices.map { v in let f = faceOfVertex[v] precondition(f >= 0, "mesh vertex \(v) at \(rest[v]) is in no triangle; \(rest.count) vertices, \(foldVertex.count) FOLD") let c = widest(model.faces[f].map { model.flat[$0] }).map { model.faces[f][$0] } let o = model.flat[c[0]], u = model.flat[c[1]] - o, w = model.flat[c[2]] - o, p = rest[v] - o let det = cross2(u, w) return (SIMD3(c[0], c[1], c[2]), cross2(p, w) / det, cross2(u, p) / det) } } /// A bare triangulation (no FOLD faces), for a proxy sheet. init(rest: [V2], triangles: [SIMD3]) { self.rest = rest self.triangles = triangles.map { t in cross2(rest[t.y] - rest[t.x], rest[t.z] - rest[t.x]) >= 0 ? t : SIMD3(t.x, t.z, t.y) } faceOf = Array(repeating: 0, count: triangles.count) foldVertex = [] } /// The mesh vertices when the FOLD vertices are at `x`, each face placed rigidly. func pose(_ x: [V3]) -> [V3] { anchors.map { an in let o = x[an.corners.x] return o + an.a * (x[an.corners.y] - o) + an.b * (x[an.corners.z] - o) } } /// Each edge once. var edges: [SIMD2] { var set = Set>() for t in triangles { for (i, j) in [(t.x, t.y), (t.y, t.z), (t.z, t.x)] { set.insert(SIMD2(min(i, j), max(i, j))) } } return set.sorted { ($0.x, $0.y) < ($1.x, $1.y) } } struct Stats { var vertices: Int var triangles: Int var shortestEdge: Double var smallestAngle: Double } var stats: Stats { let shortest = edges.map { simd_distance(rest[$0.x], rest[$0.y]) }.min() ?? 0 var smallest = 180.0 for t in triangles { let p = [rest[t.x], rest[t.y], rest[t.z]] for k in 0..<3 { let a = p[(k + 1) % 3] - p[k], b = p[(k + 2) % 3] - p[k] smallest = min(smallest, acos(max(-1, min(1, dot(a, b) / (length(a) * length(b))))) * 180 / .pi) } } return Stats(vertices: rest.count, triangles: triangles.count, shortestEdge: shortest, smallestAngle: smallest) } /// The mesh vertices of `faces`. func vertices(of faces: Set) -> Set { var out = Set() for (k, t) in triangles.enumerated() where faces.contains(faceOf[k]) { out.formUnion([t.x, t.y, t.z]) } return out } } /// The largest relative change in a mesh edge's length against the flat sheet. func strain(_ x: [V3], _ mesh: Mesh, edges: [SIMD2]) -> Double { var worst = 0.0 for e in edges { let rest = simd_distance(mesh.rest[e.x], mesh.rest[e.y]) worst = max(worst, abs(simd_distance(x[e.x], x[e.y]) - rest) / rest) } return worst } /// The largest principal strain of any triangle: the singular values σ of the map from the flat /// triangle to the current one, max |σ − 1|. Unlike edge strain it does not depend on which /// directions the mesh's edges happen to run in. func principalStrain(_ x: [V3], _ mesh: Mesh) -> Double { var worst = 0.0 for t in mesh.triangles { let p0 = mesh.rest[t.x], e1 = mesh.rest[t.y] - p0, e2 = mesh.rest[t.z] - p0 let q0 = x[t.x], f1 = x[t.y] - q0, f2 = x[t.z] - q0 // F = [f1 f2] [e1 e2]^-1 (3×2); singular values from FᵀF let det = cross2(e1, e2) let i11 = e2.y / det, i12 = -e2.x / det, i21 = -e1.y / det, i22 = e1.x / det let c1 = f1 * i11 + f2 * i21, c2 = f1 * i12 + f2 * i22 let a = dot(c1, c1), b = dot(c1, c2), d = dot(c2, c2) let mean = (a + d) / 2, diff = ((a - d) * (a - d) / 4 + b * b).squareRoot() let s1 = (mean + diff).squareRoot(), s2 = max(0, mean - diff).squareRoot() worst = max(worst, abs(s1 - 1), abs(s2 - 1)) } return worst } /// The edge with the largest strain, its rest length and where it is on the sheet. func worstEdge(_ x: [V3], _ mesh: Mesh, edges: [SIMD2]) -> (strain: Double, rest: Double, at: V2) { var best = (0.0, 0.0, V2.zero) for e in edges { let rest = simd_distance(mesh.rest[e.x], mesh.rest[e.y]) let s = abs(simd_distance(x[e.x], x[e.y]) - rest) / rest if s > best.0 { best = (s, rest, (mesh.rest[e.x] + mesh.rest[e.y]) / 2) } } return best } // MARK: - Constructions enum MeshKind: String, CaseIterable { /// Decision 0002's: frame 0's faces cut by grid lines every `spacing`, cells fanned (FoldKit's RenderMesh). case grid /// The grid with every edge shorter than a quarter of the spacing collapsed onto a crease-pattern /// vertex or along its crease. case collapsed /// Per face: each crease divided evenly at about `spacing`, a triangular lattice inside the face /// kept half a spacing from its boundary, triangulated Delaunay within the face. case delaunay } func buildMesh(_ kind: MeshKind, _ model: Model, spacing h: Double) -> Mesh { switch kind { case .grid: return gridMesh(model, spacing: h) case .collapsed: return collapsed(gridMesh(model, spacing: h), model, below: 0.25 * h) case .delaunay: return delaunayMesh(model, spacing: h) } } func gridMesh(_ model: Model, spacing h: Double) -> Mesh { let r = RenderMesh(file: model.file, spacing: h) // RenderMesh can hold points that no triangle uses (cells that collapse to fewer than three) var used = Array(repeating: false, count: r.vertices.count) for t in r.triangles { used[t.0] = true; used[t.1] = true; used[t.2] = true } var index = Array(repeating: -1, count: r.vertices.count) var rest: [V2] = [] for v in r.vertices.indices where used[v] { index[v] = rest.count; rest.append(r.vertices[v]) } return Mesh(rest: rest, triangles: r.triangles.map { SIMD3(index[$0.0], index[$0.1], index[$0.2]) }, faceOf: r.faceOf, foldVertex: r.meshVertexOf.map { index[$0] }, model: model) } /// Collapses every edge shorter than `threshold`: an interior vertex moves onto the other end, a /// vertex on a crease moves along it onto another point of it or its end; FOLD vertices stay. A /// collapse that would flip or flatten a triangle is skipped. func collapsed(_ mesh: Mesh, _ model: Model, below threshold: Double) -> Mesh { let tol = model.size * 1e-9 // the crease each mesh vertex lies on, -1 inside a face, -2 for a FOLD vertex var onEdge = Array(repeating: -1, count: mesh.rest.count) for v in mesh.foldVertex { onEdge[v] = -2 } for v in mesh.rest.indices where onEdge[v] == -1 { for (e, ends) in model.edges.enumerated() { let a = model.flat[ends[0]], b = model.flat[ends[1]], p = mesh.rest[v] let t = dot(p - a, b - a) / dot(b - a, b - a) if t > 0, t < 1, simd_distance(a + t * (b - a), p) < tol { onEdge[v] = e; break } } } var tris = mesh.triangles var faceOf = mesh.faceOf var alive = Array(repeating: true, count: tris.count) var position = mesh.rest func canMove(_ x: Int, to y: Int) -> Bool { switch onEdge[x] { case -2: return false case -1: return true default: let e = onEdge[x] return onEdge[y] == e || model.edges[e].contains { mesh.foldVertex[$0] == y } } } var changed = true while changed { changed = false var short: [(Double, Int, Int)] = [] for (k, t) in tris.enumerated() where alive[k] { for (i, j) in [(t.x, t.y), (t.y, t.z), (t.z, t.x)] where i < j { let d = simd_distance(position[i], position[j]) if d < threshold { short.append((d, i, j)) } } } short.sort { $0.0 < $1.0 } var touched = Set() for (_, i, j) in short where !touched.contains(i) && !touched.contains(j) { for (x, y) in [(i, j), (j, i)] where canMove(x, to: y) { // triangles around x without y must keep their orientation and some area let around = tris.indices.filter { alive[$0] && [tris[$0].x, tris[$0].y, tris[$0].z].contains(x) } let ok = around.allSatisfy { k in let t = tris[k] if [t.x, t.y, t.z].contains(y) { return true } let p = [t.x, t.y, t.z].map { $0 == x ? position[y] : position[$0] } let area = cross2(p[1] - p[0], p[2] - p[0]) / 2 return area > threshold * threshold * 1e-3 } guard ok else { continue } for k in around { let t = tris[k] if [t.x, t.y, t.z].contains(y) { alive[k] = false; continue } tris[k] = SIMD3(t.x == x ? y : t.x, t.y == x ? y : t.y, t.z == x ? y : t.z) } touched.formUnion([x, y]) changed = true break } } } // drop unused vertices var used = Array(repeating: false, count: position.count) for (k, t) in tris.enumerated() where alive[k] { used[t.x] = true; used[t.y] = true; used[t.z] = true } var newIndex = Array(repeating: -1, count: position.count) var rest: [V2] = [] for v in position.indices where used[v] { newIndex[v] = rest.count; rest.append(position[v]) } let keep = tris.indices.filter { alive[$0] } faceOf = keep.map { faceOf[$0] } position = rest return Mesh(rest: rest, triangles: keep.map { SIMD3(newIndex[tris[$0].x], newIndex[tris[$0].y], newIndex[tris[$0].z]) }, faceOf: faceOf, foldVertex: mesh.foldVertex.map { newIndex[$0] }, model: model) } /// See `MeshKind.delaunay`. `lines` adds segments the mesh must have edges along (bend lines). func delaunayMesh(_ model: Model, spacing h: Double, margin: Double = 0.6) -> Mesh { var points = model.flat var key: [SIMD2: Int] = [:] let q = model.size * 1e-9 func id(_ p: V2) -> Int { let k = SIMD2(Int64((p.x / q).rounded()), Int64((p.y / q).rounded())) if let i = key[k] { return i } points.append(p) key[k] = points.count - 1 return points.count - 1 } for (v, p) in model.flat.enumerated() { key[SIMD2(Int64((p.x / q).rounded()), Int64((p.y / q).rounded()))] = v } // each crease divided evenly var along: [[Int]] = [] for ends in model.edges { let a = model.flat[ends[0]], b = model.flat[ends[1]] let n = max(1, Int((simd_distance(a, b) / h).rounded())) along.append([ends[0]] + (1..] = [] var faceOf: [Int] = [] for (f, face) in model.faces.enumerated() { var poly = face.map { model.flat[$0] } var corners = face if polygonArea(poly) < 0 { poly.reverse() corners.reverse() } var boundary: [Int] = [] for k in corners.indices { let a = corners[k], b = corners[(k + 1) % corners.count] let e = edgeIndex[SIMD2(min(a, b), max(a, b))]! let run = model.edges[e][0] == a ? along[e] : along[e].reversed() boundary += run.dropLast() } var inside: [Int] = [] let fl = poly.reduce(poly[0], simd_min), fh = poly.reduce(poly[0], simd_max) var j = Int(((fl.y - lo.y) / rowStep).rounded(.down)) while lo.y + Double(j) * rowStep <= fh.y { let y = lo.y + Double(j) * rowStep let shift = j % 2 == 0 ? 0 : 0.5 var i = Int(((fl.x - lo.x) / h - shift).rounded(.down)) while lo.x + (Double(i) + shift) * h <= fh.x { let p = V2(lo.x + (Double(i) + shift) * h, y) if distanceInside(poly, p) >= margin * h { inside.append(id(p)) } i += 1 } j += 1 } _ = hi let made = triangulate(boundary: boundary, inside: inside, points) precondition(Set(boundary + inside).isSubset(of: Set(made.flatMap { [$0.x, $0.y, $0.z] })), "face \(f) lost a point") for t in made { triangles.append(t) faceOf.append(f) } } return Mesh(rest: points, triangles: triangles, faceOf: faceOf, foldVertex: Array(model.flat.indices), model: model) } func polygonArea(_ p: [V2]) -> Double { var a = 0.0 for k in p.indices { a += cross2(p[k], p[(k + 1) % p.count]) } return a / 2 } /// The distance from `p` to the nearest side of a convex counterclockwise polygon, negative outside. func distanceInside(_ poly: [V2], _ p: V2) -> Double { var d = Double.infinity for k in poly.indices { let a = poly[k], b = poly[(k + 1) % poly.count] d = min(d, cross2(b - a, p - a) / length(b - a)) } return d } /// A Delaunay triangulation of a convex polygon, its boundary points counterclockwise (straight /// runs allowed), with `inside` points strictly inside; boundary edges are kept. func triangulate(boundary: [Int], inside: [Int], _ p: [V2]) -> [SIMD3] { func area(_ a: Int, _ b: Int, _ c: Int) -> Double { cross2(p[b] - p[a], p[c] - p[a]) / 2 } var tris: [SIMD3] = [] // ear clipping on the boundary, strict corners only var ring = boundary let scale = ring.map { simd_length_squared(p[$0] - p[ring[0]]) }.max() ?? 1 while ring.count > 3 { var best = -1, bestArea = 0.0 for k in ring.indices { let i = ring[(k + ring.count - 1) % ring.count], j = ring[k], l = ring[(k + 1) % ring.count] let a = area(i, j, l) guard a > bestArea else { continue } // no other ring point on or inside the ear (a straight run along its new side) let blocked = ring.contains { m in m != i && m != j && m != l && area(i, j, m) >= -1e-12 * scale && area(j, l, m) >= -1e-12 * scale && area(l, i, m) >= -1e-12 * scale } if !blocked { (best, bestArea) = (k, a) } } if best < 0 || bestArea < 1e-14 * scale { break } tris.append(SIMD3(ring[(best + ring.count - 1) % ring.count], ring[best], ring[(best + 1) % ring.count])) ring.remove(at: best) } if ring.count == 3, area(ring[0], ring[1], ring[2]) > 0 { tris.append(SIMD3(ring[0], ring[1], ring[2])) } precondition(!tris.isEmpty, "a face did not triangulate") let constrained = Set((0..= -1e-12 * total }) else { continue } if let zero = w.firstIndex(where: { abs($0) <= 1e-9 * total }) { // on an edge: split both triangles let c = [t.x, t.y, t.z] let a = c[(zero + 1) % 3], b = c[(zero + 2) % 3], opposite = c[zero] tris[k] = SIMD3(opposite, a, v) tris.append(SIMD3(opposite, v, b)) if let n = tris.indices.first(where: { n in let u = [tris[n].x, tris[n].y, tris[n].z] return n != k && u.contains(a) && u.contains(b) && !u.contains(v) }) { let u = [tris[n].x, tris[n].y, tris[n].z] let other = u.first { $0 != a && $0 != b }! tris[n] = SIMD3(other, b, v) tris.append(SIMD3(other, v, a)) } } else { tris[k] = SIMD3(t.x, t.y, v) tris.append(SIMD3(t.y, t.z, v)) tris.append(SIMD3(t.z, t.x, v)) } placed = true break } precondition(placed, "an interior point is outside its face") } // Lawson flips to Delaunay func inCircle(_ a: Int, _ b: Int, _ c: Int, _ d: Int) -> Bool { let pa = p[a] - p[d], pb = p[b] - p[d], pc = p[c] - p[d] let det = (pa.x * pa.x + pa.y * pa.y) * cross2(pb, pc) - (pb.x * pb.x + pb.y * pb.y) * cross2(pa, pc) + (pc.x * pc.x + pc.y * pc.y) * cross2(pa, pb) return det > 1e-15 * scale * scale } var flipped = true var rounds = 0 while flipped && rounds < 1000 { flipped = false rounds += 1 var owner: [SIMD2: [(Int, Int)]] = [:] for (k, t) in tris.enumerated() { let c = [t.x, t.y, t.z] for i in 0..<3 { let a = c[i], b = c[(i + 1) % 3] owner[SIMD2(min(a, b), max(a, b)), default: []].append((k, c[(i + 2) % 3])) } } var done = Set() for (edge, sides) in owner where sides.count == 2 && !constrained.contains(edge) { let (k1, c1) = sides[0], (k2, c2) = sides[1] guard !done.contains(k1), !done.contains(k2) else { continue } let t = tris[k1] let c = [t.x, t.y, t.z] let i = c.firstIndex(of: c1)! let a = c[(i + 1) % 3], b = c[(i + 2) % 3] guard inCircle(c1, a, b, c2) else { continue } // the flip must give two counterclockwise triangles guard area(c1, a, c2) > 0, area(c2, b, c1) > 0 else { continue } tris[k1] = SIMD3(c1, a, c2) tris[k2] = SIMD3(c2, b, c1) done.formUnion([k1, k2]) flipped = true _ = edge } } return tris }