Commit 5e0fe5ad34
Verified · cmc
Layout: unified · split
Packages/FoldKit/Sources/FoldCompiler/FrameCompiler.swift +33 −19
| @@ -3,9 +3,12 @@ import Folding | ||
| 3 | 3 | import simd |
| 4 | 4 | |
| 5 | 5 | public 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) | |
| 9 | 12 | /// A `movingSide` point lies on no face, every region has one, or a crease does not separate |
| 10 | 13 | /// a moving region from the rest. |
| 11 | 14 | case unresolvedMovingSide(step: Int) |
| @@ -21,8 +24,9 @@ public enum CompileError: Error, Equatable, Sendable { | ||
| 21 | 24 | case curveTooCoarse(step: Int) |
| 22 | 25 | /// A face of the crease pattern is clockwise seen from +z. |
| 23 | 26 | 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) | |
| 26 | 30 | /// `angles`, `peakAngles` or `windows` does not have one entry per crease. |
| 27 | 31 | case creaseListMismatch(step: Int) |
| 28 | 32 | /// 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 { | ||
| 31 | 35 | case popTooStrained(step: Int, strain: Double) |
| 32 | 36 | /// A reverse fold or sink names no `spine` to open on. |
| 33 | 37 | 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) | |
| 34 | 43 | } |
| 35 | 44 | |
| 36 | 45 | /// Samples in a solved curve, evenly spaced over its window. |
| @@ -50,9 +59,9 @@ private let interpenetrationSamples = 64 | ||
| 50 | 59 | /// |
| 51 | 60 | /// Frame 0 is the pattern with every crease reset to `F` and 0. Each step is planned from the |
| 52 | 61 | /// 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. | |
| 56 | 65 | public func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile { |
| 57 | 66 | let flat = pattern.frames[0] |
| 58 | 67 | 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 | ||
| 74 | 83 | viewpoint = step.viewpoint ?? viewpoint |
| 75 | 84 | try appendStep(i + 1, step, viewpoint: viewpoint, to: &file, finalAssignment: finalAssignment) |
| 76 | 85 | } |
| 77 | let motion = layerMotionDefects(file) | |
| 78 | if case .movesThroughStillFace(let n, _, _)? = motion.first { | |
| 79 | throw CompileError.stepFailed(step: n, defects: motion) | |
| 80 | } | |
| 81 | 86 | |
| 82 | 87 | let last = file.frames[file.frames.count - 1] |
| 83 | 88 | for e in file.edgesVertices.indices |
| @@ -94,7 +99,7 @@ private func appendStep(_ n: Int, _ script: ScriptStep, viewpoint: Viewpoint, to | ||
| 94 | 99 | if script.spine == nil && [.insideReverse, .outsideReverse, .sink].contains(technique) { |
| 95 | 100 | throw CompileError.missingSpine(step: n) |
| 96 | 101 | } |
| 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) } | |
| 98 | 103 | let previous = file.frames[n - 1] |
| 99 | 104 | |
| 100 | 105 | var plan: FoldPlan? |
| @@ -176,6 +181,8 @@ private func appendStep(_ n: Int, _ script: ScriptStep, viewpoint: Viewpoint, to | ||
| 176 | 181 | |
| 177 | 182 | let defects = validate(file) |
| 178 | 183 | 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) } | |
| 179 | 186 | let collisions = step.nonRigid |
| 180 | 187 | ? meshInterpenetrations(interpolator, samples: interpenetrationSamples) |
| 181 | 188 | : interpenetrations(interpolator, faces: file.facesVertices, samples: interpenetrationSamples) |
| @@ -211,7 +218,8 @@ private struct FoldPlan { | ||
| 211 | 218 | /// |
| 212 | 219 | /// Every edge that lies on a named crease's line in the start frame is cut too, so a crease |
| 213 | 220 | /// 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. | |
| 215 | 223 | private func planFolds(_ n: Int, _ script: ScriptStep, _ file: FoldFile, |
| 216 | 224 | _ finalAssignment: [EdgeAssignment]) throws -> FoldPlan { |
| 217 | 225 | let start = file.frames[n - 1] |
| @@ -221,15 +229,18 @@ private func planFolds(_ n: Int, _ script: ScriptStep, _ file: FoldFile, | ||
| 221 | 229 | throw CompileError.creaseListMismatch(step: n) |
| 222 | 230 | } |
| 223 | 231 | |
| 232 | guard count > 0 else { throw CompileError.noCreases(step: n) } | |
| 224 | 233 | 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) } | |
| 226 | 235 | return e |
| 227 | 236 | } |
| 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 | } | |
| 229 | 240 | var driver = 0 |
| 230 | 241 | if let ref = script.driver { |
| 231 | 242 | 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) | |
| 233 | 244 | } |
| 234 | 245 | driver = i |
| 235 | 246 | } |
| @@ -328,11 +339,14 @@ private func planFolds(_ n: Int, _ script: ScriptStep, _ file: FoldFile, | ||
| 328 | 339 | let window = script.windows?[t.source] |
| 329 | 340 | let written = window == [0, 1] ? nil : window |
| 330 | 341 | 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 | } | |
| 332 | 346 | switch finalAssignment[t.edge] { |
| 333 | 347 | case .valley: return 180 |
| 334 | 348 | case .mountain: return -180 |
| 335 | default: throw CompileError.missingAngle(step: n) | |
| 349 | default: throw CompileError.missingAngle(step: n, crease: script.creases[t.source]) | |
| 336 | 350 | } |
| 337 | 351 | } |
| 338 | 352 | if script.kind == .foldAndUnfold { |
Packages/FoldKit/Sources/FoldCompiler/LayerOrderGuess.swift +6 −5
| @@ -13,10 +13,10 @@ private let separationTolerance = 1e-9 | ||
| 13 | 13 | /// |
| 14 | 14 | /// Faces that move together, or both stay still, keep frame n − 1's relation. Otherwise the face |
| 15 | 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. | |
| 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. | |
| 20 | 20 | /// |
| 21 | 21 | /// - Precondition: `step` is one `readStep` accepts with `previous` as its start frame. |
| 22 | 22 | public func guessFaceOrders(previous: FoldFrame, next: FoldFrame, step: StepRecord, file: FoldFile) -> [[Int]] { |
| @@ -60,7 +60,8 @@ func guessOrders(previous: FoldFrame, step: FoldStep, interpolator: FoldInterpol | ||
| 60 | 60 | var orders: [[Int]] = [] |
| 61 | 61 | for (a, b) in overlappingPairs(positions, faces, normals, tolerance: size * relativeTolerance) { |
| 62 | 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 { | |
| 63 | let last = differing.max { (arrival(step.axes[$0].window), $0) < (arrival(step.axes[$1].window), $1) } | |
| 64 | guard let last else { | |
| 64 | 65 | if let s = before[SIMD2(a, b)] { orders.append([a, b, s]) } |
| 65 | 66 | continue |
| 66 | 67 | } |
Packages/FoldKit/Sources/FoldCompiler/PopCompiler.swift +13 −9
| @@ -27,14 +27,16 @@ private let angleSamples = 256 | ||
| 27 | 27 | /// rigid step, and must arrive at `after`'s coordinates. |
| 28 | 28 | /// |
| 29 | 29 | /// 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. | |
| 34 | 36 | /// |
| 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%. | |
| 38 | 40 | public func compilePop(step n: Int, script: ScriptStep, before: FoldFrame, after: FoldFrame, |
| 39 | 41 | file: FoldFile) throws -> PopRecord { |
| 40 | 42 | 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 | ||
| 45 | 47 | let tolerance = sheetExtent(file) * relativeTolerance |
| 46 | 48 | let openAngle = script.openAngle ?? defaultOpenAngle |
| 47 | 49 | |
| 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 | } | |
| 49 | 53 | let ends = file.edgesVertices[named].map { before.verticesCoords[$0] } |
| 50 | 54 | let spine = [named] + edgeFaces.indices.filter { e in |
| 51 | 55 | e != named && edgeFaces[e].count == 2 |
| 52 | 56 | && file.edgesVertices[e].allSatisfy { onLine(before.verticesCoords[$0], ends[0], ends[1], tolerance) } |
| 53 | 57 | } |
| 54 | 58 | guard spine.allSatisfy({ abs(abs(before.edgesFoldAngle[$0]) - 180) <= angleSnapTolerance }) else { |
| 55 | throw CompileError.unresolvedCrease(step: n) | |
| 59 | throw CompileError.invalidSpine(step: n) | |
| 56 | 60 | } |
| 57 | 61 | |
| 58 | 62 | 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 { | ||
| 328 | 328 | } |
| 329 | 329 | |
| 330 | 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. | |
| 331 | /// coordinates, angles and pop phases within `tolerance`. Face orders compare as sets; | |
| 332 | /// `file_creator` is ignored. | |
| 333 | 333 | public func structurallyEqual(_ a: FoldFile, _ b: FoldFile, tolerance: Double) -> Bool { |
| 334 | 334 | guard a.fileSpec == b.fileSpec, a.fileTitle == b.fileTitle, a.fileAuthor == b.fileAuthor, |
| 335 | 335 | a.fileClasses == b.fileClasses, a.edgesVertices == b.edgesVertices, |
| @@ -369,10 +369,25 @@ private func stepsAgree(_ a: StepRecord, _ b: StepRecord, _ tolerance: Double) - | ||
| 369 | 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 | 370 | guard a.kind == b.kind, a.technique == b.technique, a.instruction == b.instruction, |
| 371 | 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 | |
| 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 | ||
| 382 | private 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 | ||
| 389 | private func axesAgree(_ a: [AxisRecord], _ b: [AxisRecord], _ tolerance: Double) -> Bool { | |
| 390 | a.count == b.count && zip(a, b).allSatisfy { x, y in | |
| 376 | 391 | x.edge == y.edge && Set(x.movingFaces) == Set(y.movingFaces) && x.parent == y.parent |
| 377 | 392 | && close(x.startAngle, y.startAngle, tolerance) && close(x.endAngle, y.endAngle, tolerance) |
| 378 | 393 | && close(x.peakAngle, y.peakAngle, tolerance) |
| @@ -453,7 +468,8 @@ private func replacing(_ s: ScriptStep, spine: CreaseRef?, openAngle: Double?) - | ||
| 453 | 468 | openAngle: openAngle) |
| 454 | 469 | } |
| 455 | 470 | |
| 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`. | |
| 457 | 473 | private let modelsDirectory = URL(fileURLWithPath: #filePath) |
| 458 | 474 | .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() |
| 459 | 475 | .deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Models") |
Packages/FoldKit/Sources/Folding/LayerMotion.swift +27 −20
| @@ -25,27 +25,35 @@ private let separationTolerance = 1e-9 | ||
| 25 | 25 | /// A non-rigid step's departures are read on its open axes and its arrivals on its close axes; the |
| 26 | 26 | /// pop between is not. Turn-over and rotate steps move every face together and have no still face. |
| 27 | 27 | /// |
| 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 | /// | |
| 28 | 33 | /// - Precondition: `validate(file)` is empty. Steps `readStep` rejects are skipped. |
| 29 | 34 | public 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. | |
| 39 | public 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 | } | |
| 30 | 43 | 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 | } | |
| 31 | 52 | 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)) | |
| 49 | 57 | } |
| 50 | 58 | return defects |
| 51 | 59 | } |
| @@ -72,13 +80,12 @@ private func crossings(_ frame: FoldFrame, axes: [FoldAxis], departure: Bool, st | ||
| 72 | 80 | carriers.append(axis) |
| 73 | 81 | a = axes[axis].parent |
| 74 | 82 | } |
| 75 | let windows = carriers.map { axes[$0].window } | |
| 76 | 83 | let t: Double |
| 77 | 84 | if departure { |
| 78 | let w = windows.min { $0.lowerBound < $1.lowerBound }! | |
| 85 | let w = carriers.map { axes[$0].window }.min { $0.lowerBound < $1.lowerBound }! | |
| 79 | 86 | t = w.lowerBound + lead * (w.upperBound - w.lowerBound) |
| 80 | 87 | } 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 | |
| 82 | 89 | t = w.upperBound - lead * (w.upperBound - w.lowerBound) |
| 83 | 90 | } |
| 84 | 91 | 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 | ||
| 57 | 57 | } |
| 58 | 58 | } |
| 59 | 59 | |
| 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)))) { | |
| 62 | 62 | try compile(FoldScript(contentsOf: fixture("unresolved-crease.foldscript")), |
| 63 | 63 | pattern: FoldFile(contentsOf: fixture("half-cp.fold"))) |
| 64 | 64 | } |
| @@ -122,7 +122,7 @@ private func halfFold(angles: [Double]? = nil, peakAngles: [Double]? = nil, kind | ||
| 122 | 122 | @Test func anUnassignedCreaseNeedsAnAngle() throws { |
| 123 | 123 | var pattern = try FoldFile(contentsOf: fixture("half-cp.fold")) |
| 124 | 124 | 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)))) { | |
| 126 | 126 | try compile(halfFold(kind: .foldAndUnfold), pattern: pattern) |
| 127 | 127 | } |
| 128 | 128 | } |
| @@ -135,7 +135,7 @@ private func halfFold(angles: [Double]? = nil, peakAngles: [Double]? = nil, kind | ||
| 135 | 135 | |
| 136 | 136 | @Test func aSpineThatIsNotFoldedIsRejected() throws { |
| 137 | 137 | // 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)) { | |
| 139 | 139 | try compile(halfFold(spine: .edgeIndex(6)), pattern: FoldFile(contentsOf: fixture("half-cp.fold"))) |
| 140 | 140 | } |
| 141 | 141 | } |
| @@ -165,7 +165,32 @@ private func halfFold(angles: [Double]? = nil, peakAngles: [Double]? = nil, kind | ||
| 165 | 165 | ScriptStep(kind: .fold, instruction: "Fold the right half.", creases: [.edgeIndex(6), .edgeIndex(6)], |
| 166 | 166 | movingSide: [SIMD2(1.5, 1)]), |
| 167 | 167 | ]) |
| 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)) { | |
| 169 | 194 | try compile(script, pattern: FoldFile(contentsOf: fixture("half-cp.fold"))) |
| 170 | 195 | } |
| 171 | 196 | } |
| @@ -211,6 +236,48 @@ private func splitLetterPattern() -> FoldFile { | ||
| 211 | 236 | } |
| 212 | 237 | } |
| 213 | 238 | |
| 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. | |
| 241 | private 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 | ||
| 214 | 281 | @Test func anOverrideThatPutsAFlapUnderTheLayerItArrivesOnIsRejected() throws { |
| 215 | 282 | // step 2's flap folds over the top, so it cannot end under f0 |
| 216 | 283 | var script = try FoldScript(contentsOf: fixture("letter-sequential.foldscript")) |
| @@ -225,3 +292,19 @@ private func splitLetterPattern() -> FoldFile { | ||
| 225 | 292 | try compile(script, pattern: FoldFile(contentsOf: fixture("letter-sequential-cp.fold"))) |
| 226 | 293 | } |
| 227 | 294 | } |
| 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 | ||
| 97 | 97 | // the open phase departs from frame 1 and the close phase arrives at frame 2 |
| 98 | 98 | #expect(layerMotionDefects(try compiled("reverse")).isEmpty) |
| 99 | 99 | } |
| 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 | ||
| 12 | 12 | #expect(layerMotionDefects(file) == [.movesThroughStillFace(step: 2, moving: 2, still: 0)]) |
| 13 | 13 | } |
| 14 | 14 | |
| 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 | ||
| 15 | 24 | @Test func aFlapDepartingTowardALayerAboveItIsFlagged() throws { |
| 16 | 25 | // step 3 unfolds f0 from under f2, which covers f0's hinge at x = 1 |
| 17 | 26 | var file = try FoldFile(contentsOf: fixture("letter-sequential.fold")) |