import FoldFormat import simd /// The triangles the renderer draws, finer than the FOLD faces (decision 0003). Each side of each /// frame 0 face is divided into round(length / `spacing`) equal parts; inside each face, points of /// a triangular lattice `spacing` apart are kept at least 0.6 `spacing` from its sides; each face /// is triangulated on those points by ear clipping, point insertion and Lawson flips, so it is /// Delaunay within the face. Faces sharing a side share its points, so the mesh is one connected /// sheet. The FOLD topology is unchanged; a non-rigid step bends this mesh, not the FOLD faces. /// The construction assumes convex faces, which the validator enforces. public struct RenderMesh: Sendable { /// Frame 0 positions in its plane. public let vertices: [SIMD2] public let triangles: [(Int, Int, Int)] /// The FOLD face each triangle lies in. public let faceOf: [Int] /// The mesh vertex at each FOLD vertex. public let meshVertexOf: [Int] /// Each mesh vertex as a point of one FOLD face, for placing it in a rigid pose. private let anchors: [Anchor] /// A point of a face: `corners[0] + a·(corners[1] − corners[0]) + b·(corners[2] − corners[0])`. private struct Anchor: Sendable { let corners: SIMD3 let a: Double let b: Double } public init(file: FoldFile, spacing: Double) { let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) } let lower = flat.dropFirst().reduce(flat[0], simd_min) let upper = flat.dropFirst().reduce(flat[0], simd_max) let tolerance = (upper - lower).max() * 1e-9 let rowSpacing = spacing * 3.0.squareRoot() / 2 var points = PointSet(tolerance: tolerance) let meshVertexOf = flat.map { points.index(of: $0) } // each side's points from its lower-numbered end, so both faces compute the same ones var sides: [SIMD2: [Int]] = [:] func side(_ a: Int, _ b: Int) -> [Int] { let key = SIMD2(min(a, b), max(a, b)) if sides[key] == nil { let p = flat[key.x], q = flat[key.y] let parts = max(1, Int((simd_distance(p, q) / spacing).rounded())) sides[key] = [meshVertexOf[key.x]] + (1..= 0.6 * spacing { inside.append(points.index(of: p)) } column += 1 } row += 1 } for triangle in triangulate(boundary: boundary, inside: inside, points.points) { triangles.append(triangle) faceOf.append(f) } let widest = widestCorners(outline) let origin = outline[widest[0]] let u = outline[widest[1]] - origin, v = outline[widest[2]] - origin let det = u.x * v.y - u.y * v.x for id in boundary + inside where anchors[id] == nil { let w = points.points[id] - origin anchors[id] = Anchor(corners: SIMD3(face[widest[0]], face[widest[1]], face[widest[2]]), a: (w.x * v.y - w.y * v.x) / det, b: (u.x * w.y - u.y * w.x) / det) } } self.meshVertexOf = meshVertexOf vertices = points.points self.triangles = triangles self.faceOf = faceOf self.anchors = vertices.indices.map { anchors[$0]! } } /// Frame 0's bounding box's longer side / 32. public static func spacing(for file: FoldFile) -> Double { let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) } let lower = flat.dropFirst().reduce(flat[0], simd_min) let upper = flat.dropFirst().reduce(flat[0], simd_max) return (upper - lower).max() / 32 } /// The mesh vertices when the FOLD vertices are at `positions`, each face placed rigidly. func pose(_ positions: [SIMD3]) -> [SIMD3] { anchors.map { anchor in let o = positions[anchor.corners.x] return o + anchor.a * (positions[anchor.corners.y] - o) + anchor.b * (positions[anchor.corners.z] - o) } } } /// The largest relative change in a mesh edge's length against frame 0. public func strain(_ positions: [SIMD3], mesh: RenderMesh) -> Double { var worst = 0.0 for (a, b, c) in mesh.triangles { for (i, j) in [(a, b), (b, c), (c, a)] { let rest = simd_distance(mesh.vertices[i], mesh.vertices[j]) worst = max(worst, abs(simd_distance(positions[i], positions[j]) - rest) / rest) } } return worst } /// Twice the signed area of a polygon, positive when its corners run counterclockwise. private func signedArea(_ polygon: [SIMD2]) -> Double { polygon.indices.reduce(0) { sum, k in let p = polygon[k], q = polygon[(k + 1) % polygon.count] return sum + p.x * q.y - p.y * q.x } } private func cross(_ u: SIMD2, _ v: SIMD2) -> Double { u.x * v.y - u.y * v.x } /// The distance from `p` to the nearest side of a convex counterclockwise polygon, negative outside. private func distanceInside(_ polygon: [SIMD2], _ p: SIMD2) -> Double { polygon.indices.map { k in let a = polygon[k], b = polygon[(k + 1) % polygon.count] return cross(b - a, p - a) / simd_distance(a, b) }.min() ?? 0 } /// A Delaunay triangulation of a convex polygon whose `boundary` points run counterclockwise /// (straight runs allowed), with `inside` points strictly inside, keeping the boundary's edges. /// Ear clipping on the boundary, each time the largest ear with no other boundary point on or in /// it; then each inside point inserted into the triangle holding it, splitting an edge it lies /// on; then Lawson flips of every edge off the boundary until each is locally Delaunay. /// Triangles are counterclockwise. private func triangulate(boundary: [Int], inside: [Int], _ p: [SIMD2]) -> [(Int, Int, Int)] { func area(_ a: Int, _ b: Int, _ c: Int) -> Double { cross(p[b] - p[a], p[c] - p[a]) / 2 } let scale = boundary.map { simd_length_squared(p[$0] - p[boundary[0]]) }.max() ?? 1 var triangles: [SIMD3] = [] var ring = boundary 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 } 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 } triangles.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 { triangles.append(SIMD3(ring[0], ring[1], ring[2])) } for v in inside { // the newest triangles first: consecutive points of a lattice row lie close together for k in triangles.indices.reversed() { let t = triangles[k] let total = area(t.x, t.y, t.z) let w = [area(v, t.y, t.z), area(t.x, v, t.z), area(t.x, t.y, v)] guard w.allSatisfy({ $0 >= -1e-12 * total }) else { continue } if let zero = w.firstIndex(where: { abs($0) <= 1e-9 * total }) { // on the edge opposite corner `zero`: split both triangles beside it let c = [t.x, t.y, t.z] let a = c[(zero + 1) % 3], b = c[(zero + 2) % 3] triangles[k] = SIMD3(c[zero], a, v) triangles.append(SIMD3(c[zero], v, b)) if let n = triangles.indices.first(where: { n in let u = triangles[n] return n != k && [u.x, u.y, u.z].contains(a) && [u.x, u.y, u.z].contains(b) }) { let u = triangles[n] let other = [u.x, u.y, u.z].first { $0 != a && $0 != b }! triangles[n] = SIMD3(other, b, v) triangles.append(SIMD3(other, v, a)) } } else { triangles[k] = SIMD3(t.x, t.y, v) triangles.append(SIMD3(t.y, t.z, v)) triangles.append(SIMD3(t.z, t.x, v)) } break } } let kept = Set(boundary.indices.map { k in SIMD2(min(boundary[k], boundary[(k + 1) % boundary.count]), max(boundary[k], boundary[(k + 1) % boundary.count])) }) // whether d lies strictly inside the circle through the counterclockwise a, b, c 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 = simd_length_squared(pa) * cross(pb, pc) - simd_length_squared(pb) * cross(pa, pc) + simd_length_squared(pc) * cross(pa, pb) return det > 1e-15 * scale * scale } func key(_ a: Int, _ b: Int) -> SIMD2 { SIMD2(min(a, b), max(a, b)) } func corners(_ k: Int) -> [Int] { [triangles[k].x, triangles[k].y, triangles[k].z] } var sides: [SIMD2: [Int]] = [:] for k in triangles.indices { let c = corners(k) for i in 0..<3 { sides[key(c[i], c[(i + 1) % 3]), default: []].append(k) } } var pending = sides.keys.filter { !kept.contains($0) }.sorted { ($0.x, $0.y) > ($1.x, $1.y) } while let edge = pending.popLast() { guard let pair = sides[edge], pair.count == 2 else { continue } let (k1, k2) = (pair[0], pair[1]) let first = corners(k1) let i = first.firstIndex { $0 != edge.x && $0 != edge.y }! let (c1, a, b) = (first[i], first[(i + 1) % 3], first[(i + 2) % 3]) let c2 = corners(k2).first { $0 != edge.x && $0 != edge.y }! guard inCircle(c1, a, b, c2), area(c1, a, c2) > 0, area(c2, b, c1) > 0 else { continue } triangles[k1] = SIMD3(c1, a, c2) triangles[k2] = SIMD3(c2, b, c1) sides[edge] = nil sides[key(c1, c2)] = [k1, k2] sides[key(a, c2)] = sides[key(a, c2)]!.map { $0 == k2 ? k1 : $0 } sides[key(b, c1)] = sides[key(b, c1)]!.map { $0 == k1 ? k2 : $0 } pending += [key(c1, a), key(a, c2), key(c2, b), key(b, c1)].filter { !kept.contains($0) } } return triangles.map { ($0.x, $0.y, $0.z) } } /// The indices of the three corners spanning the largest triangle, the first such in index order. func widestCorners(_ corners: [SIMD2]) -> [Int] { var best = [0, 1, 2], largest = -1.0 for i in corners.indices { for j in corners.indices where j > i { for k in corners.indices where k > j { let u = corners[j] - corners[i], v = corners[k] - corners[i] let area = abs(u.x * v.y - u.y * v.x) if area > largest { (best, largest) = ([i, j, k], area) } } } } return best } /// Points merged within a tolerance, found through a grid of buckets one tolerance wide. private struct PointSet { let tolerance: Double private(set) var points: [SIMD2] = [] private var buckets: [SIMD2: [Int]] = [:] init(tolerance: Double) { self.tolerance = tolerance } /// The index of the point within the tolerance of `p`, added when there is none. mutating func index(of p: SIMD2) -> Int { let key = SIMD2(Int64((p.x / tolerance).rounded(.down)), Int64((p.y / tolerance).rounded(.down))) for dx in -1...1 { for dy in -1...1 { for i in buckets[key &+ SIMD2(Int64(dx), Int64(dy))] ?? [] where simd_distance(points[i], p) <= tolerance { return i } } } points.append(p) buckets[key, default: []].append(points.count - 1) return points.count - 1 } }