Commit e30e7fe36c
Verified · cmc
Layout: unified · split
Packages/FoldKit/Package.swift +1 −1
| @@ -13,7 +13,7 @@ let package = Package( | |||
| 13 | .target(name: "Folding", dependencies: ["FoldFormat"]), | 13 | .target(name: "Folding", dependencies: ["FoldFormat"]), |
| 14 | .target( | 14 | .target( |
| 15 | name: "FoldKitTestSupport", | 15 | name: "FoldKitTestSupport", |
| 16 | dependencies: ["FoldFormat"], | 16 | dependencies: ["FoldFormat", "Folding"], |
| 17 | resources: [.copy("Fixtures")] | 17 | resources: [.copy("Fixtures")] |
| 18 | ), | 18 | ), |
| 19 | .testTarget(name: "FoldFormatTests", dependencies: ["FoldFormat", "FoldKitTestSupport"]), | 19 | .testTarget(name: "FoldFormatTests", dependencies: ["FoldFormat", "FoldKitTestSupport"]), |
Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift +106
| @@ -1,5 +1,7 @@ | |||
| 1 | import Foundation | 1 | import Foundation |
| 2 | import FoldFormat | 2 | import FoldFormat |
| 3 | import Folding | ||
| 4 | import simd | ||
| 3 | 5 | ||
| 4 | /// Decision 0001's case 3: a flat-foldable degree-4 vertex at the centre of a 2×2 sheet, creases | 6 | /// Decision 0001's case 3: a flat-foldable degree-4 vertex at the centre of a 2×2 sheet, creases |
| 5 | /// at 0°, 60°, 140° and 260° (sectors 60°, 80°, 120°, 100°), folded from flat to flat in one step. | 7 | /// at 0°, 60°, 140° and 260° (sectors 60°, 80°, 120°, 100°), folded from flat to flat in one step. |
| @@ -99,3 +101,107 @@ public func degreeFourExactAngle(_ edge: Int, at t: Double) -> Double { | |||
| 99 | } | 101 | } |
| 100 | 102 | ||
| 101 | private func radians(_ degrees: Double) -> Double { degrees * .pi / 180 } | 103 | private func radians(_ degrees: Double) -> Double { degrees * .pi / 180 } |
| 104 | |||
| 105 | /// A fixture file, and the interpolator for its step `step` (counted from 1). | ||
| 106 | public func interpolator(_ fixtureName: String, step: Int) throws -> (FoldFile, FoldInterpolator) { | ||
| 107 | let file = try FoldFile(contentsOf: fixture(fixtureName)) | ||
| 108 | return (file, FoldInterpolator(file: file, step: try readSteps(file)[step - 1])) | ||
| 109 | } | ||
| 110 | |||
| 111 | /// The largest change, against frame 0, in the length of any FOLD edge. | ||
| 112 | public func maxEdgeLengthDrift(_ positions: [SIMD3<Double>], _ file: FoldFile) -> Double { | ||
| 113 | let flat = file.frames[0].verticesCoords | ||
| 114 | return file.edgesVertices.map { e in | ||
| 115 | abs(simd_distance(positions[e[0]], positions[e[1]]) - simd_distance(flat[e[0]], flat[e[1]])) | ||
| 116 | }.max() ?? 0 | ||
| 117 | } | ||
| 118 | |||
| 119 | /// Whether every pairwise distance between the points agrees, within 1e-9, across both arrays. | ||
| 120 | public func pairwiseDistancesAgree(_ a: [SIMD3<Double>], _ b: [SIMD3<Double>]) -> Bool { | ||
| 121 | guard a.count == b.count else { return false } | ||
| 122 | for i in a.indices { | ||
| 123 | for j in a.indices where j > i { | ||
| 124 | if abs(simd_distance(a[i], a[j]) - simd_distance(b[i], b[j])) > 1e-9 { return false } | ||
| 125 | } | ||
| 126 | } | ||
| 127 | return true | ||
| 128 | } | ||
| 129 | |||
| 130 | /// The longer side of frame 0's bounding box. | ||
| 131 | public func sheetSize(_ file: FoldFile) -> Double { | ||
| 132 | let points = file.frames[0].verticesCoords | ||
| 133 | let lower = points.dropFirst().reduce(points[0], simd_min) | ||
| 134 | let upper = points.dropFirst().reduce(points[0], simd_max) | ||
| 135 | let extent = upper - lower | ||
| 136 | return max(extent.x, extent.y, extent.z) | ||
| 137 | } | ||
| 138 | |||
| 139 | /// A `cells` × `cells` grid of unit cells, with one step folding the right half over the left | ||
| 140 | /// about the vertical line through the middle. Cells are faces, numbered row by row from the | ||
| 141 | /// bottom left; `cells` must be even. | ||
| 142 | public func gridSheet(cells: Int) -> FoldFile { | ||
| 143 | precondition(cells >= 2 && cells.isMultiple(of: 2), "gridSheet needs an even number of cells") | ||
| 144 | let n = cells, half = n / 2 | ||
| 145 | func vertex(_ i: Int, _ j: Int) -> Int { j * (n + 1) + i } | ||
| 146 | |||
| 147 | var flat: [SIMD3<Double>] = [] | ||
| 148 | for j in 0...n { for i in 0...n { flat.append(SIMD3(Double(i), Double(j), 0)) } } | ||
| 149 | let folded = flat.map { p in SIMD3(p.x > Double(half) ? Double(n) - p.x : p.x, p.y, 0) } | ||
| 150 | |||
| 151 | var edges: [[Int]] = [], assignment: [EdgeAssignment] = [], angle: [Double] = [] | ||
| 152 | var created: [Int?] = [] | ||
| 153 | func addEdge(_ a: Int, _ b: Int, boundary: Bool, crease: Bool) { | ||
| 154 | edges.append([a, b]) | ||
| 155 | assignment.append(boundary ? .boundary : crease ? .valley : .flat) | ||
| 156 | angle.append(crease ? 180 : 0) | ||
| 157 | created.append(crease ? 1 : nil) | ||
| 158 | } | ||
| 159 | var axisEdge = 0 | ||
| 160 | for j in 0...n { | ||
| 161 | for i in 0..<n { | ||
| 162 | addEdge(vertex(i, j), vertex(i + 1, j), boundary: j == 0 || j == n, crease: false) | ||
| 163 | } | ||
| 164 | } | ||
| 165 | for j in 0..<n { | ||
| 166 | for i in 0...n { | ||
| 167 | let crease = i == half | ||
| 168 | if crease && j == 0 { axisEdge = edges.count } | ||
| 169 | addEdge(vertex(i, j), vertex(i, j + 1), boundary: i == 0 || i == n, crease: crease) | ||
| 170 | } | ||
| 171 | } | ||
| 172 | |||
| 173 | var faces: [[Int]] = [] | ||
| 174 | for j in 0..<n { | ||
| 175 | for i in 0..<n { | ||
| 176 | faces.append([vertex(i, j), vertex(i + 1, j), vertex(i + 1, j + 1), vertex(i, j + 1)]) | ||
| 177 | } | ||
| 178 | } | ||
| 179 | let right = faces.indices.filter { $0 % n >= half } | ||
| 180 | // each right cell lies flipped on top of its mirror image in the left half | ||
| 181 | let orders = right.map { f in [f, f - 2 * (f % n - half) - 1, 1] } | ||
| 182 | |||
| 183 | let step = StepRecord( | ||
| 184 | kind: .fold, | ||
| 185 | technique: .plain, | ||
| 186 | instruction: "Valley fold the right half over to the left.", | ||
| 187 | axes: [AxisRecord(edge: axisEdge, movingFaces: right, startAngle: 0, endAngle: 180)], | ||
| 188 | viewpoint: Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0)) | ||
| 189 | ) | ||
| 190 | return FoldFile( | ||
| 191 | fileSpec: 1.2, | ||
| 192 | fileTitle: "Grid", | ||
| 193 | fileAuthor: "Traditional", | ||
| 194 | fileClasses: ["diagrams"], | ||
| 195 | edgesVertices: edges, | ||
| 196 | facesVertices: faces, | ||
| 197 | edgesFirstCreasedAtStep: created, | ||
| 198 | frames: [ | ||
| 199 | FoldFrame(verticesCoords: flat, | ||
| 200 | edgesAssignment: assignment.map { $0 == .valley ? .flat : $0 }, | ||
| 201 | edgesFoldAngle: Array(repeating: 0, count: edges.count), | ||
| 202 | faceOrders: []), | ||
| 203 | FoldFrame(verticesCoords: folded, edgesAssignment: assignment, edgesFoldAngle: angle, | ||
| 204 | faceOrders: orders, step: step), | ||
| 205 | ] | ||
| 206 | ) | ||
| 207 | } | ||
Packages/FoldKit/Sources/Folding/FoldInterpolator.swift added +127
| @@ -0,0 +1,127 @@ | |||
| 1 | import FoldFormat | ||
| 2 | import simd | ||
| 3 | |||
| 4 | /// Interpolates a rigid step from frame `step.index − 1` to frame `step.index`. | ||
| 5 | /// | ||
| 6 | /// A fold or fold-and-unfold step moves the faces of each axis's moving set about that axis; an | ||
| 7 | /// axis with a parent is carried by the parent's motion. A `turnOver` or `rotate` step rotates | ||
| 8 | /// the whole of the start frame about its bounding-box centre. Steps flagged `nonRigid` are not | ||
| 9 | /// handled here. | ||
| 10 | public struct FoldInterpolator: Sendable { | ||
| 11 | private struct Motion: Sendable { | ||
| 12 | let step: FoldStep | ||
| 13 | /// Per axis, the vertices that take their position from that axis's face group. | ||
| 14 | let vertices: [[Int]] | ||
| 15 | } | ||
| 16 | |||
| 17 | private struct Reorientation: Sendable { | ||
| 18 | let centre: SIMD3<Double> | ||
| 19 | let axis: SIMD3<Double> | ||
| 20 | /// Radians at t = 1. | ||
| 21 | let angle: Double | ||
| 22 | } | ||
| 23 | |||
| 24 | private enum Mode: Sendable { | ||
| 25 | case folds(Motion) | ||
| 26 | case reorient(Reorientation) | ||
| 27 | } | ||
| 28 | |||
| 29 | private let start: [SIMD3<Double>] | ||
| 30 | private let kind: StepKind | ||
| 31 | private let mode: Mode | ||
| 32 | |||
| 33 | public init(file: FoldFile, step: FoldStep) { | ||
| 34 | precondition(!step.nonRigid, "FoldInterpolator handles rigid steps only; the non-rigid path is added by Task 7b") | ||
| 35 | start = file.frames[step.index - 1].verticesCoords | ||
| 36 | kind = step.kind | ||
| 37 | |||
| 38 | switch step.kind { | ||
| 39 | case .fold, .foldAndUnfold: | ||
| 40 | var axisOfFace: [Int: Int] = [:] | ||
| 41 | for (a, axis) in step.axes.enumerated() { | ||
| 42 | for f in axis.movingFaces { axisOfFace[f] = a } | ||
| 43 | } | ||
| 44 | // a vertex takes its position from the first face containing it | ||
| 45 | var owner = Array<Int?>(repeating: nil, count: start.count) | ||
| 46 | var seen = Array(repeating: false, count: start.count) | ||
| 47 | for (f, face) in file.facesVertices.enumerated() { | ||
| 48 | for v in face where !seen[v] { | ||
| 49 | seen[v] = true | ||
| 50 | owner[v] = axisOfFace[f] | ||
| 51 | } | ||
| 52 | } | ||
| 53 | var groups = Array(repeating: [Int](), count: step.axes.count) | ||
| 54 | for (v, a) in owner.enumerated() { | ||
| 55 | if let a { groups[a].append(v) } | ||
| 56 | } | ||
| 57 | mode = .folds(Motion(step: step, vertices: groups)) | ||
| 58 | |||
| 59 | case .turnOver, .rotate: | ||
| 60 | var lower = start[0], upper = start[0] | ||
| 61 | for p in start { | ||
| 62 | lower = simd_min(lower, p) | ||
| 63 | upper = simd_max(upper, p) | ||
| 64 | } | ||
| 65 | let eye = normalize(step.viewpoint.eye), up = normalize(step.viewpoint.up) | ||
| 66 | let axis: SIMD3<Double>, degrees: Double | ||
| 67 | if step.kind == .rotate { | ||
| 68 | axis = eye | ||
| 69 | degrees = step.rotateDegrees ?? 0 | ||
| 70 | } else { | ||
| 71 | axis = step.turnOverAxis == .horizontal ? normalize(cross(up, eye)) : up | ||
| 72 | degrees = 180 | ||
| 73 | } | ||
| 74 | mode = .reorient(Reorientation(centre: (lower + upper) / 2, axis: axis, | ||
| 75 | angle: degrees * .pi / 180)) | ||
| 76 | } | ||
| 77 | } | ||
| 78 | |||
| 79 | /// The vertex positions at `t` of the step, `t` in 0...1. | ||
| 80 | public func positions(at t: Double) -> [SIMD3<Double>] { | ||
| 81 | switch mode { | ||
| 82 | case .reorient(let r): | ||
| 83 | let q = simd_quatd(angle: r.angle * t, axis: r.axis) | ||
| 84 | return start.map { r.centre + q.act($0 - r.centre) } | ||
| 85 | |||
| 86 | case .folds(let motion): | ||
| 87 | // each axis's full transform: its own rotation, then its parent's | ||
| 88 | var full: [Transform] = [] | ||
| 89 | full.reserveCapacity(motion.step.axes.count) | ||
| 90 | for axis in motion.step.axes { | ||
| 91 | let degrees = axis.angle(at: t, kind: kind) - axis.startAngle | ||
| 92 | let q = simd_quatd(angle: degrees * .pi / 180, axis: axis.direction) | ||
| 93 | let own = Transform(rotation: simd_double3x3(q), about: axis.origin) | ||
| 94 | full.append(axis.parent.map { full[$0].after(own) } ?? own) | ||
| 95 | } | ||
| 96 | var result = start | ||
| 97 | for (a, group) in motion.vertices.enumerated() { | ||
| 98 | for v in group { result[v] = full[a].apply(start[v]) } | ||
| 99 | } | ||
| 100 | return result | ||
| 101 | } | ||
| 102 | } | ||
| 103 | } | ||
| 104 | |||
| 105 | /// p ↦ linear · p + offset | ||
| 106 | private struct Transform { | ||
| 107 | var linear: simd_double3x3 | ||
| 108 | var offset: SIMD3<Double> | ||
| 109 | |||
| 110 | /// The rotation `linear` about the point `centre`. | ||
| 111 | init(rotation linear: simd_double3x3, about centre: SIMD3<Double>) { | ||
| 112 | self.linear = linear | ||
| 113 | offset = centre - linear * centre | ||
| 114 | } | ||
| 115 | |||
| 116 | private init(linear: simd_double3x3, offset: SIMD3<Double>) { | ||
| 117 | self.linear = linear | ||
| 118 | self.offset = offset | ||
| 119 | } | ||
| 120 | |||
| 121 | func apply(_ p: SIMD3<Double>) -> SIMD3<Double> { linear * p + offset } | ||
| 122 | |||
| 123 | /// This transform applied after `inner`. | ||
| 124 | func after(_ inner: Transform) -> Transform { | ||
| 125 | Transform(linear: linear * inner.linear, offset: linear * inner.offset + offset) | ||
| 126 | } | ||
| 127 | } | ||
Packages/FoldKit/Tests/FoldingTests/InterpolationTests.swift added +109
| @@ -0,0 +1,109 @@ | |||
| 1 | import Foundation | ||
| 2 | import Testing | ||
| 3 | import simd | ||
| 4 | import FoldFormat | ||
| 5 | import Folding | ||
| 6 | import FoldKitTestSupport | ||
| 7 | |||
| 8 | let modelFixtures = ["half.fold", "mountain.fold", "letter.fold", "letter-sequential.fold", | ||
| 9 | "letter-staggered.fold", "quarters.fold", "occlusion.fold"] | ||
| 10 | |||
| 11 | @Test func tZeroReproducesTheStartFrame() throws { | ||
| 12 | let (file, i) = try interpolator("half.fold", step: 1) | ||
| 13 | #expect(zip(i.positions(at: 0), file.frames[0].verticesCoords) | ||
| 14 | .allSatisfy { simd_distance($0, $1) < 1e-12 }) | ||
| 15 | } | ||
| 16 | |||
| 17 | @Test(arguments: modelFixtures) | ||
| 18 | func tOneReproducesTheEndFrameForEveryStep(_ name: String) throws { | ||
| 19 | let file = try FoldFile(contentsOf: fixture(name)) | ||
| 20 | for step in try readSteps(file) { | ||
| 21 | let i = FoldInterpolator(file: file, step: step) | ||
| 22 | #expect(zip(i.positions(at: 1), file.frames[step.index].verticesCoords) | ||
| 23 | .allSatisfy { simd_distance($0, $1) < 1e-9 }, "\(name) step \(step.index)") | ||
| 24 | } | ||
| 25 | } | ||
| 26 | |||
| 27 | @Test(arguments: modelFixtures) | ||
| 28 | func everyEdgeLengthIsPreservedThroughoutEveryStep(_ name: String) throws { | ||
| 29 | let file = try FoldFile(contentsOf: fixture(name)) | ||
| 30 | for step in try readSteps(file) { | ||
| 31 | let i = FoldInterpolator(file: file, step: step) | ||
| 32 | for t in stride(from: 0.0, through: 1.0, by: 0.05) { | ||
| 33 | #expect(maxEdgeLengthDrift(i.positions(at: t), file) < 1e-9, | ||
| 34 | "\(name) step \(step.index) t \(t)") | ||
| 35 | } | ||
| 36 | } | ||
| 37 | } | ||
| 38 | |||
| 39 | @Test func verticesOnTheAxisDoNotMove() throws { | ||
| 40 | let (file, i) = try interpolator("half.fold", step: 1) | ||
| 41 | for v in [1, 4] { | ||
| 42 | #expect(simd_distance(i.positions(at: 0.37)[v], file.frames[0].verticesCoords[v]) < 1e-12) | ||
| 43 | } | ||
| 44 | } | ||
| 45 | |||
| 46 | @Test func aValleyFoldRisesTowardTheViewerAndAMountainFoldFallsAway() throws { | ||
| 47 | let (_, valley) = try interpolator("half.fold", step: 1) | ||
| 48 | let (_, mountain) = try interpolator("mountain.fold", step: 1) | ||
| 49 | #expect(valley.positions(at: 0.5)[2].z > 0) | ||
| 50 | #expect(mountain.positions(at: 0.5)[2].z < 0) | ||
| 51 | } | ||
| 52 | |||
| 53 | @Test func multiAxisStepMovesEverySetOnTheSharedParameter() throws { | ||
| 54 | let (file, i) = try interpolator("letter.fold", step: 1) | ||
| 55 | let start = file.frames[0].verticesCoords, mid = i.positions(at: 0.5) | ||
| 56 | #expect(simd_distance(mid[0], start[0]) > 0.1) // left flap | ||
| 57 | #expect(simd_distance(mid[3], start[3]) > 0.1) // right flap | ||
| 58 | } | ||
| 59 | |||
| 60 | @Test func foldAndUnfoldPassesThroughThePeakAndReturns() throws { | ||
| 61 | let (file, i) = try interpolator("quarters.fold", step: 1) | ||
| 62 | #expect(simd_distance(i.positions(at: 0.5)[2], SIMD3(0, 0, 0)) < 1e-9) | ||
| 63 | #expect(zip(i.positions(at: 1), file.frames[0].verticesCoords) | ||
| 64 | .allSatisfy { simd_distance($0, $1) < 1e-9 }) | ||
| 65 | } | ||
| 66 | |||
| 67 | @Test func aCoupledVertexStaysWholeThroughout() throws { | ||
| 68 | // decision 0001, case 3: curves from the closed form, sampled at 257 points | ||
| 69 | let file = degreeFourVertex() | ||
| 70 | let i = FoldInterpolator(file: file, step: try readSteps(file)[0]) | ||
| 71 | for n in 0...1024 { | ||
| 72 | #expect(maxEdgeLengthDrift(i.positions(at: Double(n) / 1024), file) < 1e-6) | ||
| 73 | } | ||
| 74 | #expect(zip(i.positions(at: 1), file.frames[1].verticesCoords) | ||
| 75 | .allSatisfy { simd_distance($0, $1) < 1e-9 }) | ||
| 76 | } | ||
| 77 | |||
| 78 | @Test func theSameVertexWithLinearAnglesTears() throws { | ||
| 79 | // the control: drop the curve and the paper does not hold together | ||
| 80 | let file = degreeFourVertex(linear: true) | ||
| 81 | let i = FoldInterpolator(file: file, step: try readSteps(file)[0]) | ||
| 82 | #expect(maxEdgeLengthDrift(i.positions(at: 0.5), file) > 0.1) | ||
| 83 | } | ||
| 84 | |||
| 85 | @Test func aStaggeredAxisMovesOnlyInItsWindow() throws { | ||
| 86 | let (file, i) = try interpolator("letter-staggered.fold", step: 1) | ||
| 87 | let start = file.frames[0].verticesCoords | ||
| 88 | #expect(simd_distance(i.positions(at: 0.25)[3], start[3]) < 1e-12) // right flap waits | ||
| 89 | #expect(simd_distance(i.positions(at: 0.5)[0], SIMD3(2, 0, 0)) < 1e-9) // left flap down | ||
| 90 | } | ||
| 91 | |||
| 92 | @Test func turnOverRotatesTheModelRigidly() throws { | ||
| 93 | let (_, i) = try interpolator("half.fold", step: 2) | ||
| 94 | #expect(pairwiseDistancesAgree(i.positions(at: 0.5), i.positions(at: 0))) | ||
| 95 | #expect(i.positions(at: 0.5).contains { $0.z != 0 }) | ||
| 96 | } | ||
| 97 | |||
| 98 | @Test func interpolationFitsInAFrameBudget() throws { | ||
| 99 | let file = gridSheet(cells: 12) // built in code: a 12×12 grid, one fold down the middle | ||
| 100 | let i = FoldInterpolator(file: file, step: try readSteps(file)[0]) | ||
| 101 | let elapsed = ContinuousClock().measure { | ||
| 102 | for n in 0..<1000 { _ = i.positions(at: Double(n) / 1000) } | ||
| 103 | } | ||
| 104 | #expect(elapsed / 1000 < .milliseconds(1)) | ||
| 105 | } | ||
| 106 | |||
| 107 | @Test func theGridSheetIsAValidFile() { | ||
| 108 | #expect(validate(gridSheet(cells: 12)).isEmpty) | ||
| 109 | } | ||