Commit 5e0fe5ad34

5e0fe5ad34be52c2a98fc423377f7e7a5ed75922

parent: 0ce8c8b65a

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-20 03:45 UTC

foldc: coincident-axis guard, per-step layer motion, crease errors

Reject an edge on a named crease's line that becomes its own axis under a
scripted angle other than ±180. Run layerMotionDefects per step and throw
on any defect. unresolvedCrease and missingAngle carry the crease
reference; noCreases and invalidSpine are their own cases. Break arrival
ties by axis index in the guess and the arrival check. structurallyEqual
compares pops within the tolerance. Correct the PopCompiler, LayerMotion
and Helpers comments.

Ref #4

Layout: unified · split

Packages/FoldKit/Sources/FoldCompiler/FrameCompiler.swift +33 −19
@@ -3,9 +3,12 @@ import Folding
33import simd
44
55public 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)
6 /// A crease, driver or spine names no edge or a boundary edge, a crease names an edge already
7 /// named in the step, or the driver is not one of the step's creases. `crease` is the
8 /// reference as the script gives it.
9 case unresolvedCrease(step: Int, crease: CreaseRef)
10 /// A fold or fold-and-unfold step names no crease.
11 case noCreases(step: Int)
912 /// A `movingSide` point lies on no face, every region has one, or a crease does not separate
1013 /// a moving region from the rest.
1114 case unresolvedMovingSide(step: Int)
@@ -21,8 +24,9 @@ public enum CompileError: Error, Equatable, Sendable {
2124 case curveTooCoarse(step: Int)
2225 /// A face of the crease pattern is clockwise seen from +z.
2326 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)
27 /// `crease`, or an edge on its line, has no angle in the script and is neither `V` nor `M` in
28 /// the crease pattern.
29 case missingAngle(step: Int, crease: CreaseRef)
2630 /// `angles`, `peakAngles` or `windows` does not have one entry per crease.
2731 case creaseListMismatch(step: Int)
2832 /// An axis the step solves to close a loop has a scripted window other than the driver's.
@@ -31,6 +35,11 @@ public enum CompileError: Error, Equatable, Sendable {
3135 case popTooStrained(step: Int, strain: Double)
3236 /// A reverse fold or sink names no `spine` to open on.
3337 case missingSpine(step: Int)
38 /// A `spine` is given on a step that is not a fold, or is not folded flat in frame n − 1.
39 case invalidSpine(step: Int)
40 /// An edge on a named crease's line, in another layer, becomes an axis of its own while the
41 /// named crease's scripted angle is not ±180; its angle is not derived.
42 case coincidentAxisAngle(step: Int, edge: Int)
3443}
3544
3645/// Samples in a solved curve, evenly spaced over its window.
@@ -50,9 +59,9 @@ private let interpenetrationSamples = 64
5059///
5160/// Frame 0 is the pattern with every crease reset to `F` and 0. Each step is planned from the
5261/// script, its end frame produced by `FoldInterpolator.positions(at: 1)`, its layer order guessed
53/// and overridden, and the file so far validated and checked for interpenetration. A step that
54/// names a `spine` is a reverse fold or sink and moves by `compilePop`'s open, pop and close. The
55/// whole file is then checked with `layerMotionDefects`; a defect fails the step it names.
62/// and overridden, and the file so far validated and checked with `layerMotionDefects` and for
63/// interpenetration. A step that names a `spine` is a reverse fold or sink and moves by
64/// `compilePop`'s open, pop and close.
5665public func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile {
5766 let flat = pattern.frames[0]
5867 for (f, normal) in faceNormals(flat, pattern).enumerated() where normal.z < 0 {
@@ -74,10 +83,6 @@ public func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile
7483 viewpoint = step.viewpoint ?? viewpoint
7584 try appendStep(i + 1, step, viewpoint: viewpoint, to: &file, finalAssignment: finalAssignment)
7685 }
77 let motion = layerMotionDefects(file)
78 if case .movesThroughStillFace(let n, _, _)? = motion.first {
79 throw CompileError.stepFailed(step: n, defects: motion)
80 }
8186
8287 let last = file.frames[file.frames.count - 1]
8388 for e in file.edgesVertices.indices
@@ -94,7 +99,7 @@ private func appendStep(_ n: Int, _ script: ScriptStep, viewpoint: Viewpoint, to
9499 if script.spine == nil && [.insideReverse, .outsideReverse, .sink].contains(technique) {
95100 throw CompileError.missingSpine(step: n)
96101 }
97 if script.spine != nil && script.kind != .fold { throw CompileError.unresolvedCrease(step: n) }
102 if script.spine != nil && script.kind != .fold { throw CompileError.invalidSpine(step: n) }
98103 let previous = file.frames[n - 1]
99104
100105 var plan: FoldPlan?
@@ -176,6 +181,8 @@ private func appendStep(_ n: Int, _ script: ScriptStep, viewpoint: Viewpoint, to
176181
177182 let defects = validate(file)
178183 guard defects.isEmpty else { throw CompileError.stepFailed(step: n, defects: defects) }
184 let motion = layerMotionDefects(step: n, in: file)
185 guard motion.isEmpty else { throw CompileError.stepFailed(step: n, defects: motion) }
179186 let collisions = step.nonRigid
180187 ? meshInterpenetrations(interpolator, samples: interpenetrationSamples)
181188 : interpenetrations(interpolator, faces: file.facesVertices, samples: interpenetrationSamples)
@@ -211,7 +218,8 @@ private struct FoldPlan {
211218///
212219/// Every edge that lies on a named crease's line in the start frame is cut too, so a crease
213220/// through several layers folds each of them; one whose faces end up in the same region is not
214/// creased.
221/// creased. One that becomes an axis of its own takes ±180 by the pattern's assignment, so its
222/// named crease must be scripted at ±180 or not at all.
215223private func planFolds(_ n: Int, _ script: ScriptStep, _ file: FoldFile,
216224 _ finalAssignment: [EdgeAssignment]) throws -> FoldPlan {
217225 let start = file.frames[n - 1]
@@ -221,15 +229,18 @@ private func planFolds(_ n: Int, _ script: ScriptStep, _ file: FoldFile,
221229 throw CompileError.creaseListMismatch(step: n)
222230 }
223231
232 guard count > 0 else { throw CompileError.noCreases(step: n) }
224233 let named = try script.creases.map { ref in
225 guard let e = resolve(ref, file, edgeFaces) else { throw CompileError.unresolvedCrease(step: n) }
234 guard let e = resolve(ref, file, edgeFaces) else { throw CompileError.unresolvedCrease(step: n, crease: ref) }
226235 return e
227236 }
228 guard !named.isEmpty, Set(named).count == named.count else { throw CompileError.unresolvedCrease(step: n) }
237 if let repeated = named.indices.first(where: { named[..<$0].contains(named[$0]) }) {
238 throw CompileError.unresolvedCrease(step: n, crease: script.creases[repeated])
239 }
229240 var driver = 0
230241 if let ref = script.driver {
231242 guard let e = resolve(ref, file, edgeFaces), let i = named.firstIndex(of: e) else {
232 throw CompileError.unresolvedCrease(step: n)
243 throw CompileError.unresolvedCrease(step: n, crease: ref)
233244 }
234245 driver = i
235246 }
@@ -328,11 +339,14 @@ private func planFolds(_ n: Int, _ script: ScriptStep, _ file: FoldFile,
328339 let window = script.windows?[t.source]
329340 let written = window == [0, 1] ? nil : window
330341 func endAngle(_ list: [Double]?) throws -> Double {
331 if isNamed, let list { return list[t.source] }
342 if let list {
343 if isNamed { return list[t.source] }
344 if abs(list[t.source]) != 180 { throw CompileError.coincidentAxisAngle(step: n, edge: t.edge) }
345 }
332346 switch finalAssignment[t.edge] {
333347 case .valley: return 180
334348 case .mountain: return -180
335 default: throw CompileError.missingAngle(step: n)
349 default: throw CompileError.missingAngle(step: n, crease: script.creases[t.source])
336350 }
337351 }
338352 if script.kind == .foldAndUnfold {
Packages/FoldKit/Sources/FoldCompiler/LayerOrderGuess.swift +6 −5
@@ -13,10 +13,10 @@ private let separationTolerance = 1e-9
1313///
1414/// Faces that move together, or both stay still, keep frame n − 1's relation. Otherwise the face
1515/// 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.
16/// last axis that moves them differently finishes, the higher-indexed of axes that finish
17/// together, at the paper points that meet in the middle of their overlap. A moving set that has
18/// turned over arrives with its layers reversed. This is right for plain valley and mountain
19/// folds and wrong for a flap tucked between layers, which the script corrects with overrides.
2020///
2121/// - Precondition: `step` is one `readStep` accepts with `previous` as its start frame.
2222public func guessFaceOrders(previous: FoldFrame, next: FoldFrame, step: StepRecord, file: FoldFile) -> [[Int]] {
@@ -60,7 +60,8 @@ func guessOrders(previous: FoldFrame, step: FoldStep, interpolator: FoldInterpol
6060 var orders: [[Int]] = []
6161 for (a, b) in overlappingPairs(positions, faces, normals, tolerance: size * relativeTolerance) {
6262 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 {
63 let last = differing.max { (arrival(step.axes[$0].window), $0) < (arrival(step.axes[$1].window), $1) }
64 guard let last else {
6465 if let s = before[SIMD2(a, b)] { orders.append([a, b, s]) }
6566 continue
6667 }
Packages/FoldKit/Sources/FoldCompiler/PopCompiler.swift +13 −9
@@ -27,14 +27,16 @@ private let angleSamples = 256
2727/// rigid step, and must arrive at `after`'s coordinates.
2828///
2929/// The starting guess can lead the solver to another branch of the vertex's motion. Closing the
30/// loops does not catch that: every branch is closed. The check that the close reaches `after`
31/// catches a branch that ends elsewhere; one that ends on the same coordinates with the tip
32/// outside is caught by the validator's layer-order rules on frame n, and in general by the rule
33/// on the side a moving face departs toward and arrives from.
30/// loops does not catch that: every branch is closed. A branch is caught when the close does not
31/// reach `after`'s coordinates, when it leaves a crease of the last frame assigned against the
32/// crease pattern, or when frame n breaks the validator's layer-order rules; the reverse fixture's
33/// test that the tip lands between the flap's layers covers that fixture. `layerMotionDefects`
34/// does not add a check here: frame n's orders for the faces the step's axes move are guessed
35/// from the same close, read near the same moment.
3436///
35/// - Throws: `unresolvedCrease` when the spine names no edge or is not folded flat,
36/// `noRigidMotion` when the flap cannot open on its spine, `popped` does not close or the close
37/// does not reach `after`, and `popTooStrained` when the pop's strain exceeds 10%.
37/// - Throws: `unresolvedCrease` when the spine names no edge, `invalidSpine` when it is not
38/// folded flat, `noRigidMotion` when the flap cannot open on its spine, `popped` does not close
39/// or the close does not reach `after`, and `popTooStrained` when the pop's strain exceeds 10%.
3840public func compilePop(step n: Int, script: ScriptStep, before: FoldFrame, after: FoldFrame,
3941 file: FoldFile) throws -> PopRecord {
4042 guard let reference = script.spine, let record = after.step else {
@@ -45,14 +47,16 @@ public func compilePop(step n: Int, script: ScriptStep, before: FoldFrame, after
4547 let tolerance = sheetExtent(file) * relativeTolerance
4648 let openAngle = script.openAngle ?? defaultOpenAngle
4749
48 guard let named = resolve(reference, file, edgeFaces) else { throw CompileError.unresolvedCrease(step: n) }
50 guard let named = resolve(reference, file, edgeFaces) else {
51 throw CompileError.unresolvedCrease(step: n, crease: reference)
52 }
4953 let ends = file.edgesVertices[named].map { before.verticesCoords[$0] }
5054 let spine = [named] + edgeFaces.indices.filter { e in
5155 e != named && edgeFaces[e].count == 2
5256 && file.edgesVertices[e].allSatisfy { onLine(before.verticesCoords[$0], ends[0], ends[1], tolerance) }
5357 }
5458 guard spine.allSatisfy({ abs(abs(before.edgesFoldAngle[$0]) - 180) <= angleSnapTolerance }) else {
55 throw CompileError.unresolvedCrease(step: n)
59 throw CompileError.invalidSpine(step: n)
5660 }
5761
5862 var group = Array(repeating: -1, count: faceCount)
Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift +23 −7
@@ -328,8 +328,8 @@ public func compiled(_ name: String) throws -> FoldFile {
328328}
329329
330330/// 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.
331/// coordinates, angles and pop phases within `tolerance`. Face orders compare as sets;
332/// `file_creator` is ignored.
333333public func structurallyEqual(_ a: FoldFile, _ b: FoldFile, tolerance: Double) -> Bool {
334334 guard a.fileSpec == b.fileSpec, a.fileTitle == b.fileTitle, a.fileAuthor == b.fileAuthor,
335335 a.fileClasses == b.fileClasses, a.edgesVertices == b.edgesVertices,
@@ -369,10 +369,25 @@ private func stepsAgree(_ a: StepRecord, _ b: StepRecord, _ tolerance: Double) -
369369 let view = { (v: Viewpoint) in [v.eye.x, v.eye.y, v.eye.z, v.up.x, v.up.y, v.up.z] }
370370 guard a.kind == b.kind, a.technique == b.technique, a.instruction == b.instruction,
371371 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
372 a.repeatOf == b.repeatOf, a.nonRigid == b.nonRigid,
373 close(view(a.viewpoint), view(b.viewpoint), tolerance) else { return false }
374 switch (a.pop, b.pop) {
375 case (nil, nil): break
376 case let (x?, y?): guard popsAgree(x, y, tolerance) else { return false }
377 default: return false
378 }
379 return axesAgree(a.axes, b.axes, tolerance)
380}
381
382private func popsAgree(_ a: PopRecord, _ b: PopRecord, _ tolerance: Double) -> Bool {
383 let flatten = { (points: [SIMD3<Double>]) in points.flatMap { [$0.x, $0.y, $0.z] } }
384 return a.spine == b.spine && close(a.openAngle, b.openAngle, tolerance) && close(a.phases, b.phases, tolerance)
385 && close(flatten(a.popped), flatten(b.popped), tolerance)
386 && axesAgree(a.openAxes, b.openAxes, tolerance) && axesAgree(a.closeAxes, b.closeAxes, tolerance)
387}
388
389private func axesAgree(_ a: [AxisRecord], _ b: [AxisRecord], _ tolerance: Double) -> Bool {
390 a.count == b.count && zip(a, b).allSatisfy { x, y in
376391 x.edge == y.edge && Set(x.movingFaces) == Set(y.movingFaces) && x.parent == y.parent
377392 && close(x.startAngle, y.startAngle, tolerance) && close(x.endAngle, y.endAngle, tolerance)
378393 && close(x.peakAngle, y.peakAngle, tolerance)
@@ -453,7 +468,8 @@ private func replacing(_ s: ScriptStep, spine: CreaseRef?, openAngle: Double?) -
453468 openAngle: openAngle)
454469}
455470
456/// The repository's `Models/` directory, four levels above this package's `Sources/`.
471/// The repository's `Models/` directory: this file's path with its last five components, up to
472/// and including `Packages`, replaced by `Models`.
457473private let modelsDirectory = URL(fileURLWithPath: #filePath)
458474 .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
459475 .deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Models")
Packages/FoldKit/Sources/Folding/LayerMotion.swift +27 −20
@@ -25,27 +25,35 @@ private let separationTolerance = 1e-9
2525/// A non-rigid step's departures are read on its open axes and its arrivals on its close axes; the
2626/// pop between is not. Turn-over and rotate steps move every face together and have no still face.
2727///
28/// Arrivals are read on the last axis to finish, the higher-indexed of axes that finish together,
29/// at the moment the compiler's layer-order guess reads them. In a rigid step the guess places
30/// the arriving face on the side it arrives from, so in a compiled file an arrival disagrees with
31/// frame n's orders only where the script overrides them.
32///
2833/// - Precondition: `validate(file)` is empty. Steps `readStep` rejects are skipped.
2934public func layerMotionDefects(_ file: FoldFile) -> [FoldDefect] {
35 file.frames.indices.dropFirst().flatMap { layerMotionDefects(step: $0, in: file) }
36}
37
38/// `layerMotionDefects(_:)` for step `n` alone. `file` needs frames 0…n.
39public func layerMotionDefects(step n: Int, in file: FoldFile) -> [FoldDefect] {
40 guard let step = try? readStep(n, in: file), step.kind == .fold || step.kind == .foldAndUnfold else {
41 return []
42 }
3043 let size = sheetExtent(file)
44 let pop = step.nonRigid ? step.pop : nil
45 let departing = pop?.openAxes ?? step.axes, arriving = pop?.closeAxes ?? step.axes
46 let moving = (step.axes + departing + arriving).reduce(into: Set<Int>()) { $0.formUnion($1.movingFaces) }
47 let interpolator = FoldInterpolator(file: file, step: step)
48 let check = { (frame: FoldFrame, axes: [FoldAxis], departure: Bool) in
49 crossings(frame, axes: axes, departure: departure, still: { !moving.contains($0) },
50 interpolator: interpolator, file: file, size: size)
51 }
3152 var defects: [FoldDefect] = []
32 for n in file.frames.indices.dropFirst() {
33 guard let step = try? readStep(n, in: file), step.kind == .fold || step.kind == .foldAndUnfold else {
34 continue
35 }
36 let pop = step.nonRigid ? step.pop : nil
37 let departing = pop?.openAxes ?? step.axes, arriving = pop?.closeAxes ?? step.axes
38 let moving = (step.axes + departing + arriving).reduce(into: Set<Int>()) { $0.formUnion($1.movingFaces) }
39 let interpolator = FoldInterpolator(file: file, step: step)
40 let check = { (frame: FoldFrame, axes: [FoldAxis], departure: Bool) in
41 crossings(frame, axes: axes, departure: departure, still: { !moving.contains($0) },
42 interpolator: interpolator, file: file, size: size)
43 }
44 var reported = Set<SIMD2<Int>>()
45 for (m, s) in check(file.frames[n - 1], departing, true) + check(file.frames[n], arriving, false)
46 where reported.insert(SIMD2(m, s)).inserted {
47 defects.append(.movesThroughStillFace(step: n, moving: m, still: s))
48 }
53 var reported = Set<SIMD2<Int>>()
54 for (m, s) in check(file.frames[n - 1], departing, true) + check(file.frames[n], arriving, false)
55 where reported.insert(SIMD2(m, s)).inserted {
56 defects.append(.movesThroughStillFace(step: n, moving: m, still: s))
4957 }
5058 return defects
5159}
@@ -72,13 +80,12 @@ private func crossings(_ frame: FoldFrame, axes: [FoldAxis], departure: Bool, st
7280 carriers.append(axis)
7381 a = axes[axis].parent
7482 }
75 let windows = carriers.map { axes[$0].window }
7683 let t: Double
7784 if departure {
78 let w = windows.min { $0.lowerBound < $1.lowerBound }!
85 let w = carriers.map { axes[$0].window }.min { $0.lowerBound < $1.lowerBound }!
7986 t = w.lowerBound + lead * (w.upperBound - w.lowerBound)
8087 } else {
81 let w = windows.max { $0.upperBound < $1.upperBound }!
88 let w = axes[carriers.max { (axes[$0].window.upperBound, $0) < (axes[$1].window.upperBound, $1) }!].window
8289 t = w.upperBound - lead * (w.upperBound - w.lowerBound)
8390 }
8491 let near = sampled[t] ?? interpolator.positions(at: t)
Packages/FoldKit/Tests/FoldCompilerTests/CompilerTests.swift +88 −5
@@ -57,8 +57,8 @@ func compilingASyntheticScriptReproducesItsHandWrittenFixture(_ name: String) th
5757 }
5858}
5959
60@Test func anUnresolvedCreaseNamesItsStep() {
61 #expect(throws: CompileError.unresolvedCrease(step: 2)) {
60@Test func anUnresolvedCreaseNamesItsStepAndReference() {
61 #expect(throws: CompileError.unresolvedCrease(step: 2, crease: .betweenVertices(SIMD2(0, 1), SIMD2(1, 1)))) {
6262 try compile(FoldScript(contentsOf: fixture("unresolved-crease.foldscript")),
6363 pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
6464 }
@@ -122,7 +122,7 @@ private func halfFold(angles: [Double]? = nil, peakAngles: [Double]? = nil, kind
122122@Test func anUnassignedCreaseNeedsAnAngle() throws {
123123 var pattern = try FoldFile(contentsOf: fixture("half-cp.fold"))
124124 pattern.frames[0].edgesAssignment[6] = .flat
125 #expect(throws: CompileError.missingAngle(step: 1)) {
125 #expect(throws: CompileError.missingAngle(step: 1, crease: .betweenVertices(SIMD2(1, 0), SIMD2(1, 2)))) {
126126 try compile(halfFold(kind: .foldAndUnfold), pattern: pattern)
127127 }
128128}
@@ -135,7 +135,7 @@ private func halfFold(angles: [Double]? = nil, peakAngles: [Double]? = nil, kind
135135
136136@Test func aSpineThatIsNotFoldedIsRejected() throws {
137137 // a flap opens on a spine folded flat in the frame the step starts from
138 #expect(throws: CompileError.unresolvedCrease(step: 1)) {
138 #expect(throws: CompileError.invalidSpine(step: 1)) {
139139 try compile(halfFold(spine: .edgeIndex(6)), pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
140140 }
141141}
@@ -165,7 +165,32 @@ private func halfFold(angles: [Double]? = nil, peakAngles: [Double]? = nil, kind
165165 ScriptStep(kind: .fold, instruction: "Fold the right half.", creases: [.edgeIndex(6), .edgeIndex(6)],
166166 movingSide: [SIMD2(1.5, 1)]),
167167 ])
168 #expect(throws: CompileError.unresolvedCrease(step: 1)) {
168 #expect(throws: CompileError.unresolvedCrease(step: 1, crease: .edgeIndex(6))) {
169 try compile(script, pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
170 }
171}
172
173@Test func aSpineOnAStepThatIsNotAFoldIsRejected() throws {
174 #expect(throws: CompileError.invalidSpine(step: 1)) {
175 try compile(halfFold(kind: .foldAndUnfold, spine: .edgeIndex(6)), pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
176 }
177}
178
179@Test func aDriverThatIsNotAStepCreaseIsUnresolved() throws {
180 let script = FoldScript(creasePattern: "half-cp.fold", title: "Half", steps: [
181 ScriptStep(kind: .fold, instruction: "Fold the right half.", creases: [.edgeIndex(6)],
182 movingSide: [SIMD2(1.5, 1)], driver: .edgeIndex(0)),
183 ])
184 #expect(throws: CompileError.unresolvedCrease(step: 1, crease: .edgeIndex(0))) {
185 try compile(script, pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
186 }
187}
188
189@Test func aFoldWithNoCreaseIsRejected() throws {
190 let script = FoldScript(creasePattern: "half-cp.fold", title: "Half", steps: [
191 ScriptStep(kind: .fold, instruction: "Fold the right half.", movingSide: [SIMD2(1.5, 1)]),
192 ])
193 #expect(throws: CompileError.noCreases(step: 1)) {
169194 try compile(script, pattern: FoldFile(contentsOf: fixture("half-cp.fold")))
170195 }
171196}
@@ -211,6 +236,48 @@ private func splitLetterPattern() -> FoldFile {
211236 }
212237}
213238
239/// A 4 × 1 strip with valley creases at x = 1 (e10) and x = 2 (e11) and a mountain at x = 3 (e12).
240/// Folded in half at x = 2, e12 lies on e10's line in a separate layer.
241private func stripPattern() -> FoldFile {
242 let points: [SIMD3<Double>] = [
243 SIMD3(0, 0, 0), SIMD3(1, 0, 0), SIMD3(2, 0, 0), SIMD3(3, 0, 0), SIMD3(4, 0, 0),
244 SIMD3(4, 1, 0), SIMD3(3, 1, 0), SIMD3(2, 1, 0), SIMD3(1, 1, 0), SIMD3(0, 1, 0),
245 ]
246 let assignment = Array(repeating: EdgeAssignment.boundary, count: 10) + [.valley, .valley, .mountain]
247 return FoldFile(fileSpec: 1.2, fileTitle: "Strip", fileAuthor: "Traditional", fileClasses: ["creasePattern"],
248 edgesVertices: (0..<10).map { [$0, ($0 + 1) % 10] } + [[1, 8], [2, 7], [3, 6]],
249 facesVertices: [[0, 1, 8, 9], [1, 2, 7, 8], [2, 3, 6, 7], [3, 4, 5, 6]],
250 edgesFirstCreasedAtStep: Array(repeating: nil, count: 13),
251 frames: [FoldFrame(verticesCoords: points, edgesAssignment: assignment,
252 edgesFoldAngle: Array(repeating: 0, count: 13), faceOrders: [])])
253}
254
255@Test func aCoincidentAxisUnderAScriptedAngleIsRejected() throws {
256 // step 2's crease at x = 1 cuts both layers; the upper layer's edge, e12, is an axis of its own
257 let script = FoldScript(creasePattern: "", title: "Strip", steps: [
258 ScriptStep(kind: .fold, instruction: "Valley fold in half.", creases: [.betweenVertices(SIMD2(2, 0), SIMD2(2, 1))],
259 movingSide: [SIMD2(3, 0.5)]),
260 ScriptStep(kind: .fold, instruction: "Fold the end up to stand.",
261 creases: [.betweenVertices(SIMD2(1, 0), SIMD2(1, 1))],
262 movingSide: [SIMD2(0.5, 0.5), SIMD2(3.5, 0.5)], angles: [90]),
263 ])
264 #expect(throws: CompileError.coincidentAxisAngle(step: 2, edge: 12)) {
265 try compile(script, pattern: stripPattern())
266 }
267}
268
269@Test func aCoincidentAxisFoldedFlatCompiles() throws {
270 let script = FoldScript(creasePattern: "", title: "Strip", steps: [
271 ScriptStep(kind: .fold, instruction: "Valley fold in half.", creases: [.betweenVertices(SIMD2(2, 0), SIMD2(2, 1))],
272 movingSide: [SIMD2(3, 0.5)]),
273 ScriptStep(kind: .fold, instruction: "Fold the end over.", creases: [.betweenVertices(SIMD2(1, 0), SIMD2(1, 1))],
274 movingSide: [SIMD2(0.5, 0.5), SIMD2(3.5, 0.5)], angles: [180]),
275 ])
276 let out = try compile(script, pattern: stripPattern())
277 #expect(out.frames[2].edgesFoldAngle[10] == 180)
278 #expect(out.frames[2].edgesFoldAngle[12] == -180)
279}
280
214281@Test func anOverrideThatPutsAFlapUnderTheLayerItArrivesOnIsRejected() throws {
215282 // step 2's flap folds over the top, so it cannot end under f0
216283 var script = try FoldScript(contentsOf: fixture("letter-sequential.foldscript"))
@@ -225,3 +292,19 @@ private func splitLetterPattern() -> FoldFile {
225292 try compile(script, pattern: FoldFile(contentsOf: fixture("letter-sequential-cp.fold")))
226293 }
227294}
295
296@Test func aFlapThroughAStillFaceFailsItsStepBeforeLaterSteps() throws {
297 // step 2 moves through a still face; step 3 has no moving side on the sheet
298 let script = try FoldScript(contentsOf: fixture("letter-sequential.foldscript"))
299 let (first, second) = (script.steps[0], script.steps[1])
300 let failing = FoldScript(creasePattern: script.creasePattern, title: script.title, steps: [
301 first,
302 ScriptStep(kind: second.kind, instruction: second.instruction, creases: second.creases,
303 movingSide: second.movingSide, repeatOf: second.repeatOf,
304 faceOrders: [OrderOverride(above: SIMD2(0.5, 1.5), below: SIMD2(2.5, 1.5))]),
305 ScriptStep(kind: .fold, instruction: "Fold off the sheet.", creases: first.creases, movingSide: [SIMD2(5, 5)]),
306 ])
307 #expect(throws: CompileError.stepFailed(step: 2, defects: [.movesThroughStillFace(step: 2, moving: 2, still: 0)])) {
308 try compile(failing, pattern: FoldFile(contentsOf: fixture("letter-sequential-cp.fold")))
309 }
310}
Packages/FoldKit/Tests/FoldCompilerTests/NonRigidTests.swift +20
@@ -97,3 +97,23 @@ import FoldKitTestSupport
9797 // the open phase departs from frame 1 and the close phase arrives at frame 2
9898 #expect(layerMotionDefects(try compiled("reverse")).isEmpty)
9999}
100
101@Test func popsCompareWithinTheTolerance() throws {
102 let file = try compiled("reverse")
103 func nudged(by d: Double) -> FoldFile {
104 let record = file.frames[2].step!, p = record.pop!
105 let close = p.closeAxes.map {
106 AxisRecord(edge: $0.edge, movingFaces: $0.movingFaces, startAngle: $0.startAngle + d, endAngle: $0.endAngle,
107 peakAngle: $0.peakAngle, parent: $0.parent, window: $0.window, angles: $0.angles?.map { $0 + d })
108 }
109 let pop = PopRecord(spine: p.spine, openAngle: p.openAngle + d, phases: p.phases.map { $0 + d },
110 openAxes: p.openAxes, popped: p.popped.map { $0 + d }, closeAxes: close)
111 var copy = file
112 copy.frames[2].step = StepRecord(kind: record.kind, technique: record.technique, instruction: record.instruction,
113 axes: record.axes, nonRigid: record.nonRigid, pop: pop,
114 viewpoint: record.viewpoint)
115 return copy
116 }
117 #expect(structurallyEqual(nudged(by: 1e-13), file, tolerance: 1e-12))
118 #expect(!structurallyEqual(nudged(by: 1e-9), file, tolerance: 1e-12))
119}
Packages/FoldKit/Tests/FoldingTests/LayerMotionTests.swift +9
@@ -12,6 +12,15 @@ import FoldKitTestSupport
1212 #expect(layerMotionDefects(file) == [.movesThroughStillFace(step: 2, moving: 2, still: 0)])
1313}
1414
15@Test func oneStepIsCheckedOnTheFramesUpToIt() throws {
16 var file = try FoldFile(contentsOf: fixture("letter-sequential.fold"))
17 file.frames[2].faceOrders = [[0, 1, 1], [0, 2, -1], [1, 2, 1]]
18 var head = file
19 head.frames.removeLast()
20 #expect(layerMotionDefects(step: 1, in: head).isEmpty)
21 #expect(layerMotionDefects(step: 2, in: file) == [.movesThroughStillFace(step: 2, moving: 2, still: 0)])
22}
23
1524@Test func aFlapDepartingTowardALayerAboveItIsFlagged() throws {
1625 // step 3 unfolds f0 from under f2, which covers f0's hinge at x = 1
1726 var file = try FoldFile(contentsOf: fixture("letter-sequential.fold"))