Packages/FoldKit/Tests/FoldingTests/RenderMeshTests.swift

161 lines · 8015 bytes

14 symbols in this file
  1import Foundation
  2import Testing
  3import simd
  4import FoldFormat
  5import Folding
  6import FoldKitTestSupport
  7
  8/// A flat 2 × 1 sheet with `points` as its vertices and `faces` as its faces; edges are not read
  9/// by the mesh and are left empty.
 10private func sheet(_ points: [SIMD2<Double>], _ faces: [[Int]]) -> FoldFile {
 11    FoldFile(fileSpec: 1.2, fileAuthor: "Traditional", edgesVertices: [], facesVertices: faces,
 12             edgesFirstCreasedAtStep: [],
 13             frames: [FoldFrame(verticesCoords: points.map { SIMD3($0.x, $0.y, 0) }, edgesAssignment: [],
 14                                edgesFoldAngle: [], faceOrders: [])])
 15}
 16
 17/// A crease along y = 0.5 split at M = (1, 0.5), and a crease from M to the top edge. M is a
 18/// 180° corner of the bottom face, listed so that a fan from the face's first corner meets it
 19/// collinearly.
 20private func tJunction() -> FoldFile {
 21    sheet([SIMD2(0, 0), SIMD2(2, 0), SIMD2(2, 0.5), SIMD2(2, 1), SIMD2(1, 1), SIMD2(0, 1), SIMD2(0, 0.5),
 22           SIMD2(1, 0.5)],
 23          [[2, 7, 6, 0, 1], [6, 7, 4, 5], [7, 2, 3, 4]])
 24}
 25
 26/// Whether every mesh vertex in or on a face's outline is a corner of one of that face's triangles.
 27private func everyFaceUsesItsVertices(_ file: FoldFile, _ mesh: RenderMesh) -> Bool {
 28    let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) }
 29    return file.facesVertices.indices.allSatisfy { f in
 30        let outline = file.facesVertices[f].map { flat[$0] }
 31        var used = Set<Int>()
 32        for (t, (a, b, c)) in mesh.triangles.enumerated() where mesh.faceOf[t] == f { used.formUnion([a, b, c]) }
 33        return mesh.vertices.indices.allSatisfy { v in
 34            let p = mesh.vertices[v]
 35            let inside = outline.indices.allSatisfy { i in
 36                let a = outline[i], side = outline[(i + 1) % outline.count] - a, offset = p - a
 37                return side.x * offset.y - side.y * offset.x >= -1e-12
 38            }
 39            return !inside || used.contains(v)
 40        }
 41    }
 42}
 43
 44@Test(arguments: [10.0, 0.3, 2.0 / 32])
 45func aStraightCornerIsInItsFacesTriangles(_ spacing: Double) {
 46    let file = tJunction()
 47    #expect(everyFaceUsesItsVertices(file, RenderMesh(file: file, spacing: spacing)))
 48}
 49
 50@Test func aNonRigidStepOverAStraightCornerBuilds() {
 51    // a crease along y = 0.5 split at M, straight in both faces that hold it, and a crease at
 52    // x = 1.5; the right top face is held, the rest move, so M is a free vertex of the pop
 53    let m = SIMD2(1.03, 0.5)
 54    let file = sheet([SIMD2(0, 0), SIMD2(1.5, 0), SIMD2(2, 0), SIMD2(2, 0.5), SIMD2(2, 1), SIMD2(1.5, 1),
 55                      SIMD2(0, 1), SIMD2(0, 0.5), m, SIMD2(1.5, 0.5)],
 56                     [[9, 8, 7, 0, 1], [7, 8, 9, 5, 6], [1, 2, 3, 9], [9, 3, 4, 5]])
 57    let start = file.frames[0].verticesCoords
 58    let step = FoldStep(index: 1, kind: .fold, instruction: "Pop.",
 59                        axes: [FoldAxis(edge: 0, origin: .zero, direction: SIMD3(1, 0, 0), movingFaces: [0, 1, 2],
 60                                        startAngle: 0, endAngle: 0)],
 61                        nonRigid: true,
 62                        pop: Pop(spine: [], openAngle: 30, phases: (1.0 / 3)...(2.0 / 3), openAxes: [],
 63                                 popped: start, closeAxes: []),
 64                        viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0)))
 65    let i = FoldInterpolator(file: file, step: step)
 66    #expect(everyFaceUsesItsVertices(file, i.mesh))
 67    #expect(zip(i.positions(at: 0.5), start).allSatisfy { simd_distance($0, $1) < 1e-9 })
 68}
 69
 70/// A unit square cut by one crease between irrational heights on its left and right sides; no two
 71/// creases or sides meet at less than 80°.
 72private func offGrid() -> FoldFile {
 73    let a = 1 / 7.0.squareRoot(), b = 1 - 1 / 5.0.squareRoot()
 74    return sheet([SIMD2(0, 0), SIMD2(1, 0), SIMD2(1, b), SIMD2(1, 1), SIMD2(0, 1), SIMD2(0, a)],
 75                 [[0, 1, 2, 5], [5, 2, 3, 4]])
 76}
 77
 78/// The mesh's edges, each once, as pairs of mesh vertices.
 79private func edges(_ mesh: RenderMesh) -> [SIMD2<Int>] {
 80    var set = Set<SIMD2<Int>>()
 81    for (a, b, c) in mesh.triangles {
 82        for (i, j) in [(a, b), (b, c), (c, a)] { set.insert(SIMD2(min(i, j), max(i, j))) }
 83    }
 84    return set.sorted { ($0.x, $0.y) < ($1.x, $1.y) }
 85}
 86
 87private func meshTestFiles() throws -> [FoldFile] {
 88    [try FoldFile(contentsOf: fixture("reverse-cp.fold")), try FoldFile(contentsOf: fixture("preliminary-cp.fold")),
 89     offGrid()]
 90}
 91
 92/// The shipped models' crease patterns, whose faces are their frame 0's.
 93private func shippedPatterns() throws -> [FoldFile] {
 94    try ["cup", "box", "sampan", "crane"].map { try FoldFile(contentsOf: pattern($0)) }
 95}
 96
 97@Test func noMeshEdgeIsMuchShorterThanTheSpacing() throws {
 98    // decision 0003: 0.15 of the spacing, except where a crease is shorter or creases meet sharply;
 99    // none of these sheets needs the exception, the shipped models' included
100    for file in try meshTestFiles() + shippedPatterns() {
101        let spacing = RenderMesh.spacing(for: file)
102        let mesh = RenderMesh(file: file, spacing: spacing)
103        let shortest = edges(mesh).map { simd_distance(mesh.vertices[$0.x], mesh.vertices[$0.y]) }.min()!
104        #expect(shortest >= 0.15 * spacing, "\(file.fileTitle ?? "off grid"): \(shortest / spacing) of the spacing")
105    }
106}
107
108@Test func eachSideOfAFaceIsDividedEvenly() throws {
109    // round(length / spacing) equal parts, the same points in both faces that share the side
110    for file in try meshTestFiles() {
111        let spacing = RenderMesh.spacing(for: file)
112        let mesh = RenderMesh(file: file, spacing: spacing)
113        let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) }
114        for face in file.facesVertices {
115            for k in face.indices {
116                let a = flat[face[k]], b = flat[face[(k + 1) % face.count]]
117                let parts = max(1, Int((simd_distance(a, b) / spacing).rounded()))
118                let on = mesh.vertices.filter { p in
119                    abs((b - a).x * (p - a).y - (b - a).y * (p - a).x) <= 1e-9 * simd_distance(a, b)
120                        && simd_dot(p - a, b - a) >= -1e-12 && simd_dot(p - b, a - b) >= -1e-12
121                }
122                #expect(on.count == parts + 1)
123                for p in on {
124                    let u = simd_dot(p - a, b - a) / simd_length_squared(b - a) * Double(parts)
125                    #expect(abs(u - u.rounded()) < 1e-9)
126                }
127            }
128        }
129    }
130}
131
132@Test func theMeshIsDelaunayWithinEachFace() throws {
133    // no edge between two triangles of one face has the opposite corner of one inside the other's circumcircle
134    for file in try meshTestFiles() {
135        let mesh = RenderMesh(file: file, spacing: RenderMesh.spacing(for: file))
136        var opposite: [SIMD2<Int>: [Int]] = [:]
137        for (a, b, c) in mesh.triangles {
138            for (i, j, k) in [(a, b, c), (b, c, a), (c, a, b)] { opposite[SIMD2(min(i, j), max(i, j)), default: []].append(k) }
139        }
140        var violations = 0
141        for (edge, corners) in opposite where corners.count == 2 {
142            let (p, q) = (mesh.vertices[edge.x], mesh.vertices[edge.y])
143            let (r, s) = (mesh.vertices[corners[0]], mesh.vertices[corners[1]])
144            // the angles opposite the edge sum to at most 180° when the edge is locally Delaunay
145            func angle(_ o: SIMD2<Double>) -> Double {
146                acos(max(-1, min(1, simd_dot(simd_normalize(p - o), simd_normalize(q - o)))))
147            }
148            if angle(r) + angle(s) > .pi + 1e-9 { violations += 1 }
149        }
150        #expect(violations == 0, "\(file.fileTitle ?? "off grid")")
151    }
152}
153
154@Test func eachFoldVertexIsAMeshVertex() throws {
155    for file in try meshTestFiles() {
156        let mesh = RenderMesh(file: file, spacing: RenderMesh.spacing(for: file))
157        #expect(mesh.meshVertexOf.enumerated().allSatisfy { v, m in
158            mesh.vertices[m] == SIMD2(file.frames[0].verticesCoords[v].x, file.frames[0].verticesCoords[v].y)
159        })
160    }
161}