Commit 83d69fc779

83d69fc7797305f4943159d8694780e66c444a5f

parent: b1e606f57c

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-20 02:15 UTC

foldc: compile a fold script and crease pattern into a FOLD sequence

Ref #4

Layout: unified · split

Packages/FoldKit/Package.swift +7 −1
@@ -7,17 +7,23 @@ let package = Package(
7 products: [ 7 products: [
8 .library(name: "FoldFormat", targets: ["FoldFormat"]), 8 .library(name: "FoldFormat", targets: ["FoldFormat"]),
9 .library(name: "Folding", targets: ["Folding"]), 9 .library(name: "Folding", targets: ["Folding"]),
10 .library(name: "FoldCompiler", targets: ["FoldCompiler"]),
11 .executable(name: "foldc", targets: ["foldc"]),
10 ], 12 ],
11 targets: [ 13 targets: [
12 .target(name: "FoldFormat"), 14 .target(name: "FoldFormat"),
13 .target(name: "Folding", dependencies: ["FoldFormat"]), 15 .target(name: "Folding", dependencies: ["FoldFormat"]),
16 .target(name: "FoldCompiler", dependencies: ["FoldFormat", "Folding"]),
17 .executableTarget(name: "foldc", dependencies: ["FoldCompiler"]),
14 .target( 18 .target(
15 name: "FoldKitTestSupport", 19 name: "FoldKitTestSupport",
16 dependencies: ["FoldFormat", "Folding"], 20 dependencies: ["FoldFormat", "Folding", "FoldCompiler"],
17 resources: [.copy("Fixtures")] 21 resources: [.copy("Fixtures")]
18 ), 22 ),
19 .testTarget(name: "FoldFormatTests", dependencies: ["FoldFormat", "FoldKitTestSupport"]), 23 .testTarget(name: "FoldFormatTests", dependencies: ["FoldFormat", "FoldKitTestSupport"]),
20 .testTarget(name: "FoldingTests", dependencies: ["Folding", "FoldFormat", "FoldKitTestSupport"]), 24 .testTarget(name: "FoldingTests", dependencies: ["Folding", "FoldFormat", "FoldKitTestSupport"]),
25 .testTarget(name: "FoldCompilerTests",
26 dependencies: ["FoldCompiler", "Folding", "FoldFormat", "FoldKitTestSupport"]),
21 ], 27 ],
22 swiftLanguageModes: [.v6] 28 swiftLanguageModes: [.v6]
23) 29)
Packages/FoldKit/Sources/FoldCompiler/FoldScript.swift added +136
@@ -0,0 +1,136 @@
1import FoldFormat
2import Foundation
3
4/// A fold script: a crease pattern and the steps that fold it. `creasePattern` is a path
5/// relative to the script.
6public struct FoldScript: Codable, Sendable {
7 public let creasePattern: String
8 public let title: String
9 public let steps: [ScriptStep]
10
11 public init(creasePattern: String, title: String, steps: [ScriptStep]) {
12 self.creasePattern = creasePattern
13 self.title = title
14 self.steps = steps
15 }
16
17 public init(contentsOf url: URL) throws {
18 self = try JSONDecoder().decode(FoldScript.self, from: Data(contentsOf: url))
19 }
20}
21
22/// One authored step. Points are in crease-pattern coordinates.
23///
24/// - `creases`: the creases the step folds; each must separate a moving region from the rest.
25/// - `movingSide`: a point inside each region that moves; the region no point lies in is fixed.
26/// - `angles`, `peakAngles`, `windows`: one per crease. An angle defaults to ±180 by the crease
27/// pattern's assignment, a window to `[0, 1]`.
28/// - `viewpoint`: defaults to the previous step's, or eye `[0, 0, 1]`, up `[0, 1, 0]` for step 1.
29/// - `driver`: the crease held linear when the step's creases close a loop; defaults to the first.
30/// - `faceOrders`, `faceOrdersMidFold`: corrections to the guessed layer order.
31/// - `spine`, `openAngle`: a reverse fold or sink, compiled by the non-rigid path.
32public struct ScriptStep: Codable, Sendable {
33 public let kind: StepKind
34 public let technique: StepTechnique?
35 public let instruction: String
36 public let creases: [CreaseRef]
37 public let movingSide: [SIMD2<Double>]
38 public let angles: [Double]?
39 public let peakAngles: [Double]?
40 public let rotateDegrees: Double?
41 public let turnOverAxis: TurnOverAxis?
42 public let repeatOf: Int?
43 public let viewpoint: Viewpoint?
44 public let faceOrders: [OrderOverride]?
45 public let faceOrdersMidFold: [OrderOverride]?
46 public let driver: CreaseRef?
47 public let windows: [[Double]]?
48 public let spine: CreaseRef?
49 public let openAngle: Double?
50
51 public init(kind: StepKind, technique: StepTechnique? = nil, instruction: String, creases: [CreaseRef] = [],
52 movingSide: [SIMD2<Double>] = [], angles: [Double]? = nil, peakAngles: [Double]? = nil,
53 rotateDegrees: Double? = nil, turnOverAxis: TurnOverAxis? = nil, repeatOf: Int? = nil,
54 viewpoint: Viewpoint? = nil, faceOrders: [OrderOverride]? = nil,
55 faceOrdersMidFold: [OrderOverride]? = nil, driver: CreaseRef? = nil, windows: [[Double]]? = nil,
56 spine: CreaseRef? = nil, openAngle: Double? = nil) {
57 self.kind = kind
58 self.technique = technique
59 self.instruction = instruction
60 self.creases = creases
61 self.movingSide = movingSide
62 self.angles = angles
63 self.peakAngles = peakAngles
64 self.rotateDegrees = rotateDegrees
65 self.turnOverAxis = turnOverAxis
66 self.repeatOf = repeatOf
67 self.viewpoint = viewpoint
68 self.faceOrders = faceOrders
69 self.faceOrdersMidFold = faceOrdersMidFold
70 self.driver = driver
71 self.windows = windows
72 self.spine = spine
73 self.openAngle = openAngle
74 }
75
76 public init(from decoder: any Decoder) throws {
77 let c = try decoder.container(keyedBy: CodingKeys.self)
78 kind = try c.decode(StepKind.self, forKey: .kind)
79 technique = try c.decodeIfPresent(StepTechnique.self, forKey: .technique)
80 instruction = try c.decode(String.self, forKey: .instruction)
81 creases = try c.decodeIfPresent([CreaseRef].self, forKey: .creases) ?? []
82 movingSide = try c.decodeIfPresent([SIMD2<Double>].self, forKey: .movingSide) ?? []
83 angles = try c.decodeIfPresent([Double].self, forKey: .angles)
84 peakAngles = try c.decodeIfPresent([Double].self, forKey: .peakAngles)
85 rotateDegrees = try c.decodeIfPresent(Double.self, forKey: .rotateDegrees)
86 turnOverAxis = try c.decodeIfPresent(TurnOverAxis.self, forKey: .turnOverAxis)
87 repeatOf = try c.decodeIfPresent(Int.self, forKey: .repeatOf)
88 viewpoint = try c.decodeIfPresent(Viewpoint.self, forKey: .viewpoint)
89 faceOrders = try c.decodeIfPresent([OrderOverride].self, forKey: .faceOrders)
90 faceOrdersMidFold = try c.decodeIfPresent([OrderOverride].self, forKey: .faceOrdersMidFold)
91 driver = try c.decodeIfPresent(CreaseRef.self, forKey: .driver)
92 windows = try c.decodeIfPresent([[Double]].self, forKey: .windows)
93 spine = try c.decodeIfPresent(CreaseRef.self, forKey: .spine)
94 openAngle = try c.decodeIfPresent(Double.self, forKey: .openAngle)
95 }
96}
97
98/// A crease, as the two points it runs between or as an edge index. In a script, `[[x0, y0],
99/// [x1, y1]]` or an integer.
100public enum CreaseRef: Codable, Sendable, Equatable {
101 case betweenVertices(SIMD2<Double>, SIMD2<Double>)
102 case edgeIndex(Int)
103
104 public init(from decoder: any Decoder) throws {
105 let c = try decoder.singleValueContainer()
106 if let edge = try? c.decode(Int.self) {
107 self = .edgeIndex(edge)
108 return
109 }
110 let ends = try c.decode([SIMD2<Double>].self)
111 guard ends.count == 2 else {
112 throw DecodingError.dataCorruptedError(in: c, debugDescription: "a crease runs between two points")
113 }
114 self = .betweenVertices(ends[0], ends[1])
115 }
116
117 public func encode(to encoder: any Encoder) throws {
118 var c = encoder.singleValueContainer()
119 switch self {
120 case .betweenVertices(let a, let b): try c.encode([a, b])
121 case .edgeIndex(let edge): try c.encode(edge)
122 }
123 }
124}
125
126/// Puts the face containing `above` over the face containing `below`, as seen from the step's
127/// viewpoint. Points are in crease-pattern coordinates.
128public struct OrderOverride: Codable, Sendable, Equatable {
129 public let above: SIMD2<Double>
130 public let below: SIMD2<Double>
131
132 public init(above: SIMD2<Double>, below: SIMD2<Double>) {
133 self.above = above
134 self.below = below
135 }
136}
Packages/FoldKit/Sources/FoldCompiler/FrameCompiler.swift added +613
@@ -0,0 +1,613 @@
1import FoldFormat
2import Folding
3import simd
4
5public enum CompileError: Error, Equatable, Sendable {
6 /// A crease names no edge, a boundary edge or an edge already named in the step, or the driver
7 /// is not one of the step's creases.
8 case unresolvedCrease(step: Int)
9 /// A `movingSide` point lies on no face, every region has one, or a crease does not separate
10 /// a moving region from the rest.
11 case unresolvedMovingSide(step: Int)
12 /// An order override's point lies on no face.
13 case unresolvedFace(step: Int, point: SIMD2<Double>)
14 case stepFailed(step: Int, defects: [FoldDefect])
15 case interpenetration(step: Int, [Intersection])
16 /// A crease folded in the last frame has a different assignment in the crease pattern.
17 case assignmentDisagreesWithPattern(edge: Int)
18 /// The step's creases close a loop that does not stay closed.
19 case noRigidMotion(step: Int)
20 /// A solved curve, rebuilt from its samples, opens a gap between them.
21 case curveTooCoarse(step: Int)
22 /// A face of the crease pattern is clockwise seen from +z.
23 case clockwiseFace(face: Int)
24 /// A crease has no angle in the script and is neither `V` nor `M` in the crease pattern.
25 case missingAngle(step: Int)
26 /// `angles`, `peakAngles` or `windows` does not have one entry per crease.
27 case creaseListMismatch(step: Int)
28 /// The step names a `spine`; reverse folds and sinks are compiled by the non-rigid path.
29 case nonRigidStepNotSupported(step: Int)
30}
31
32/// Samples in a solved curve, evenly spaced over its window.
33private let curveSamples = 257
34/// Lengths are compared to within this fraction of the sheet's longer side.
35let relativeTolerance = 1e-6
36/// A crease's named endpoints match an edge's within this distance in crease-pattern units.
37private let creaseMatchTolerance = 1e-6
38/// A solved angle within this many degrees of linear at every sample is written without a curve.
39private let linearTolerance = 1e-9
40/// A measured end angle within this many degrees of an expected one is taken to be it.
41private let angleSnapTolerance = 1e-6
42/// Samples of a step checked for interpenetration.
43private let interpenetrationSamples = 64
44
45/// Compiles a fold script against its crease pattern into a FOLD sequence.
46///
47/// Frame 0 is the pattern with every crease reset to `F` and 0. Each step is planned from the
48/// script, its end frame produced by `FoldInterpolator.positions(at: 1)`, its layer order guessed
49/// and overridden, and the file so far validated and checked for interpenetration.
50public func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile {
51 let flat = pattern.frames[0]
52 for (f, normal) in faceNormals(flat, pattern).enumerated() where normal.z < 0 {
53 throw CompileError.clockwiseFace(face: f)
54 }
55 let finalAssignment = flat.edgesAssignment
56 let keyFrame = FoldFrame(verticesCoords: flat.verticesCoords,
57 edgesAssignment: finalAssignment.map { $0 == .boundary ? .boundary : .flat },
58 edgesFoldAngle: finalAssignment.map { _ in 0 },
59 faceOrders: [])
60 var file = FoldFile(fileSpec: 1.2, fileTitle: script.title, fileAuthor: pattern.fileAuthor,
61 fileClasses: ["diagrams"], edgesVertices: pattern.edgesVertices,
62 facesVertices: pattern.facesVertices,
63 edgesFirstCreasedAtStep: pattern.edgesVertices.map { _ in nil },
64 frames: [keyFrame])
65
66 var viewpoint = Viewpoint(eye: SIMD3(0, 0, 1), up: SIMD3(0, 1, 0))
67 for (i, step) in script.steps.enumerated() {
68 viewpoint = step.viewpoint ?? viewpoint
69 try appendStep(i + 1, step, viewpoint: viewpoint, to: &file, finalAssignment: finalAssignment)
70 }
71
72 let last = file.frames[file.frames.count - 1]
73 for e in file.edgesVertices.indices
74 where last.edgesFoldAngle[e] != 0 && last.edgesAssignment[e] != finalAssignment[e] {
75 throw CompileError.assignmentDisagreesWithPattern(edge: e)
76 }
77 return file
78}
79
80/// Compiles step `n` and appends frame n to `file`.
81private func appendStep(_ n: Int, _ script: ScriptStep, viewpoint: Viewpoint, to file: inout FoldFile,
82 finalAssignment: [EdgeAssignment]) throws {
83 if script.spine != nil { throw CompileError.nonRigidStepNotSupported(step: n) }
84 let previous = file.frames[n - 1]
85
86 var plan: FoldPlan?
87 if script.kind == .fold || script.kind == .foldAndUnfold {
88 plan = try planFolds(n, script, file, finalAssignment)
89 }
90 var record = StepRecord(kind: script.kind, technique: script.technique ?? .plain,
91 instruction: script.instruction, axes: plan?.axes ?? [],
92 rotateDegrees: script.rotateDegrees, turnOverAxis: script.turnOverAxis,
93 repeatOf: script.repeatOf, viewpoint: viewpoint)
94
95 // frame n with the start's coordinates, enough for readStep
96 var draft = file
97 draft.frames.append(FoldFrame(verticesCoords: previous.verticesCoords,
98 edgesAssignment: previous.edgesAssignment,
99 edgesFoldAngle: previous.edgesFoldAngle, faceOrders: [], step: record))
100 var step = try readStep(n, in: draft)
101 if let plan, !plan.loops.isEmpty {
102 record = try solveLoops(n, record, step, draft)
103 draft.frames[n].step = record
104 step = try readStep(n, in: draft)
105 try checkClosure(n, step, draft, solved: record.axes.contains { $0.angles != nil })
106 }
107 let interpolator = FoldInterpolator(file: draft, step: step)
108
109 var angles = previous.edgesFoldAngle
110 var assignment = previous.edgesAssignment
111 if let plan {
112 for axis in record.axes { angles[axis.edge] = axis.endAngle }
113 if script.kind == .fold {
114 for (e, angle) in try loopEndAngles(n, plan, previous, interpolator, file) { angles[e] = angle }
115 }
116 for e in plan.creased {
117 assignment[e] = angles[e] > 0 ? .valley : angles[e] < 0 ? .mountain : .flat
118 if file.edgesFirstCreasedAtStep[e] == nil { file.edgesFirstCreasedAtStep[e] = n }
119 }
120 }
121
122 var frame = FoldFrame(verticesCoords: interpolator.positions(at: 1), edgesAssignment: assignment,
123 edgesFoldAngle: angles, faceOrders: [], step: record)
124 let guess = guessFaceOrders(previous: previous, next: frame, step: record, file: file)
125 frame.faceOrders = try naming(n) {
126 try applyOrderOverrides(script.faceOrders ?? [], to: guess, frame: frame, viewpoint: viewpoint, file: file)
127 }
128 file.frames.append(frame)
129
130 if script.kind == .foldAndUnfold {
131 var peak = frame
132 peak.verticesCoords = interpolator.positions(at: 0.5)
133 let peakGuess = guessOrders(previous: previous, step: step, interpolator: interpolator,
134 positions: peak.verticesCoords, file: file,
135 arrival: { ($0.lowerBound + $0.upperBound) / 2 })
136 file.frames[n].faceOrdersMidFold = try naming(n) {
137 try applyOrderOverrides(script.faceOrdersMidFold ?? [], to: peakGuess, frame: peak,
138 viewpoint: viewpoint, file: file)
139 }
140 } else if script.kind == .fold
141 && (script.faceOrdersMidFold != nil || movingSetsOverlapInProjection(step: n, file)) {
142 file.frames[n].faceOrdersMidFold = try naming(n) {
143 try applyOrderOverrides(script.faceOrdersMidFold ?? [], to: frame.faceOrders, frame: frame,
144 viewpoint: viewpoint, file: file)
145 }
146 }
147
148 let defects = validate(file)
149 guard defects.isEmpty else { throw CompileError.stepFailed(step: n, defects: defects) }
150 let collisions = interpenetrations(interpolator, faces: file.facesVertices, samples: interpenetrationSamples)
151 guard collisions.isEmpty else { throw CompileError.interpenetration(step: n, collisions) }
152}
153
154/// Runs `body`, giving an `unresolvedFace` error the step number `n`.
155private func naming<T>(_ n: Int, _ body: () throws -> T) throws -> T {
156 do {
157 return try body()
158 } catch CompileError.unresolvedFace(_, let point) {
159 throw CompileError.unresolvedFace(step: n, point: point)
160 }
161}
162
163// MARK: - Planning a fold
164
165/// A fold or fold-and-unfold step's axes and the edges it creases.
166private struct FoldPlan {
167 /// One per edge of the region tree, driver first, without curves.
168 var axes: [AxisRecord]
169 /// Every edge whose two faces the step moves differently.
170 var creased: [Int]
171 /// Creased edges off the region tree, each closing a loop.
172 var loops: [Int]
173 /// The scripted end angle of each crease in `loops` that the script names with an angle.
174 var expected: [Int: Double]
175}
176
177/// Resolves the step's creases and moving side, cuts the sheet into regions along the creases
178/// and grows a tree of regions from the fixed one, across the creases in script order, driver
179/// first. Each tree edge is an axis; each other crease between different regions closes a loop.
180///
181/// Every edge that lies on a named crease's line in the start frame is cut too, so a crease
182/// through several layers folds each of them; one whose faces end up in the same region is not
183/// creased.
184private func planFolds(_ n: Int, _ script: ScriptStep, _ file: FoldFile,
185 _ finalAssignment: [EdgeAssignment]) throws -> FoldPlan {
186 let start = file.frames[n - 1]
187 let edgeFaces = edgesFaces(file)
188 let count = script.creases.count
189 for list in [script.angles?.count, script.peakAngles?.count, script.windows?.count] where list != nil && list != count {
190 throw CompileError.creaseListMismatch(step: n)
191 }
192
193 let named = try script.creases.map { ref in
194 guard let e = resolve(ref, file, edgeFaces) else { throw CompileError.unresolvedCrease(step: n) }
195 return e
196 }
197 guard !named.isEmpty, Set(named).count == named.count else { throw CompileError.unresolvedCrease(step: n) }
198 var driver = 0
199 if let ref = script.driver {
200 guard let e = resolve(ref, file, edgeFaces), let i = named.firstIndex(of: e) else {
201 throw CompileError.unresolvedCrease(step: n)
202 }
203 driver = i
204 }
205 let order = [driver] + named.indices.filter { $0 != driver }
206
207 // each crease with the index of the script crease it belongs to
208 var creases = order.map { (edge: named[$0], source: $0) }
209 let tolerance = sheetExtent(file) * relativeTolerance
210 for i in order {
211 let ends = file.edgesVertices[named[i]].map { start.verticesCoords[$0] }
212 for e in edgeFaces.indices where edgeFaces[e].count == 2 && !creases.contains(where: { $0.edge == e })
213 && file.edgesVertices[e].allSatisfy({ onLine(start.verticesCoords[$0], ends[0], ends[1], tolerance) }) {
214 creases.append((e, i))
215 }
216 }
217
218 // regions: faces connected across edges the step does not cut
219 let cut = Set(creases.map(\.edge))
220 var region = Array(repeating: -1, count: file.facesVertices.count)
221 var regionCount = 0
222 for seed in region.indices where region[seed] < 0 {
223 region[seed] = regionCount
224 var stack = [seed]
225 while let f = stack.popLast() {
226 for (e, faces) in edgeFaces.enumerated() where faces.count == 2 && faces.contains(f) && !cut.contains(e) {
227 let g = faces[0] == f ? faces[1] : faces[0]
228 if region[g] < 0 {
229 region[g] = regionCount
230 stack.append(g)
231 }
232 }
233 }
234 regionCount += 1
235 }
236
237 // nodes: 0 for the fixed regions, then each moving region in the order its point appears
238 guard !script.movingSide.isEmpty else { throw CompileError.unresolvedMovingSide(step: n) }
239 var nodeOfRegion = Array(repeating: 0, count: regionCount)
240 var nodeCount = 1
241 for point in script.movingSide {
242 guard let f = face(containing: point, file) else { throw CompileError.unresolvedMovingSide(step: n) }
243 if nodeOfRegion[region[f]] == 0 {
244 nodeOfRegion[region[f]] = nodeCount
245 nodeCount += 1
246 }
247 }
248 guard nodeOfRegion.contains(0) else { throw CompileError.unresolvedMovingSide(step: n) }
249 let node = region.map { nodeOfRegion[$0] }
250
251 // the tree, by union-find over the creases in order
252 var component = Array(0..<nodeCount)
253 func find(_ x: Int) -> Int {
254 var x = x
255 while component[x] != x { x = component[x] }
256 return x
257 }
258 var tree: [(edge: Int, source: Int, ends: (Int, Int))] = []
259 var creased: [Int] = [], loops: [Int] = []
260 for (e, source) in creases {
261 let a = node[edgeFaces[e][0]], b = node[edgeFaces[e][1]]
262 if a == b {
263 if e == named[source] { throw CompileError.unresolvedMovingSide(step: n) }
264 continue
265 }
266 creased.append(e)
267 if find(a) != find(b) {
268 component[find(a)] = find(b)
269 tree.append((e, source, (a, b)))
270 } else {
271 loops.append(e)
272 }
273 }
274
275 // orient the tree from the fixed node
276 var parentNode = Array<Int?>(repeating: nil, count: nodeCount)
277 var axisOfNode = Array<Int?>(repeating: nil, count: nodeCount)
278 var reached: Set<Int> = [0]
279 var queue = [0]
280 while !queue.isEmpty {
281 let a = queue.removeFirst()
282 for (k, t) in tree.enumerated() where t.ends.0 == a || t.ends.1 == a {
283 let b = t.ends.0 == a ? t.ends.1 : t.ends.0
284 guard reached.insert(b).inserted else { continue }
285 parentNode[b] = a
286 axisOfNode[b] = k
287 queue.append(b)
288 }
289 }
290
291 let axes = try tree.enumerated().map { k, t -> AxisRecord in
292 let child = axisOfNode[t.ends.0] == k ? t.ends.0 : t.ends.1
293 let parent = parentNode[child].flatMap { axisOfNode[$0] }
294 let isNamed = t.edge == named[t.source]
295 let movingFaces = node.indices.filter { node[$0] == child }
296 let startAngle = start.edgesFoldAngle[t.edge]
297 let window = script.windows?[t.source]
298 let written = window == [0, 1] ? nil : window
299 func endAngle(_ list: [Double]?) throws -> Double {
300 if isNamed, let list { return list[t.source] }
301 switch finalAssignment[t.edge] {
302 case .valley: return 180
303 case .mountain: return -180
304 default: throw CompileError.missingAngle(step: n)
305 }
306 }
307 if script.kind == .foldAndUnfold {
308 return AxisRecord(edge: t.edge, movingFaces: movingFaces, startAngle: startAngle, endAngle: startAngle,
309 peakAngle: try endAngle(script.peakAngles), parent: parent, window: written)
310 }
311 return AxisRecord(edge: t.edge, movingFaces: movingFaces, startAngle: startAngle,
312 endAngle: try endAngle(script.angles), parent: parent, window: written)
313 }
314
315 var expected: [Int: Double] = [:]
316 if let angles = script.angles {
317 for (e, source) in creases where loops.contains(e) && e == named[source] {
318 expected[e] = angles[source]
319 }
320 }
321 return FoldPlan(axes: axes, creased: creased, loops: loops, expected: expected)
322}
323
324/// The edge a crease reference names: by index, or the edge whose endpoints in the crease
325/// pattern are nearest the named points, within 1e-6. Boundary edges are not creases.
326private func resolve(_ ref: CreaseRef, _ file: FoldFile, _ edgeFaces: [[Int]]) -> Int? {
327 switch ref {
328 case .edgeIndex(let e):
329 return edgeFaces.indices.contains(e) && edgeFaces[e].count == 2 ? e : nil
330 case .betweenVertices(let p, let q):
331 let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) }
332 let nearest = file.edgesVertices.indices.map { e -> (edge: Int, distance: Double) in
333 let u = flat[file.edgesVertices[e][0]], v = flat[file.edgesVertices[e][1]]
334 return (e, min(max(distance(u, p), distance(v, q)), max(distance(u, q), distance(v, p))))
335 }.min { $0.distance < $1.distance }
336 guard let nearest, nearest.distance <= creaseMatchTolerance, edgeFaces[nearest.edge].count == 2 else {
337 return nil
338 }
339 return nearest.edge
340 }
341}
342
343/// The first face of the crease pattern whose closed outline contains `point`.
344func face(containing point: SIMD2<Double>, _ file: FoldFile) -> Int? {
345 let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) }
346 return file.facesVertices.indices.first { f in
347 let corners = file.facesVertices[f].map { flat[$0] }
348 return corners.indices.allSatisfy { i in
349 let a = corners[i], side = corners[(i + 1) % corners.count] - a, offset = point - a
350 return side.x * offset.y - side.y * offset.x >= 0
351 }
352 }
353}
354
355private func onLine(_ p: SIMD3<Double>, _ a: SIMD3<Double>, _ b: SIMD3<Double>, _ tolerance: Double) -> Bool {
356 length(cross(p - a, normalize(b - a))) <= tolerance
357}
358
359/// The longer side of frame 0's bounding box.
360func sheetExtent(_ file: FoldFile) -> Double {
361 let points = file.frames[0].verticesCoords
362 let lower = points.dropFirst().reduce(points[0], simd_min)
363 let upper = points.dropFirst().reduce(points[0], simd_max)
364 return (upper - lower).max()
365}
366
367// MARK: - Loops
368
369/// Holds the driver (the first axis in `record`) linear on its window and solves every other
370/// axis so the loops stay closed: damped Gauss–Newton on the gap between vertex copies, continued
371/// along the window from the previous samples. Each solved axis takes the driver's window and a
372/// curve of 257 samples, or none when it is linear to within 1e-9°; the last sample is the end
373/// angle exactly.
374private func solveLoops(_ n: Int, _ record: StepRecord, _ step: FoldStep, _ file: FoldFile) throws -> StepRecord {
375 guard let driver = step.axes.firstIndex(where: { $0.edge == record.axes[0].edge }) else { return record }
376 let free = step.axes.indices.filter { $0 != driver }
377 guard !free.isEmpty else { return record }
378
379 let kinematics = LoopKinematics(step: step, file: file)
380 let tolerance = sheetExtent(file) * relativeTolerance
381 let window = step.axes[driver].window
382 let fraction = { (k: Int) in Double(k) / Double(curveSamples - 1) }
383 func linear(_ axis: FoldAxis, _ u: Double) -> Double {
384 step.kind == .foldAndUnfold
385 ? axis.startAngle + ((axis.peakAngle ?? axis.endAngle) - axis.startAngle) * (1 - abs(2 * u - 1))
386 : axis.startAngle + u * (axis.endAngle - axis.startAngle)
387 }
388
389 var samples: [[Double]] = []
390 for k in 0..<curveSamples {
391 let u = fraction(k)
392 var guess = switch k {
393 case 0: step.axes.map(\.startAngle)
394 case 1: step.axes.map { linear($0, u) }
395 default: zip(samples[k - 1], samples[k - 2]).map { 2 * $0 - $1 }
396 }
397 guess[driver] = linear(step.axes[driver], u)
398 guard kinematics.solve(&guess, free: free) <= tolerance else { throw CompileError.noRigidMotion(step: n) }
399 samples.append(guess)
400 }
401
402 var axes = record.axes
403 for a in free {
404 let axis = step.axes[a]
405 var curve = samples.map { $0[a] }
406 curve[curveSamples - 1] = axis.endAngle
407 let isLinear = curve.indices.allSatisfy { abs(curve[$0] - linear(axis, fraction($0))) <= linearTolerance }
408 guard let i = axes.firstIndex(where: { $0.edge == axis.edge }) else { continue }
409 let r = axes[i]
410 axes[i] = AxisRecord(edge: r.edge, movingFaces: r.movingFaces, startAngle: r.startAngle,
411 endAngle: r.endAngle, peakAngle: r.peakAngle, parent: r.parent,
412 window: window == 0...1 ? nil : [window.lowerBound, window.upperBound],
413 angles: isLinear ? nil : curve)
414 }
415 return StepRecord(kind: record.kind, technique: record.technique, instruction: record.instruction,
416 axes: axes, rotateDegrees: record.rotateDegrees, turnOverAxis: record.turnOverAxis,
417 repeatOf: record.repeatOf, nonRigid: record.nonRigid, pop: record.pop,
418 viewpoint: record.viewpoint)
419}
420
421/// Checks the step's loops stay closed as its axes move, at four times the curve sample density
422/// over the driver's window and over the whole step.
423private func checkClosure(_ n: Int, _ step: FoldStep, _ file: FoldFile, solved: Bool) throws {
424 let kinematics = LoopKinematics(step: step, file: file)
425 let tolerance = sheetExtent(file) * relativeTolerance
426 let intervals = 4 * (curveSamples - 1)
427 let window = step.axes.first?.window ?? 0...1
428 let times = (0...intervals).flatMap { k -> [Double] in
429 let u = Double(k) / Double(intervals)
430 return [u, window.lowerBound + u * (window.upperBound - window.lowerBound)]
431 }
432 for t in times where kinematics.gap(step.axes.map { $0.angle(at: t, kind: step.kind) }) > tolerance {
433 throw solved ? CompileError.curveTooCoarse(step: n) : CompileError.noRigidMotion(step: n)
434 }
435}
436
437/// The end angle of each loop crease, measured from the faces' normals along the step and
438/// unwrapped from its start angle, then taken to be its scripted angle, ±180 or 0 when within
439/// 1e-6° of one.
440private func loopEndAngles(_ n: Int, _ plan: FoldPlan, _ previous: FoldFrame, _ interpolator: FoldInterpolator,
441 _ file: FoldFile) throws -> [Int: Double] {
442 let edgeFaces = edgesFaces(file)
443 var current = Dictionary(uniqueKeysWithValues: plan.loops.map { ($0, previous.edgesFoldAngle[$0]) })
444 let intervals = curveSamples - 1
445 for k in 1...intervals {
446 let positions = interpolator.positions(at: Double(k) / Double(intervals))
447 let normals = faceNormals(positions: positions, faces: file.facesVertices)
448 for e in plan.loops {
449 let measured = dihedral(e, edgeFaces[e], positions, normals, file)
450 current[e] = measured + 360 * ((current[e]! - measured) / 360).rounded()
451 }
452 }
453 var result: [Int: Double] = [:]
454 for (e, angle) in current {
455 let candidates = (plan.expected[e].map { [$0] } ?? []) + [180, -180, 0]
456 let snapped = candidates.first { abs(angle - $0) <= angleSnapTolerance } ?? angle
457 if let expected = plan.expected[e], snapped != expected { throw CompileError.noRigidMotion(step: n) }
458 result[e] = snapped
459 }
460 return result
461}
462
463/// The fold angle in degrees of an interior edge between faces `faces`, positive for a valley:
464/// the turn from the first face's normal to the second's about the edge, directed as the second
465/// face traverses it.
466private func dihedral(_ e: Int, _ faces: [Int], _ positions: [SIMD3<Double>], _ normals: [SIMD3<Double>],
467 _ file: FoldFile) -> Double {
468 let corners = file.facesVertices[faces[1]], ends = Set(file.edgesVertices[e])
469 let i = corners.indices.first { ends == Set([corners[$0], corners[($0 + 1) % corners.count]]) }!
470 let d = normalize(positions[corners[(i + 1) % corners.count]] - positions[corners[i]])
471 let a = normals[faces[0]], b = normals[faces[1]]
472 return atan2(dot(cross(a, b), d), dot(a, b)) * 180 / .pi
473}
474
475/// p ↦ q·p + t
476private struct Rigid {
477 var q = simd_quatd(ix: 0, iy: 0, iz: 0, r: 1)
478 var t = SIMD3<Double>.zero
479
480 func apply(_ p: SIMD3<Double>) -> SIMD3<Double> { q.act(p) + t }
481
482 /// This transform applied after `inner`.
483 func after(_ inner: Rigid) -> Rigid { Rigid(q: q * inner.q, t: q.act(inner.t) + t) }
484
485 static func rotation(about origin: SIMD3<Double>, direction: SIMD3<Double>, degrees: Double) -> Rigid {
486 let q = simd_quatd(angle: degrees * .pi / 180, axis: direction)
487 return Rigid(q: q, t: origin - q.act(origin))
488 }
489}
490
491/// A step's axes as functions of their angles, and the gap between the copies of each vertex
492/// that faces moving with different axes carry.
493private struct LoopKinematics {
494 let axes: [FoldAxis]
495 let start: [SIMD3<Double>]
496 /// Each vertex shared by faces that move differently, with the axes that move them, −1 for
497 /// a still face.
498 let copies: [(vertex: Int, axes: [Int])]
499
500 init(step: FoldStep, file: FoldFile) {
501 axes = step.axes
502 start = file.frames[step.index - 1].verticesCoords
503 var axisOfFace = Array(repeating: -1, count: file.facesVertices.count)
504 for (a, axis) in step.axes.enumerated() {
505 for f in axis.movingFaces { axisOfFace[f] = a }
506 }
507 var movers = Array(repeating: [Int](), count: start.count)
508 for (f, corners) in file.facesVertices.enumerated() {
509 for v in corners where !movers[v].contains(axisOfFace[f]) { movers[v].append(axisOfFace[f]) }
510 }
511 copies = movers.indices.filter { movers[$0].count > 1 }.map { ($0, movers[$0]) }
512 }
513
514 func residual(_ angles: [Double]) -> [Double] {
515 var full: [Rigid] = []
516 for (a, axis) in axes.enumerated() {
517 let own = Rigid.rotation(about: axis.origin, direction: axis.direction,
518 degrees: angles[a] - axis.startAngle)
519 full.append(axis.parent.map { full[$0].after(own) } ?? own)
520 }
521 func place(_ a: Int, _ p: SIMD3<Double>) -> SIMD3<Double> { a < 0 ? p : full[a].apply(p) }
522 var r: [Double] = []
523 for (v, movers) in copies {
524 let base = place(movers[0], start[v])
525 for a in movers.dropFirst() {
526 let d = place(a, start[v]) - base
527 r += [d.x, d.y, d.z]
528 }
529 }
530 return r
531 }
532
533 /// The largest distance between two copies of one vertex.
534 func gap(_ angles: [Double]) -> Double {
535 let r = residual(angles)
536 return stride(from: 0, to: r.count, by: 3).map { length(SIMD3(r[$0], r[$0 + 1], r[$0 + 2])) }.max() ?? 0
537 }
538
539 /// Damped Gauss–Newton on the angles of the axes in `free`, holding the rest. Returns the gap
540 /// it reaches.
541 func solve(_ angles: inout [Double], free: [Int], iterations: Int = 60) -> Double {
542 var lambda = 1e-6
543 var r = residual(angles)
544 var cost = r.reduce(0) { $0 + $1 * $1 }
545 for _ in 0..<iterations {
546 if cost < 1e-26 { break }
547 let h = 1e-6
548 var jacobian = Array(repeating: [Double](repeating: 0, count: free.count), count: r.count)
549 for (k, a) in free.enumerated() {
550 var probe = angles
551 probe[a] += h
552 let plus = residual(probe)
553 probe[a] -= 2 * h
554 let minus = residual(probe)
555 for i in r.indices { jacobian[i][k] = (plus[i] - minus[i]) / (2 * h) }
556 }
557 var improved = false
558 for _ in 0..<20 {
559 var normal = Array(repeating: [Double](repeating: 0, count: free.count), count: free.count)
560 var gradient = [Double](repeating: 0, count: free.count)
561 for i in r.indices {
562 for a in free.indices {
563 gradient[a] -= jacobian[i][a] * r[i]
564 for b in free.indices { normal[a][b] += jacobian[i][a] * jacobian[i][b] }
565 }
566 }
567 for a in free.indices { normal[a][a] += lambda * (1 + normal[a][a]) }
568 guard let delta = solveLinear(normal, gradient) else {
569 lambda *= 10
570 continue
571 }
572 var trial = angles
573 for (k, a) in free.enumerated() { trial[a] += delta[k] }
574 let rt = residual(trial)
575 let ct = rt.reduce(0) { $0 + $1 * $1 }
576 if ct < cost {
577 angles = trial
578 r = rt
579 cost = ct
580 lambda = max(lambda / 10, 1e-12)
581 improved = true
582 break
583 }
584 lambda *= 10
585 }
586 if !improved { break }
587 }
588 return gap(angles)
589 }
590}
591
592/// Gaussian elimination with partial pivoting; nil when `a` is singular.
593private func solveLinear(_ a: [[Double]], _ b: [Double]) -> [Double]? {
594 var m = a, x = b
595 let n = b.count
596 for c in 0..<n {
597 guard let p = (c..<n).max(by: { abs(m[$0][c]) < abs(m[$1][c]) }), abs(m[p][c]) > 1e-300 else { return nil }
598 m.swapAt(c, p)
599 x.swapAt(c, p)
600 for r in (c + 1)..<n {
601 let f = m[r][c] / m[c][c]
602 if f == 0 { continue }
603 for k in c..<n { m[r][k] -= f * m[c][k] }
604 x[r] -= f * x[c]
605 }
606 }
607 for c in stride(from: n - 1, through: 0, by: -1) {
608 var s = x[c]
609 for k in (c + 1)..<n { s -= m[c][k] * x[k] }
610 x[c] = s / m[c][c]
611 }
612 return x
613}
Packages/FoldKit/Sources/FoldCompiler/LayerOrderGuess.swift added +212
@@ -0,0 +1,212 @@
1import FoldFormat
2import Folding
3import simd
4
5/// Two unit normals whose dot product's magnitude reaches this lie on one line.
6private let parallelCosine = 1 - 1e-9
7/// How far before a pair's arrival the guess looks, as a fraction of the arriving axis's window.
8private let arrivalLead = 1e-3
9/// Two layers closer than this fraction of the sheet's size at that moment are not told apart.
10private let separationTolerance = 1e-9
11
12/// Guesses `next`'s `faceOrders`, every overlapping pair once as `[f, g, s]` with `f < g`.
13///
14/// Faces that move together, or both stay still, keep frame n − 1's relation. Otherwise the face
15/// that arrives last is placed on the side it arrives from: the pair is compared just before the
16/// last axis that moves them differently finishes, at the paper points that meet in the middle
17/// of their overlap. A moving set that has turned over arrives with its layers reversed. This is
18/// right for plain valley and mountain folds and wrong for a flap tucked between layers, which the
19/// script corrects with overrides.
20///
21/// - Precondition: `step` is one `readStep` accepts with `previous` as its start frame.
22public func guessFaceOrders(previous: FoldFrame, next: FoldFrame, step: StepRecord, file: FoldFile) -> [[Int]] {
23 var end = next
24 end.step = step
25 let draft = FoldFile(fileSpec: file.fileSpec, edgesVertices: file.edgesVertices,
26 facesVertices: file.facesVertices,
27 edgesFirstCreasedAtStep: file.edgesFirstCreasedAtStep,
28 frames: [file.frames[0], previous, end])
29 guard let folding = try? readStep(2, in: draft) else {
30 preconditionFailure("guessFaceOrders needs a step that readStep accepts")
31 }
32 return guessOrders(previous: previous, step: folding, interpolator: FoldInterpolator(file: draft, step: folding),
33 positions: next.verticesCoords, file: file, arrival: { $0.upperBound })
34}
35
36/// The guess for the faces at `positions`, a state of `step`; `arrival` gives the time within an
37/// axis's window at which its faces reach that state.
38func guessOrders(previous: FoldFrame, step: FoldStep, interpolator: FoldInterpolator, positions: [SIMD3<Double>],
39 file: FoldFile, arrival: (ClosedRange<Double>) -> Double) -> [[Int]] {
40 let faces = file.facesVertices
41 let size = sheetExtent(file)
42 let normals = faceNormals(positions: positions, faces: faces)
43
44 var before: [SIMD2<Int>: Int] = [:]
45 for (pair, s) in rigidInvariantFaceOrders(previous.faceOrders, normals: faceNormals(previous, file))
46 where before[pair] == nil {
47 before[pair] = s
48 }
49 var axisOfFace: [Int: Int] = [:]
50 for (a, axis) in step.axes.enumerated() {
51 for f in axis.movingFaces { axisOfFace[f] = a }
52 }
53 func carriers(_ f: Int) -> Set<Int> {
54 var result = Set<Int>(), a = axisOfFace[f]
55 while let axis = a, result.insert(axis).inserted { a = step.axes[axis].parent }
56 return result
57 }
58
59 var sampled: [Double: [SIMD3<Double>]] = [:]
60 var orders: [[Int]] = []
61 for (a, b) in overlappingPairs(positions, faces, normals, tolerance: size * relativeTolerance) {
62 let differing = carriers(a).symmetricDifference(carriers(b))
63 guard let last = differing.max(by: { arrival(step.axes[$0].window) < arrival(step.axes[$1].window) }) else {
64 if let s = before[SIMD2(a, b)] { orders.append([a, b, s]) }
65 continue
66 }
67 let window = step.axes[last].window
68 let t = arrival(window) - arrivalLead * (window.upperBound - window.lowerBound)
69 let near = sampled[t] ?? interpolator.positions(at: t)
70 sampled[t] = near
71 let meeting = overlapCentre(a, b, positions, faces, normals)
72 let separation = dot(carry(meeting, on: faces[a], from: positions, to: near)
73 - carry(meeting, on: faces[b], from: positions, to: near), normals[b])
74 if abs(separation) > size * separationTolerance {
75 orders.append([a, b, separation > 0 ? 1 : -1])
76 } else if let s = before[SIMD2(a, b)] {
77 orders.append([a, b, s])
78 }
79 }
80 return orders
81}
82
83/// Replaces the order of each overridden pair, adding it when absent. Each override names its
84/// faces by points in the crease pattern and puts `above` nearer the eye than `below`; the result
85/// keeps every pair once as `[f, g, s]` with `f < g`, sorted.
86///
87/// - Throws: `CompileError.unresolvedFace` with step 0 when a point lies on no face; `compile`
88/// reports the step.
89public func applyOrderOverrides(_ overrides: [OrderOverride], to orders: [[Int]], frame: FoldFrame,
90 viewpoint: Viewpoint, file: FoldFile) throws -> [[Int]] {
91 guard !overrides.isEmpty else { return orders }
92 let normals = faceNormals(frame, file)
93 var result = orders
94 for o in overrides {
95 guard let above = face(containing: o.above, file) else {
96 throw CompileError.unresolvedFace(step: 0, point: o.above)
97 }
98 guard let below = face(containing: o.below, file) else {
99 throw CompileError.unresolvedFace(step: 0, point: o.below)
100 }
101 let s = dot(normals[below], viewpoint.eye) > 0 ? 1 : -1
102 let triple = above < below
103 ? [above, below, s]
104 : [below, above, dot(normals[above], normals[below]) > 0 ? -s : s]
105 result.removeAll { Set($0.prefix(2)) == Set([above, below]) }
106 result.append(triple)
107 }
108 return result.sorted { ($0[0], $0[1]) < ($1[0], $1[1]) }
109}
110
111/// Pairs `(a, b)`, `a < b`, of faces in one plane whose interiors overlap.
112private func overlappingPairs(_ positions: [SIMD3<Double>], _ faces: [[Int]], _ normals: [SIMD3<Double>],
113 tolerance: Double) -> [(Int, Int)] {
114 var pairs: [(Int, Int)] = []
115 for a in faces.indices where normals[a] != .zero {
116 let corner = positions[faces[a][0]]
117 let (u, v) = planeBasis(normals[a])
118 let project = { (f: Int) in faces[f].map { SIMD2(dot(positions[$0], u), dot(positions[$0], v)) } }
119 let outline = project(a)
120 for b in faces.indices.dropFirst(a + 1) where normals[b] != .zero
121 && abs(dot(normals[a], normals[b])) >= parallelCosine
122 && faces[b].allSatisfy({ abs(dot(positions[$0] - corner, normals[a])) <= tolerance })
123 && convexPolygonsOverlap(outline, project(b), tolerance: tolerance) {
124 pairs.append((a, b))
125 }
126 }
127 return pairs
128}
129
130/// The centroid of the overlap of two coplanar faces, in their plane.
131private func overlapCentre(_ a: Int, _ b: Int, _ positions: [SIMD3<Double>], _ faces: [[Int]],
132 _ normals: [SIMD3<Double>]) -> SIMD3<Double> {
133 let n = normals[a]
134 let (u, v) = planeBasis(n)
135 let project = { (f: Int) in
136 counterclockwise(faces[f].map { SIMD2(dot(positions[$0], u), dot(positions[$0], v)) })
137 }
138 var overlap = project(a)
139 let clip = project(b)
140 for i in clip.indices where !overlap.isEmpty {
141 overlap = keepLeft(of: clip[i], clip[(i + 1) % clip.count], overlap)
142 }
143 let c = centroid(overlap)
144 return c.x * u + c.y * v + dot(positions[faces[a][0]], n) * n
145}
146
147/// `point`, a point of the face with corners `corners` at `from`, where the same point of paper
148/// is at `to`. Both states must place the face rigidly.
149private func carry(_ point: SIMD3<Double>, on corners: [Int], from: [SIMD3<Double>], to: [SIMD3<Double>]) -> SIMD3<Double> {
150 // the corner triangle with the largest area gives the best-conditioned weights
151 var best = (0, 1, 2), largest = -1.0
152 for i in corners.indices {
153 for j in corners.indices where j > i {
154 for k in corners.indices where k > j {
155 let area = length(cross(from[corners[j]] - from[corners[i]], from[corners[k]] - from[corners[i]]))
156 if area > largest { (best, largest) = ((i, j, k), area) }
157 }
158 }
159 }
160 let (p, q, r) = (corners[best.0], corners[best.1], corners[best.2])
161 let e1 = from[q] - from[p], e2 = from[r] - from[p], d = point - from[p]
162 let d11 = dot(e1, e1), d12 = dot(e1, e2), d22 = dot(e2, e2)
163 let denominator = d11 * d22 - d12 * d12
164 let wq = (d22 * dot(d, e1) - d12 * dot(d, e2)) / denominator
165 let wr = (d11 * dot(d, e2) - d12 * dot(d, e1)) / denominator
166 return to[p] + wq * (to[q] - to[p]) + wr * (to[r] - to[p])
167}
168
169/// Two unit vectors spanning the plane with unit normal `n`.
170private func planeBasis(_ n: SIMD3<Double>) -> (SIMD3<Double>, SIMD3<Double>) {
171 let helper: SIMD3<Double> = abs(n.x) < 0.9 ? SIMD3(1, 0, 0) : SIMD3(0, 1, 0)
172 let u = normalize(cross(n, helper))
173 return (u, cross(n, u))
174}
175
176private func signedArea(_ p: [SIMD2<Double>]) -> Double {
177 p.indices.reduce(0) { sum, i in
178 let a = p[i], b = p[(i + 1) % p.count]
179 return sum + (a.x * b.y - b.x * a.y) / 2
180 }
181}
182
183private func counterclockwise(_ p: [SIMD2<Double>]) -> [SIMD2<Double>] {
184 signedArea(p) < 0 ? p.reversed() : p
185}
186
187/// The area centroid of a polygon, or its corners' mean when it has no area.
188private func centroid(_ p: [SIMD2<Double>]) -> SIMD2<Double> {
189 let area = signedArea(p)
190 guard abs(area) > 0 else { return p.reduce(.zero, +) / Double(max(p.count, 1)) }
191 var sum = SIMD2<Double>.zero
192 for i in p.indices {
193 let a = p[i], b = p[(i + 1) % p.count]
194 sum += (a + b) * (a.x * b.y - b.x * a.y)
195 }
196 return sum / (6 * area)
197}
198
199/// The part of convex polygon `p` to the left of the directed line from `a` to `b`.
200private func keepLeft(of a: SIMD2<Double>, _ b: SIMD2<Double>, _ p: [SIMD2<Double>]) -> [SIMD2<Double>] {
201 let d = b - a
202 let side = p.map { d.x * ($0.y - a.y) - d.y * ($0.x - a.x) }
203 var result: [SIMD2<Double>] = []
204 for i in p.indices {
205 let j = (i + 1) % p.count
206 if side[i] >= 0 { result.append(p[i]) }
207 if (side[i] > 0 && side[j] < 0) || (side[i] < 0 && side[j] > 0) {
208 result.append(p[i] + (p[j] - p[i]) * (side[i] / (side[i] - side[j])))
209 }
210 }
211 return result
212}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/angle-out-of-range.foldscript added +20
@@ -0,0 +1,20 @@
1{
2 "creasePattern": "half-cp.fold",
3 "title": "Angle out of range",
4 "steps": [
5 {
6 "kind": "fold",
7 "instruction": "Valley fold the right half to a right angle.",
8 "creases": [[[1, 0], [1, 2]]],
9 "movingSide": [[1.5, 1]],
10 "angles": [90]
11 },
12 {
13 "kind": "fold",
14 "instruction": "Fold the right half past flat.",
15 "creases": [[[1, 0], [1, 2]]],
16 "movingSide": [[1.5, 1]],
17 "angles": [200]
18 }
19 ]
20}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/half-cp.fold added +10
@@ -0,0 +1,10 @@
1{
2 "file_spec": 1.2,
3 "file_title": "Half",
4 "file_author": "Traditional",
5 "file_classes": ["creasePattern"],
6 "vertices_coords": [[0, 0], [1, 0], [2, 0], [2, 2], [1, 2], [0, 2]],
7 "edges_vertices": [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 0], [1, 4]],
8 "edges_assignment": ["B", "B", "B", "B", "B", "B", "V"],
9 "faces_vertices": [[0, 1, 4, 5], [1, 2, 3, 4]]
10}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/half.foldscript added +22
@@ -0,0 +1,22 @@
1{
2 "creasePattern": "half-cp.fold",
3 "title": "Half",
4 "steps": [
5 {
6 "kind": "fold",
7 "instruction": "Valley fold the right half over to the left.",
8 "creases": [[[1, 0], [1, 2]]],
9 "movingSide": [[1.5, 1]]
10 },
11 {
12 "kind": "turnOver",
13 "instruction": "Turn the paper over from side to side.",
14 "turnOverAxis": "vertical"
15 },
16 {
17 "kind": "rotate",
18 "instruction": "Rotate the paper a quarter turn counterclockwise.",
19 "rotateDegrees": 90
20 }
21 ]
22}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/letter-cp.fold added +10
@@ -0,0 +1,10 @@
1{
2 "file_spec": 1.2,
3 "file_title": "Letter",
4 "file_author": "Traditional",
5 "file_classes": ["creasePattern"],
6 "vertices_coords": [[0, 0], [1, 0], [2, 0], [3, 0], [3, 3], [2, 3], [1, 3], [0, 3]],
7 "edges_vertices": [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 0], [1, 6], [2, 5]],
8 "edges_assignment": ["B", "B", "B", "B", "B", "B", "B", "B", "V", "M"],
9 "faces_vertices": [[0, 1, 6, 7], [1, 2, 5, 6], [2, 3, 4, 5]]
10}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/letter-sequential-cp.fold added +10
@@ -0,0 +1,10 @@
1{
2 "file_spec": 1.2,
3 "file_title": "Letter, sequential",
4 "file_author": "Traditional",
5 "file_classes": ["creasePattern"],
6 "vertices_coords": [[0, 0], [1, 0], [2, 0], [3, 0], [3, 3], [2, 3], [1, 3], [0, 3]],
7 "edges_vertices": [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 0], [1, 6], [2, 5]],
8 "edges_assignment": ["B", "B", "B", "B", "B", "B", "B", "B", "V", "V"],
9 "faces_vertices": [[0, 1, 6, 7], [1, 2, 5, 6], [2, 3, 4, 5]]
10}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/letter-sequential.foldscript added +19
@@ -0,0 +1,19 @@
1{
2 "creasePattern": "letter-sequential-cp.fold",
3 "title": "Letter, sequential",
4 "steps": [
5 {
6 "kind": "fold",
7 "instruction": "Valley fold the left third over.",
8 "creases": [[[1, 0], [1, 3]]],
9 "movingSide": [[0.5, 1.5]]
10 },
11 {
12 "kind": "fold",
13 "instruction": "Repeat on the right: valley fold the right third over the top.",
14 "creases": [[[2, 0], [2, 3]]],
15 "movingSide": [[2.5, 1.5]],
16 "repeatOf": 1
17 }
18 ]
19}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/letter-staggered-cp.fold added +10
@@ -0,0 +1,10 @@
1{
2 "file_spec": 1.2,
3 "file_title": "Letter, staggered",
4 "file_author": "Traditional",
5 "file_classes": ["creasePattern"],
6 "vertices_coords": [[0, 0], [1, 0], [2, 0], [3, 0], [3, 3], [2, 3], [1, 3], [0, 3]],
7 "edges_vertices": [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 0], [1, 6], [2, 5]],
8 "edges_assignment": ["B", "B", "B", "B", "B", "B", "B", "B", "V", "V"],
9 "faces_vertices": [[0, 1, 6, 7], [1, 2, 5, 6], [2, 3, 4, 5]]
10}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/letter-staggered.foldscript added +13
@@ -0,0 +1,13 @@
1{
2 "creasePattern": "letter-staggered-cp.fold",
3 "title": "Letter, staggered",
4 "steps": [
5 {
6 "kind": "fold",
7 "instruction": "Valley fold the left third over, then the right third over the top.",
8 "creases": [[[1, 0], [1, 3]], [[2, 0], [2, 3]]],
9 "movingSide": [[0.5, 1.5], [2.5, 1.5]],
10 "windows": [[0, 0.5], [0.5, 1]]
11 }
12 ]
13}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/letter.foldscript added +12
@@ -0,0 +1,12 @@
1{
2 "creasePattern": "letter-cp.fold",
3 "title": "Letter",
4 "steps": [
5 {
6 "kind": "fold",
7 "instruction": "Valley fold the left third over and mountain fold the right third behind.",
8 "creases": [[[1, 0], [1, 3]], [[2, 0], [2, 3]]],
9 "movingSide": [[0.5, 1.5], [2.5, 1.5]]
10 }
11 ]
12}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/mountain-cp.fold added +10
@@ -0,0 +1,10 @@
1{
2 "file_spec": 1.2,
3 "file_title": "Mountain",
4 "file_author": "Traditional",
5 "file_classes": ["creasePattern"],
6 "vertices_coords": [[0, 0], [1, 0], [2, 0], [2, 2], [1, 2], [0, 2]],
7 "edges_vertices": [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 0], [1, 4]],
8 "edges_assignment": ["B", "B", "B", "B", "B", "B", "M"],
9 "faces_vertices": [[0, 1, 4, 5], [1, 2, 3, 4]]
10}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/mountain.foldscript added +12
@@ -0,0 +1,12 @@
1{
2 "creasePattern": "mountain-cp.fold",
3 "title": "Mountain",
4 "steps": [
5 {
6 "kind": "fold",
7 "instruction": "Mountain fold the right half behind.",
8 "creases": [[[1, 0], [1, 2]]],
9 "movingSide": [[1.5, 1]]
10 }
11 ]
12}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/occlusion-cp.fold added +10
@@ -0,0 +1,10 @@
1{
2 "file_spec": 1.2,
3 "file_title": "Occlusion",
4 "file_author": "Traditional",
5 "file_classes": ["creasePattern"],
6 "vertices_coords": [[0, 0], [2, 0], [2.5, 0], [4, 0], [4, 4], [2.5, 4], [0, 4], [0, 2]],
7 "edges_vertices": [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 0], [7, 1], [2, 5]],
8 "edges_assignment": ["B", "B", "B", "B", "B", "B", "B", "B", "V", "V"],
9 "faces_vertices": [[0, 1, 7], [1, 2, 5, 6, 7], [2, 3, 4, 5]]
10}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/occlusion.foldscript added +23
@@ -0,0 +1,23 @@
1{
2 "creasePattern": "occlusion-cp.fold",
3 "title": "Occlusion",
4 "steps": [
5 {
6 "kind": "fold",
7 "instruction": "Valley fold the bottom left corner up to the centre.",
8 "creases": [[[0, 2], [2, 0]]],
9 "movingSide": [[0.5, 0.5]]
10 },
11 {
12 "kind": "fold",
13 "instruction": "Valley fold the right edge over along the crease.",
14 "creases": [[[2.5, 0], [2.5, 4]]],
15 "movingSide": [[3, 2]]
16 },
17 {
18 "kind": "turnOver",
19 "instruction": "Turn the paper over from side to side.",
20 "turnOverAxis": "vertical"
21 }
22 ]
23}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/quarters-cp.fold added +10
@@ -0,0 +1,10 @@
1{
2 "file_spec": 1.2,
3 "file_title": "Quarters",
4 "file_author": "Traditional",
5 "file_classes": ["creasePattern"],
6 "vertices_coords": [[0, 0], [1, 0], [2, 0], [2, 1], [2, 2], [1, 2], [0, 2], [0, 1], [1, 1]],
7 "edges_vertices": [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 0], [1, 8], [8, 5], [7, 8], [8, 3]],
8 "edges_assignment": ["B", "B", "B", "B", "B", "B", "B", "B", "V", "M", "V", "V"],
9 "faces_vertices": [[0, 1, 8, 7], [1, 2, 3, 8], [8, 3, 4, 5], [7, 8, 5, 6]]
10}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/quarters.foldscript added +24
@@ -0,0 +1,24 @@
1{
2 "creasePattern": "quarters-cp.fold",
3 "title": "Quarters",
4 "steps": [
5 {
6 "kind": "foldAndUnfold",
7 "instruction": "Valley fold in half from right to left and unfold.",
8 "creases": [[[1, 0], [1, 1]]],
9 "movingSide": [[1.5, 0.5]]
10 },
11 {
12 "kind": "fold",
13 "instruction": "Valley fold the top half down.",
14 "creases": [[[0, 1], [1, 1]]],
15 "movingSide": [[0.5, 1.5]]
16 },
17 {
18 "kind": "fold",
19 "instruction": "Valley fold the right half over to the left.",
20 "creases": [[[1, 0], [1, 1]]],
21 "movingSide": [[1.5, 0.5]]
22 }
23 ]
24}
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/unresolved-crease.foldscript added +18
@@ -0,0 +1,18 @@
1{
2 "creasePattern": "half-cp.fold",
3 "title": "Unresolved crease",
4 "steps": [
5 {
6 "kind": "fold",
7 "instruction": "Valley fold the right half over to the left.",
8 "creases": [[[1, 0], [1, 2]]],
9 "movingSide": [[1.5, 1]]
10 },
11 {
12 "kind": "fold",
13 "instruction": "Fold along a crease the pattern does not have.",
14 "creases": [[[0, 1], [1, 1]]],
15 "movingSide": [[0.5, 1.5]]
16 }
17 ]
18}
Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift +93
@@ -1,4 +1,5 @@
1import Foundation 1import Foundation
2import FoldCompiler
2import FoldFormat 3import FoldFormat
3import Folding 4import Folding
4import simd 5import simd
@@ -88,6 +89,38 @@ public func degreeFourVertex(linear: Bool = false) -> FoldFile {
88 ) 89 )
89} 90}
90 91
92/// `degreeFourVertex()` as a crease pattern: its sheet and creases with their final assignments,
93/// no frames.
94public func degreeFourPattern() -> FoldFile {
95 let vertex = degreeFourVertex()
96 return FoldFile(
97 fileSpec: 1.2,
98 fileTitle: vertex.fileTitle,
99 fileAuthor: vertex.fileAuthor,
100 fileClasses: ["creasePattern"],
101 edgesVertices: vertex.edgesVertices,
102 facesVertices: vertex.facesVertices,
103 edgesFirstCreasedAtStep: vertex.edgesVertices.map { _ in nil },
104 frames: [FoldFrame(verticesCoords: vertex.frames[0].verticesCoords,
105 edgesAssignment: vertex.frames[1].edgesAssignment,
106 edgesFoldAngle: vertex.edgesVertices.map { _ in 0 },
107 faceOrders: [])]
108 )
109}
110
111/// `degreeFourVertex()` as a one-step script: the 140° crease drives, then the 260°, 0° and 60°
112/// creases in that order, so the 60° crease closes the loop. The 120° sector is held.
113public func degreeFourScript() -> FoldScript {
114 func inside(_ degrees: Double) -> SIMD2<Double> {
115 SIMD2(1 + 0.5 * cos(radians(degrees)), 1 + 0.5 * sin(radians(degrees)))
116 }
117 return FoldScript(creasePattern: "", title: "Degree-4 vertex", steps: [
118 ScriptStep(kind: .fold, instruction: "Fold the vertex flat.",
119 creases: [.edgeIndex(10), .edgeIndex(11), .edgeIndex(8), .edgeIndex(9)],
120 movingSide: [inside(30), inside(100), inside(310)]),
121 ])
122}
123
91/// The fold angle, in degrees, of one of `degreeFourVertex()`'s creases at `t`, from the closed form. 124/// The fold angle, in degrees, of one of `degreeFourVertex()`'s creases at `t`, from the closed form.
92public func degreeFourExactAngle(_ edge: Int, at t: Double) -> Double { 125public func degreeFourExactAngle(_ edge: Int, at t: Double) -> Double {
93 let k = cos(radians(70)) / cos(radians(10)) 126 let k = cos(radians(70)) / cos(radians(10))
@@ -287,3 +320,63 @@ public func interpolatorForSharedVertexSweep() throws -> (FoldFile, FoldInterpol
287 ) 320 )
288 return (file, FoldInterpolator(file: file, step: step)) 321 return (file, FoldInterpolator(file: file, step: step))
289} 322}
323
324/// `<name>.foldscript` compiled against `<name>-cp.fold`.
325public func compiled(_ name: String) throws -> FoldFile {
326 try compile(FoldScript(contentsOf: fixture("\(name).foldscript")),
327 pattern: FoldFile(contentsOf: fixture("\(name)-cp.fold")))
328}
329
330/// Whether two files have the same metadata, topology, assignments, layer orders and steps, with
331/// coordinates and angles within `tolerance`. Face orders compare as sets; `file_creator` is
332/// ignored.
333public func structurallyEqual(_ a: FoldFile, _ b: FoldFile, tolerance: Double) -> Bool {
334 guard a.fileSpec == b.fileSpec, a.fileTitle == b.fileTitle, a.fileAuthor == b.fileAuthor,
335 a.fileClasses == b.fileClasses, a.edgesVertices == b.edgesVertices,
336 a.facesVertices == b.facesVertices, a.edgesFirstCreasedAtStep == b.edgesFirstCreasedAtStep,
337 a.frames.count == b.frames.count else { return false }
338 return zip(a.frames, b.frames).allSatisfy { framesAgree($0, $1, tolerance) }
339}
340
341private func close(_ a: [Double], _ b: [Double], _ tolerance: Double) -> Bool {
342 a.count == b.count && zip(a, b).allSatisfy { abs($0 - $1) <= tolerance }
343}
344
345private func close(_ a: Double?, _ b: Double?, _ tolerance: Double) -> Bool {
346 switch (a, b) {
347 case (nil, nil): true
348 case let (x?, y?): abs(x - y) <= tolerance
349 default: false
350 }
351}
352
353private func framesAgree(_ a: FoldFrame, _ b: FoldFrame, _ tolerance: Double) -> Bool {
354 let flatten = { (points: [SIMD3<Double>]) in points.flatMap { [$0.x, $0.y, $0.z] } }
355 let orders = { (list: [[Int]]?) in list.map(Set.init) }
356 guard close(flatten(a.verticesCoords), flatten(b.verticesCoords), tolerance),
357 a.edgesAssignment == b.edgesAssignment,
358 close(a.edgesFoldAngle, b.edgesFoldAngle, tolerance),
359 a.faceOrders.count == b.faceOrders.count, Set(a.faceOrders) == Set(b.faceOrders),
360 orders(a.faceOrdersMidFold) == orders(b.faceOrdersMidFold) else { return false }
361 switch (a.step, b.step) {
362 case (nil, nil): return true
363 case let (x?, y?): return stepsAgree(x, y, tolerance)
364 default: return false
365 }
366}
367
368private func stepsAgree(_ a: StepRecord, _ b: StepRecord, _ tolerance: Double) -> Bool {
369 let view = { (v: Viewpoint) in [v.eye.x, v.eye.y, v.eye.z, v.up.x, v.up.y, v.up.z] }
370 guard a.kind == b.kind, a.technique == b.technique, a.instruction == b.instruction,
371 close(a.rotateDegrees, b.rotateDegrees, tolerance), a.turnOverAxis == b.turnOverAxis,
372 a.repeatOf == b.repeatOf, a.nonRigid == b.nonRigid, a.pop == b.pop,
373 close(view(a.viewpoint), view(b.viewpoint), tolerance),
374 a.axes.count == b.axes.count else { return false }
375 return zip(a.axes, b.axes).allSatisfy { x, y in
376 x.edge == y.edge && Set(x.movingFaces) == Set(y.movingFaces) && x.parent == y.parent
377 && close(x.startAngle, y.startAngle, tolerance) && close(x.endAngle, y.endAngle, tolerance)
378 && close(x.peakAngle, y.peakAngle, tolerance)
379 && close(x.window ?? [0, 1], y.window ?? [0, 1], tolerance)
380 && (x.angles == nil) == (y.angles == nil) && close(x.angles ?? [], y.angles ?? [], tolerance)
381 }
382}
Packages/FoldKit/Sources/foldc/main.swift added +28
@@ -0,0 +1,28 @@
1import FoldCompiler
2import FoldFormat
3import Foundation
4
5// foldc <script.foldscript> -o <model.fold>
6
7func fail(_ message: String, status: Int32) -> Never {
8 FileHandle.standardError.write(Data("foldc: \(message)\n".utf8))
9 exit(status)
10}
11
12let arguments = Array(CommandLine.arguments.dropFirst())
13guard arguments.count == 3, arguments[1] == "-o" else {
14 fail("usage: foldc <script.foldscript> -o <model.fold>", status: 2)
15}
16let scriptURL = URL(fileURLWithPath: arguments[0])
17let outputURL = URL(fileURLWithPath: arguments[2])
18
19do {
20 let script = try FoldScript(contentsOf: scriptURL)
21 let patternURL = URL(fileURLWithPath: script.creasePattern, relativeTo: scriptURL.deletingLastPathComponent())
22 let model = try compile(script, pattern: FoldFile(contentsOf: patternURL))
23 let encoder = JSONEncoder()
24 encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
25 try encoder.encode(model).write(to: outputURL)
26} catch {
27 fail("\(error)", status: 1)
28}
Packages/FoldKit/Tests/FoldCompilerTests/CompilerTests.swift added +170
@@ -0,0 +1,170 @@
1import Foundation
2import Testing
3import FoldCompiler
4import FoldFormat
5import Folding
6import FoldKitTestSupport
7
8@Test(arguments: ["half", "mountain", "letter", "letter-sequential", "letter-staggered", "quarters", "occlusion"])
9func compilingASyntheticScriptReproducesItsHandWrittenFixture(_ name: String) throws {
10 let out = try compile(FoldScript(contentsOf: fixture("\(name).foldscript")),
11 pattern: FoldFile(contentsOf: fixture("\(name)-cp.fold")))
12 #expect(structurallyEqual(out, try FoldFile(contentsOf: fixture("\(name).fold")), tolerance: 1e-12))
13 #expect(validate(out).isEmpty)
14}
15
16@Test func aCreaseThroughTwoLayersChangesBothEdges() throws {
17 let out = try compiled("quarters")
18 #expect(out.frames[3].edgesFoldAngle[8] == 180)
19 #expect(out.frames[3].edgesFoldAngle[9] == -180)
20 #expect(out.frames[3].edgesAssignment[9] == .mountain)
21}
22
23@Test func firstCreasedAtStepIsTheFirstStepThatMakesTheCrease() throws {
24 // x = 1 is made by the fold-and-unfold in step 1 and refolded in step 3
25 #expect(try compiled("quarters").edgesFirstCreasedAtStep
26 == [nil, nil, nil, nil, nil, nil, nil, nil, 1, 1, 2, 2])
27}
28
29@Test func movingSideIsResolvedFromAContainedPoint() throws {
30 #expect(try compiled("half").frames[1].step?.axes[0].movingFaces == [1])
31}
32
33@Test func creaseGivenByEndpointsResolvesToAnEdgeIndex() throws {
34 #expect(try compiled("half").frames[1].step?.axes[0].edge == 6)
35}
36
37@Test func anOverrideReplacesTheGuessForThatPair() throws {
38 let file = try FoldFile(contentsOf: fixture("letter-sequential.fold"))
39 let frame = file.frames[2]
40 // the guess puts f2 (folded last) above f0; the override puts f0 above f2
41 let swapped = try applyOrderOverrides([OrderOverride(above: SIMD2(0.5, 1.5), below: SIMD2(2.5, 1.5))],
42 to: frame.faceOrders, frame: frame,
43 viewpoint: frame.step!.viewpoint, file: file)
44 #expect(swapped != frame.faceOrders)
45 #expect(throws: Never.self) { try LayerOrder(faceOrders: swapped, normals: faceNormals(frame, file)) }
46}
47
48@Test func aCoupledStepIsSolvedIntoCurves() throws {
49 // decision 0001's case 3 as a script: the 140° crease drives, the 260° crease
50 // gets a curve, the 0° crease rides on it, the 60° crease closes the loop
51 let out = try compile(degreeFourScript(), pattern: degreeFourPattern())
52 let axes = try #require(out.frames[1].step?.axes)
53 #expect(axes.contains { $0.angles != nil })
54 #expect(axes.contains { $0.parent != nil })
55 for axis in axes where axis.angles != nil {
56 #expect(abs(axis.angles![128] - degreeFourExactAngle(axis.edge, at: 0.5)) < 1e-6)
57 }
58}
59
60@Test func anUnresolvedCreaseNamesItsStep() {
61 #expect(throws: CompileError.unresolvedCrease(step: 2)) {
62 try compile(FoldScript(contentsOf: fixture("unresolved-crease.foldscript")),
63 pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
64 }
65}
66
67@Test func aStepThatFailsValidationNamesItsStep() {
68 #expect {
69 try compile(FoldScript(contentsOf: fixture("angle-out-of-range.foldscript")),
70 pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
71 } throws: { if case CompileError.stepFailed(step: 2, _) = $0 { true } else { false } }
72}
73
74@Test func guessedFaceOrdersAreAcyclic() throws {
75 let out = try compiled("occlusion")
76 for frame in out.frames { #expect(throws: Never.self) {
77 try LayerOrder(faceOrders: frame.faceOrders, normals: faceNormals(frame, out)) } }
78}
79
80@Test func aClockwiseFaceIsRejected() throws {
81 var pattern = try FoldFile(contentsOf: fixture("half-cp.fold"))
82 pattern.facesVertices[1].reverse()
83 #expect(throws: CompileError.clockwiseFace(face: 1)) {
84 try compile(FoldScript(contentsOf: fixture("half.foldscript")), pattern: pattern)
85 }
86}
87
88@Test func aCoupledStepReproducesTheClosedForm() throws {
89 #expect(structurallyEqual(try compile(degreeFourScript(), pattern: degreeFourPattern()), degreeFourVertex(),
90 tolerance: 1e-9))
91}
92
93private func halfFold(angles: [Double]? = nil, peakAngles: [Double]? = nil, kind: StepKind = .fold,
94 movingSide: SIMD2<Double> = SIMD2(1.5, 1), faceOrders: [OrderOverride]? = nil,
95 spine: CreaseRef? = nil) -> FoldScript {
96 FoldScript(creasePattern: "half-cp.fold", title: "Half", steps: [
97 ScriptStep(kind: kind, instruction: "Fold the right half.", creases: [.betweenVertices(SIMD2(1, 0), SIMD2(1, 2))],
98 movingSide: [movingSide], angles: angles, peakAngles: peakAngles, faceOrders: faceOrders,
99 spine: spine),
100 ])
101}
102
103@Test func aCreaseFoldedAgainstThePatternIsRejected() throws {
104 #expect(throws: CompileError.assignmentDisagreesWithPattern(edge: 6)) {
105 try compile(halfFold(angles: [-180]), pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
106 }
107}
108
109@Test func aMovingSideOffTheSheetIsRejected() throws {
110 #expect(throws: CompileError.unresolvedMovingSide(step: 1)) {
111 try compile(halfFold(movingSide: SIMD2(5, 5)), pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
112 }
113}
114
115@Test func anOverrideOffTheSheetNamesItsStep() throws {
116 let override = OrderOverride(above: SIMD2(0.5, 1), below: SIMD2(5, 5))
117 #expect(throws: CompileError.unresolvedFace(step: 1, point: SIMD2(5, 5))) {
118 try compile(halfFold(faceOrders: [override]), pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
119 }
120}
121
122@Test func anUnassignedCreaseNeedsAnAngle() throws {
123 var pattern = try FoldFile(contentsOf: fixture("half-cp.fold"))
124 pattern.frames[0].edgesAssignment[6] = .flat
125 #expect(throws: CompileError.missingAngle(step: 1)) {
126 try compile(halfFold(kind: .foldAndUnfold), pattern: pattern)
127 }
128}
129
130@Test func anglesPairWithCreases() throws {
131 #expect(throws: CompileError.creaseListMismatch(step: 1)) {
132 try compile(halfFold(angles: [180, 180]), pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
133 }
134}
135
136@Test func aStepNamingASpineIsLeftToTheNonRigidPath() throws {
137 #expect(throws: CompileError.nonRigidStepNotSupported(step: 1)) {
138 try compile(halfFold(spine: .edgeIndex(6)), pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
139 }
140}
141
142@Test func aLoopCreaseScriptedAtTheWrongAngleHasNoRigidMotion() throws {
143 let step = degreeFourScript().steps[0]
144 let script = FoldScript(creasePattern: "", title: "Degree-4 vertex", steps: [
145 ScriptStep(kind: .fold, instruction: step.instruction, creases: step.creases, movingSide: step.movingSide,
146 angles: [180, 180, 180, 180]),
147 ])
148 #expect(throws: CompileError.noRigidMotion(step: 1)) { try compile(script, pattern: degreeFourPattern()) }
149}
150
151@Test func twoFlapsFoldedIntoEachOtherAreRejected() throws {
152 let script = FoldScript(creasePattern: "letter-sequential-cp.fold", title: "Letter", steps: [
153 ScriptStep(kind: .fold, instruction: "Valley fold both thirds over at once.",
154 creases: [.betweenVertices(SIMD2(1, 0), SIMD2(1, 3)), .betweenVertices(SIMD2(2, 0), SIMD2(2, 3))],
155 movingSide: [SIMD2(0.5, 1.5), SIMD2(2.5, 1.5)]),
156 ])
157 #expect {
158 try compile(script, pattern: FoldFile(contentsOf: fixture("letter-sequential-cp.fold")))
159 } throws: { if case CompileError.interpenetration(step: 1, _) = $0 { true } else { false } }
160}
161
162@Test func aCreaseNamedTwiceIsUnresolved() throws {
163 let script = FoldScript(creasePattern: "half-cp.fold", title: "Half", steps: [
164 ScriptStep(kind: .fold, instruction: "Fold the right half.", creases: [.edgeIndex(6), .edgeIndex(6)],
165 movingSide: [SIMD2(1.5, 1)]),
166 ])
167 #expect(throws: CompileError.unresolvedCrease(step: 1)) {
168 try compile(script, pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
169 }
170}