Commit f8a2b36461
Verified · cmc
Layout: unified · split
Packages/FoldKit/Sources/FoldCompiler/FoldScript.swift +7 −3
| @@ -28,8 +28,9 @@ public struct FoldScript: Codable, Sendable { | |||
| 28 | /// - `viewpoint`: defaults to the previous step's, or eye `[0, 0, 1]`, up `[0, 1, 0]` for step 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. | 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. | 30 | /// - `faceOrders`, `faceOrdersMidFold`: corrections to the guessed layer order. |
| 31 | /// - `spine`, `openAngle`: a reverse fold or sink, compiled by the non-rigid path. `openAngle` | 31 | /// - `spine`, `openAngle`, `openOn`: a reverse fold or sink, compiled by the non-rigid path. |
| 32 | /// defaults to 20. | 32 | /// `openAngle` defaults to 20. `openOn` names the crease whose opening opens the flap when that |
| 33 | /// is not the spine: the spine of the earlier reverse fold whose flap this step's flap is in. | ||
| 33 | public struct ScriptStep: Codable, Sendable { | 34 | public struct ScriptStep: Codable, Sendable { |
| 34 | public let kind: StepKind | 35 | public let kind: StepKind |
| 35 | public let technique: StepTechnique? | 36 | public let technique: StepTechnique? |
| @@ -48,13 +49,14 @@ public struct ScriptStep: Codable, Sendable { | |||
| 48 | public let windows: [[Double]]? | 49 | public let windows: [[Double]]? |
| 49 | public let spine: CreaseRef? | 50 | public let spine: CreaseRef? |
| 50 | public let openAngle: Double? | 51 | public let openAngle: Double? |
| 52 | public let openOn: CreaseRef? | ||
| 51 | 53 | ||
| 52 | public init(kind: StepKind, technique: StepTechnique? = nil, instruction: String, creases: [CreaseRef] = [], | 54 | public init(kind: StepKind, technique: StepTechnique? = nil, instruction: String, creases: [CreaseRef] = [], |
| 53 | movingSide: [SIMD2<Double>] = [], angles: [Double]? = nil, peakAngles: [Double]? = nil, | 55 | movingSide: [SIMD2<Double>] = [], angles: [Double]? = nil, peakAngles: [Double]? = nil, |
| 54 | rotateDegrees: Double? = nil, turnOverAxis: TurnOverAxis? = nil, repeatOf: Int? = nil, | 56 | rotateDegrees: Double? = nil, turnOverAxis: TurnOverAxis? = nil, repeatOf: Int? = nil, |
| 55 | viewpoint: Viewpoint? = nil, faceOrders: [OrderOverride]? = nil, | 57 | viewpoint: Viewpoint? = nil, faceOrders: [OrderOverride]? = nil, |
| 56 | faceOrdersMidFold: [OrderOverride]? = nil, driver: CreaseRef? = nil, windows: [[Double]]? = nil, | 58 | faceOrdersMidFold: [OrderOverride]? = nil, driver: CreaseRef? = nil, windows: [[Double]]? = nil, |
| 57 | spine: CreaseRef? = nil, openAngle: Double? = nil) { | 59 | spine: CreaseRef? = nil, openAngle: Double? = nil, openOn: CreaseRef? = nil) { |
| 58 | self.kind = kind | 60 | self.kind = kind |
| 59 | self.technique = technique | 61 | self.technique = technique |
| 60 | self.instruction = instruction | 62 | self.instruction = instruction |
| @@ -72,6 +74,7 @@ public struct ScriptStep: Codable, Sendable { | |||
| 72 | self.windows = windows | 74 | self.windows = windows |
| 73 | self.spine = spine | 75 | self.spine = spine |
| 74 | self.openAngle = openAngle | 76 | self.openAngle = openAngle |
| 77 | self.openOn = openOn | ||
| 75 | } | 78 | } |
| 76 | 79 | ||
| 77 | public init(from decoder: any Decoder) throws { | 80 | public init(from decoder: any Decoder) throws { |
| @@ -93,6 +96,7 @@ public struct ScriptStep: Codable, Sendable { | |||
| 93 | windows = try c.decodeIfPresent([[Double]].self, forKey: .windows) | 96 | windows = try c.decodeIfPresent([[Double]].self, forKey: .windows) |
| 94 | spine = try c.decodeIfPresent(CreaseRef.self, forKey: .spine) | 97 | spine = try c.decodeIfPresent(CreaseRef.self, forKey: .spine) |
| 95 | openAngle = try c.decodeIfPresent(Double.self, forKey: .openAngle) | 98 | openAngle = try c.decodeIfPresent(Double.self, forKey: .openAngle) |
| 99 | openOn = try c.decodeIfPresent(CreaseRef.self, forKey: .openOn) | ||
| 96 | } | 100 | } |
| 97 | } | 101 | } |
| 98 | 102 | ||
Packages/FoldKit/Sources/FoldCompiler/FrameCompiler.swift +2 −2
| @@ -33,7 +33,7 @@ public enum CompileError: Error, Equatable, Sendable { | |||
| 33 | case solvedAxisWindowConflict(step: Int, edge: Int) | 33 | case solvedAxisWindowConflict(step: Int, edge: Int) |
| 34 | /// The pop's largest relative change in a render-mesh edge's length exceeds 10%. | 34 | /// The pop's largest relative change in a render-mesh edge's length exceeds 10%. |
| 35 | case popTooStrained(step: Int, strain: Double) | 35 | case popTooStrained(step: Int, strain: Double) |
| 36 | /// A reverse fold or sink names no `spine` to open on. | 36 | /// A reverse fold or sink, or a step naming `openOn`, names no `spine`. |
| 37 | case missingSpine(step: Int) | 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. | 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) | 39 | case invalidSpine(step: Int) |
| @@ -99,7 +99,7 @@ public func compile(_ script: FoldScript, pattern: FoldFile) throws -> FoldFile | |||
| 99 | private func appendStep(_ n: Int, _ script: ScriptStep, viewpoint: Viewpoint, to file: inout FoldFile, | 99 | private func appendStep(_ n: Int, _ script: ScriptStep, viewpoint: Viewpoint, to file: inout FoldFile, |
| 100 | finalAssignment: [EdgeAssignment]) throws { | 100 | finalAssignment: [EdgeAssignment]) throws { |
| 101 | let technique = script.technique ?? .plain | 101 | let technique = script.technique ?? .plain |
| 102 | if script.spine == nil && [.insideReverse, .outsideReverse, .sink].contains(technique) { | 102 | if script.spine == nil && ([.insideReverse, .outsideReverse, .sink].contains(technique) || script.openOn != nil) { |
| 103 | throw CompileError.missingSpine(step: n) | 103 | throw CompileError.missingSpine(step: n) |
| 104 | } | 104 | } |
| 105 | if script.spine != nil && script.kind != .fold { throw CompileError.invalidSpine(step: n) } | 105 | if script.spine != nil && script.kind != .fold { throw CompileError.invalidSpine(step: n) } |
Packages/FoldKit/Sources/FoldCompiler/PopCompiler.swift +116 −46
| @@ -18,28 +18,34 @@ private let angleSamples = 256 | |||
| 18 | /// on, with decision 0003's opening. `before` is frame n − 1; `after` is frame n as the step's axes | 18 | /// on, with decision 0003's opening. `before` is frame n − 1; `after` is frame n as the step's axes |
| 19 | /// place it, carrying the step's record; `file` holds frames 0…n − 1. | 19 | /// place it, carrying the step's record; `file` holds frames 0…n − 1. |
| 20 | /// | 20 | /// |
| 21 | /// The named crease is folded flat. The paper is cut along every edge on its line in `before`; | 21 | /// The flap opens on the opening crease: `openOn`, or the named spine crease. Both are folded |
| 22 | /// the spine is the edges of that line whose faces then fall on different sides, each folded flat | 22 | /// flat. The paper is cut along every edge on either crease's line in `before`, and, with |
| 23 | /// or flat. A flat one is a bend line: it bends while the flap is open and is never creased. The | 23 | /// `openOn`, along the creases of the earlier reverse fold that opened on `openOn` and whose flap |
| 24 | /// side nearer the viewpoint opens: the open axis turns it about the line, from ±180 to | 24 | /// holds this step's. Of each line, the edges whose faces then fall on different sides are kept, |
| 25 | /// ±`openAngle`. The pop and close move on a tree cut along the spine and the step's creases, | 25 | /// each folded flat or flat; a flat one is a bend line, which bends while the flap is open and is |
| 26 | /// grown from the faces neither the opening nor the step moves, spine first. In `popped` the spine | 26 | /// never creased. The side of the opening crease nearer the viewpoint opens, with the earlier |
| 27 | /// is held as the open phase leaves it, reversed where both its faces move in the step, and the | 27 | /// fold's flap: the open axes are a tree grown from the other faces across the kept edges, the |
| 28 | /// other tree axes are solved to keep the paper whole, starting from `openAngle / 180` of their | 28 | /// opening crease first and driven from ±180 to ±`openAngle`, the earlier fold's creases and the |
| 29 | /// way. The close axes drive the named spine edge back to ±180 and solve the rest, as for a rigid | 29 | /// spine solved to keep the paper whole. The pop and close move on a tree cut along those edges and |
| 30 | /// step, and must arrive at `after`'s coordinates. | 30 | /// the step's creases, grown from the faces neither the opening nor the step moves, the opening |
| 31 | /// crease first. In `popped` the opening crease and the spine's edges in the flap are held as the | ||
| 32 | /// open phase leaves them, the latter reversed, and the other tree axes are solved, starting where | ||
| 33 | /// the open phase leaves them or `openAngle / 180` of their way. The close axes drive the opening | ||
| 34 | /// crease back to ±180 and solve the rest, as for a rigid step, and must arrive at `after`'s | ||
| 35 | /// coordinates. | ||
| 31 | /// | 36 | /// |
| 32 | /// The starting guess can lead the solver to another branch of the vertex's motion. Closing the | 37 | /// The starting guess can lead the solver to another branch of the vertex's motion. Closing the |
| 33 | /// loops does not catch that: every branch is closed. A branch is caught when the close does not | 38 | /// loops does not catch that: every branch is closed. A branch is caught when the close does not |
| 34 | /// reach `after`'s coordinates, when it leaves a crease of the last frame assigned against the | 39 | /// reach `after`'s coordinates, when it leaves a crease of the last frame assigned against the |
| 35 | /// crease pattern, or when frame n breaks the validator's layer-order rules; the reverse fixture's | 40 | /// crease pattern, or when frame n breaks the validator's layer-order rules; the reverse fixtures' |
| 36 | /// test that the tip lands between the flap's layers covers that fixture. `layerMotionDefects` | 41 | /// tests that the tip lands between the flap's layers cover them. `layerMotionDefects` does not |
| 37 | /// does not add a check here: frame n's orders for the faces the step's axes move are guessed | 42 | /// add a check here: frame n's orders for the faces the step's axes move are guessed from the same |
| 38 | /// from the same close, read near the same moment. | 43 | /// close, read near the same moment. |
| 39 | /// | 44 | /// |
| 40 | /// - Throws: `unresolvedCrease` when the spine names no edge, `invalidSpine` when it is not | 45 | /// - Throws: `unresolvedCrease` when the spine or `openOn` names no edge, `invalidSpine` when one |
| 41 | /// folded flat, `noRigidMotion` when the flap cannot open on its spine, `popped` does not close | 46 | /// of them is not folded flat or a kept edge is neither folded flat nor flat, `noRigidMotion` |
| 42 | /// or the close does not reach `after`, and `popTooStrained` when the pop's strain exceeds 10%. | 47 | /// when the flap cannot open, `popped` does not close or the close does not reach `after`, and |
| 48 | /// `popTooStrained` when the pop's strain exceeds 10%. | ||
| 43 | public func compilePop(step n: Int, script: ScriptStep, before: FoldFrame, after: FoldFrame, | 49 | public func compilePop(step n: Int, script: ScriptStep, before: FoldFrame, after: FoldFrame, |
| 44 | file: FoldFile) throws -> PopRecord { | 50 | file: FoldFile) throws -> PopRecord { |
| 45 | guard let reference = script.spine, let record = after.step else { | 51 | guard let reference = script.spine, let record = after.step else { |
| @@ -50,12 +56,13 @@ public func compilePop(step n: Int, script: ScriptStep, before: FoldFrame, after | |||
| 50 | let tolerance = sheetExtent(file) * relativeTolerance | 56 | let tolerance = sheetExtent(file) * relativeTolerance |
| 51 | let openAngle = script.openAngle ?? defaultOpenAngle | 57 | let openAngle = script.openAngle ?? defaultOpenAngle |
| 52 | func foldedFlat(_ e: Int) -> Bool { abs(abs(before.edgesFoldAngle[e]) - 180) <= angleSnapTolerance } | 58 | func foldedFlat(_ e: Int) -> Bool { abs(abs(before.edgesFoldAngle[e]) - 180) <= angleSnapTolerance } |
| 53 | 59 | func edge(_ ref: CreaseRef) throws -> Int { | |
| 54 | guard let named = resolve(reference, file, edgeFaces) else { | 60 | guard let e = resolve(ref, file, edgeFaces) else { throw CompileError.unresolvedCrease(step: n, crease: ref) } |
| 55 | throw CompileError.unresolvedCrease(step: n, crease: reference) | 61 | guard foldedFlat(e) else { throw CompileError.invalidSpine(step: n) } |
| 62 | return e | ||
| 56 | } | 63 | } |
| 57 | guard foldedFlat(named) else { throw CompileError.invalidSpine(step: n) } | 64 | let named = try edge(reference) |
| 58 | let line = onLine(named, before, file, edgeFaces, tolerance) | 65 | let opener = try script.openOn.map(edge) ?? named |
| 59 | 66 | ||
| 60 | var group = Array(repeating: -1, count: faceCount) | 67 | var group = Array(repeating: -1, count: faceCount) |
| 61 | for (a, axis) in record.axes.enumerated() { | 68 | for (a, axis) in record.axes.enumerated() { |
| @@ -64,47 +71,63 @@ public func compilePop(step n: Int, script: ScriptStep, before: FoldFrame, after | |||
| 64 | let moving = group.map { $0 >= 0 } | 71 | let moving = group.map { $0 >= 0 } |
| 65 | let creased = edgeFaces.indices.filter { edgeFaces[$0].count == 2 && group[edgeFaces[$0][0]] != group[edgeFaces[$0][1]] } | 72 | let creased = edgeFaces.indices.filter { edgeFaces[$0].count == 2 && group[edgeFaces[$0][0]] != group[edgeFaces[$0][1]] } |
| 66 | 73 | ||
| 67 | // edges on the line whose faces stay connected without it lie within one side | 74 | // the earlier reverse fold this step's flap is in, which opened on the opening crease |
| 68 | let sides = regions(cut: Set(line), file, edgeFaces) | 75 | let tip = Set((0..<faceCount).filter { moving[$0] }) |
| 69 | let spine = line.filter { sides[edgeFaces[$0][0]] != sides[edgeFaces[$0][1]] } | 76 | let earlier = script.openOn == nil ? nil : (1..<n).reversed().lazy.compactMap { file.frames[$0].step }.first { s in |
| 70 | guard spine.allSatisfy({ foldedFlat($0) || abs(before.edgesFoldAngle[$0]) <= angleSnapTolerance }) else { | 77 | s.nonRigid && s.pop?.spine.contains(opener) == true && tip.isSubset(of: s.axes.flatMap(\.movingFaces)) |
| 78 | } | ||
| 79 | let earlierFlap = Set(earlier?.axes.flatMap(\.movingFaces) ?? []) | ||
| 80 | let earlierCreases = edgeFaces.indices.filter { e in | ||
| 81 | edgeFaces[e].count == 2 && earlierFlap.contains(edgeFaces[e][0]) != earlierFlap.contains(edgeFaces[e][1]) | ||
| 82 | } | ||
| 83 | |||
| 84 | // edges on a line whose faces stay connected without it lie within one side | ||
| 85 | let openerLine = onLine(opener, before, file, edgeFaces, tolerance) | ||
| 86 | let spineLine = onLine(named, before, file, edgeFaces, tolerance) | ||
| 87 | let sides = regions(cut: Set(openerLine + earlierCreases + spineLine), file, edgeFaces) | ||
| 88 | func across(_ e: Int) -> Bool { sides[edgeFaces[e][0]] != sides[edgeFaces[e][1]] } | ||
| 89 | let openLine = openerLine.filter(across) | ||
| 90 | let spine = spineLine.filter(across) | ||
| 91 | guard (openLine + spine).allSatisfy({ foldedFlat($0) || abs(before.edgesFoldAngle[$0]) <= angleSnapTolerance }) else { | ||
| 71 | throw CompileError.invalidSpine(step: n) | 92 | throw CompileError.invalidSpine(step: n) |
| 72 | } | 93 | } |
| 73 | let tipSpine = Set(spine.filter { edgeFaces[$0].allSatisfy { moving[$0] } }) | 94 | let tipSpine = Set(spine.filter { edgeFaces[$0].allSatisfy(tip.contains) }) |
| 74 | 95 | ||
| 75 | // the layer nearer the viewer opens: of the named edge's faces, the one a valley puts on the | 96 | // the layer nearer the viewer opens: of the opening crease's faces, the one a valley puts on |
| 76 | // first face's normal side, or a mountain on the other | 97 | // the first face's normal side, or a mountain on the other |
| 77 | let (f, g) = (edgeFaces[named][0], edgeFaces[named][1]) | 98 | let (f, g) = (edgeFaces[opener][0], edgeFaces[opener][1]) |
| 78 | let normals = faceNormals(before, file) | 99 | let normals = faceNormals(before, file) |
| 79 | let gNearer = (before.edgesFoldAngle[named] > 0) == (dot(normals[f], record.viewpoint.eye) > 0) | 100 | let gNearer = (before.edgesFoldAngle[opener] > 0) == (dot(normals[f], record.viewpoint.eye) > 0) |
| 80 | let (near, far) = gNearer ? (g, f) : (f, g) | 101 | let (near, far) = gNearer ? (g, f) : (f, g) |
| 81 | guard sides[far] != sides[near] else { throw CompileError.noRigidMotion(step: n) } | 102 | guard sides[far] != sides[near], !earlierFlap.contains(far) else { throw CompileError.noRigidMotion(step: n) } |
| 82 | let opening = (0..<faceCount).filter { sides[$0] == sides[near] } | 103 | let opening = Set((0..<faceCount).filter { sides[$0] == sides[near] || earlierFlap.contains($0) }) |
| 83 | let openSign = before.edgesFoldAngle[named] > 0 ? 1.0 : -1.0 | 104 | let openEdges = unique(openLine + earlierCreases + spine) |
| 84 | let openAxes = [AxisRecord(edge: named, movingFaces: opening, startAngle: before.edgesFoldAngle[named], | 105 | let openTree = growTree(order: openEdges, fixed: Set((0..<faceCount).filter { !opening.contains($0) }), |
| 85 | endAngle: openSign * openAngle, window: [0, phases[0]])] | 106 | file, edgeFaces) |
| 86 | let opened = try openEndAngles(n, openAxes, edges: spine, before: before, record, file) | 107 | guard openTree.axes.first?.edge == opener else { throw CompileError.noRigidMotion(step: n) } |
| 108 | let openSign = before.edgesFoldAngle[opener] > 0 ? 1.0 : -1.0 | ||
| 109 | let openAxes = try openingAxes(n, openTree, end: openSign * openAngle, before: before, record, file) | ||
| 110 | let opened = try openEndAngles(n, openAxes, edges: openEdges, before: before, record, file) | ||
| 87 | 111 | ||
| 88 | // the tree the pop and the close move on | 112 | // the tree the pop and the close move on |
| 89 | let fixed = Set((0..<faceCount).filter { !moving[$0] && !opening.contains($0) }) | 113 | let fixed = Set((0..<faceCount).filter { !moving[$0] && !opening.contains($0) }) |
| 90 | guard !fixed.isEmpty else { throw CompileError.noRigidMotion(step: n) } | 114 | guard !fixed.isEmpty else { throw CompileError.noRigidMotion(step: n) } |
| 91 | let order = spine + record.axes.map(\.edge).filter { !spine.contains($0) } | 115 | let order = unique(openEdges + record.axes.map(\.edge) + creased) |
| 92 | + creased.filter { e in !spine.contains(e) && !record.axes.contains { $0.edge == e } } | ||
| 93 | let tree = growTree(order: order, fixed: fixed, file, edgeFaces) | 116 | let tree = growTree(order: order, fixed: fixed, file, edgeFaces) |
| 94 | 117 | ||
| 95 | // popped: the spine held as the opening leaves it, reversed beyond the step's creases; the | 118 | // popped: the open edges as the opening leaves them, the spine reversed in the flap; the rest |
| 96 | // rest solved. The close returns the spine to where it was, reversed beyond the step's creases. | 119 | // solved. The close returns the open edges to where they were, the spine reversed in the flap. |
| 97 | func held(_ e: Int) -> Double { tipSpine.contains(e) ? -opened[e]! : opened[e]! } | ||
| 98 | func closed(_ e: Int) -> Double { | 120 | func closed(_ e: Int) -> Double { |
| 99 | spine.contains(e) ? (tipSpine.contains(e) ? -1 : 1) * before.edgesFoldAngle[e] : after.edgesFoldAngle[e] | 121 | opened[e] == nil ? after.edgesFoldAngle[e] : (tipSpine.contains(e) ? -1 : 1) * before.edgesFoldAngle[e] |
| 100 | } | 122 | } |
| 101 | var guess: [Int: Double] = [:] | 123 | var guess: [Int: Double] = [:] |
| 102 | for axis in tree.axes { | 124 | for axis in tree.axes { |
| 103 | let start = before.edgesFoldAngle[axis.edge] | 125 | let start = before.edgesFoldAngle[axis.edge] |
| 104 | guess[axis.edge] = spine.contains(axis.edge) ? held(axis.edge) | 126 | guess[axis.edge] = opened[axis.edge].map { tipSpine.contains(axis.edge) ? -$0 : $0 } |
| 105 | : start + (closed(axis.edge) - start) * openAngle / 180 | 127 | ?? start + (closed(axis.edge) - start) * openAngle / 180 |
| 106 | } | 128 | } |
| 107 | let popped = try solvedPose(n, tree, from: before, angles: guess, holding: Set(spine), record, file) | 129 | let popped = try solvedPose(n, tree, from: before, angles: guess, holding: Set(openLine).union(tipSpine), |
| 130 | record, file) | ||
| 108 | var poppedFrame = before | 131 | var poppedFrame = before |
| 109 | poppedFrame.verticesCoords = popped.positions | 132 | poppedFrame.verticesCoords = popped.positions |
| 110 | 133 | ||
| @@ -126,6 +149,53 @@ public func compilePop(step n: Int, script: ScriptStep, before: FoldFrame, after | |||
| 126 | return pop | 149 | return pop |
| 127 | } | 150 | } |
| 128 | 151 | ||
| 152 | /// `edges` without repeats, in order. | ||
| 153 | private func unique(_ edges: [Int]) -> [Int] { | ||
| 154 | var seen = Set<Int>() | ||
| 155 | return edges.filter { seen.insert($0).inserted } | ||
| 156 | } | ||
| 157 | |||
| 158 | /// The open axes on `[0, phases[0]]`: the tree's first axis, the opening crease, linear from its | ||
| 159 | /// angle in `before` to `end`; the axes on a loop's cycle solved so the loops close, continued | ||
| 160 | /// from `before` along the window to find where they end and then solved as for a rigid step; the | ||
| 161 | /// rest held. | ||
| 162 | private func openingAxes(_ n: Int, _ tree: RegionTree, end: Double, before: FoldFrame, _ record: StepRecord, | ||
| 163 | _ file: FoldFile) throws -> [AxisRecord] { | ||
| 164 | let opener = tree.axes[0].edge | ||
| 165 | func draft(_ ends: [Int: Double]) -> (StepRecord, FoldFile) { | ||
| 166 | let axes = records(tree, start: { before.edgesFoldAngle[$0] }, end: { ends[$0] ?? before.edgesFoldAngle[$0] }, | ||
| 167 | window: [0, phases[0]]) | ||
| 168 | let open = withAxes(record, axes) | ||
| 169 | var draft = file | ||
| 170 | draft.frames.append(FoldFrame(verticesCoords: before.verticesCoords, edgesAssignment: before.edgesAssignment, | ||
| 171 | edgesFoldAngle: before.edgesFoldAngle, faceOrders: [], step: open)) | ||
| 172 | return (open, draft) | ||
| 173 | } | ||
| 174 | let (held, heldFile) = draft([opener: end]) | ||
| 175 | guard !tree.loops.isEmpty else { return held.axes } | ||
| 176 | let step = try readStep(n, in: heldFile) | ||
| 177 | let driver = step.axes.firstIndex { $0.edge == opener }! | ||
| 178 | let free = axesOnCycles(step, loops: tree.loops, heldFile).subtracting([driver]).sorted() | ||
| 179 | guard !free.isEmpty else { return held.axes } | ||
| 180 | |||
| 181 | let kinematics = LoopKinematics(step: step, file: heldFile) | ||
| 182 | let tolerance = sheetExtent(file) * relativeTolerance | ||
| 183 | var previous = step.axes.map(\.startAngle), angles = previous | ||
| 184 | for k in 1...angleSamples { | ||
| 185 | var guess = zip(angles, previous).map { 2 * $0 - $1 } | ||
| 186 | guess[driver] = step.axes[driver].startAngle + Double(k) / Double(angleSamples) * (end - step.axes[driver].startAngle) | ||
| 187 | guard kinematics.solve(&guess, free: free) <= tolerance else { throw CompileError.noRigidMotion(step: n) } | ||
| 188 | (previous, angles) = (angles, guess) | ||
| 189 | } | ||
| 190 | let (open, openFile) = draft(Dictionary(uniqueKeysWithValues: zip(step.axes.map(\.edge), angles))) | ||
| 191 | let solved = try solveLoops(n, open, try readStep(n, in: openFile), loops: tree.loops, openFile) | ||
| 192 | var solvedFile = openFile | ||
| 193 | solvedFile.frames[n].step = solved | ||
| 194 | try checkClosure(n, try readStep(n, in: solvedFile), driver: opener, solvedFile, | ||
| 195 | solved: solved.axes.contains { $0.angles != nil }) | ||
| 196 | return solved.axes | ||
| 197 | } | ||
| 198 | |||
| 129 | /// `named` and every other interior edge on its line in `frame`. | 199 | /// `named` and every other interior edge on its line in `frame`. |
| 130 | private func onLine(_ named: Int, _ frame: FoldFrame, _ file: FoldFile, _ edgeFaces: [[Int]], | 200 | private func onLine(_ named: Int, _ frame: FoldFrame, _ file: FoldFile, _ edgeFaces: [[Int]], |
| 131 | _ tolerance: Double) -> [Int] { | 201 | _ tolerance: Double) -> [Int] { |
Packages/FoldKit/Sources/FoldFormat/StepRecord.swift +4 −3
| @@ -48,9 +48,10 @@ public struct Viewpoint: Codable, Equatable, Sendable { | |||
| 48 | } | 48 | } |
| 49 | } | 49 | } |
| 50 | 50 | ||
| 51 | /// The open, pop and close of a non-rigid step: `openAxes` open the flap about its `spine` to | 51 | /// The open, pop and close of a non-rigid step: `openAxes` open the flap on `[0, phases[0]]`, the |
| 52 | /// `openAngle` on `[0, phases[0]]`, every vertex reaches `popped` by `phases[1]`, and | 52 | /// first turning the opening crease to `openAngle` (the `spine`, or for a nested opening an |
| 53 | /// `closeAxes`, relative to `popped`, close the flap on `[phases[1], 1]`. | 53 | /// earlier fold's spine), every vertex reaches `popped` by `phases[1]`, and `closeAxes`, relative |
| 54 | /// to `popped`, close the flap on `[phases[1], 1]`. | ||
| 54 | public struct PopRecord: Codable, Equatable, Sendable { | 55 | public struct PopRecord: Codable, Equatable, Sendable { |
| 55 | public let spine: [Int] | 56 | public let spine: [Int] |
| 56 | public let openAngle: Double | 57 | public let openAngle: Double |
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/reverse-nested-cp.fold added +13
| @@ -0,0 +1,13 @@ | |||
| 1 | { | ||
| 2 | "file_spec": 1.2, | ||
| 3 | "file_title": "Nested reverse folds", | ||
| 4 | "file_author": "Traditional", | ||
| 5 | "file_classes": ["creasePattern"], | ||
| 6 | "vertices_coords": [[0, 0], [3, 0], [4, 0], [4, 1], [4, 2], [3, 2], [0, 2], [0, 1], [2, 1], | ||
| 7 | [3.5, 1], [4, 0.5], [4, 1.5]], | ||
| 8 | "edges_vertices": [[0, 1], [1, 2], [2, 10], [10, 3], [3, 11], [11, 4], [4, 5], [5, 6], [6, 7], [7, 0], | ||
| 9 | [7, 8], [8, 9], [9, 3], [8, 1], [8, 5], [9, 10], [9, 11]], | ||
| 10 | "edges_assignment": ["B", "B", "B", "B", "B", "B", "B", "B", "B", "B", | ||
| 11 | "V", "M", "V", "V", "V", "M", "M"], | ||
| 12 | "faces_vertices": [[0, 1, 8, 7], [1, 2, 10, 9, 8], [10, 3, 9], [9, 3, 11], [8, 9, 11, 4, 5], [7, 8, 5, 6]] | ||
| 13 | } | ||
Packages/FoldKit/Sources/FoldKitTestSupport/Fixtures/reverse-nested.foldscript added +31
| @@ -0,0 +1,31 @@ | |||
| 1 | { | ||
| 2 | "creasePattern": "reverse-nested-cp.fold", | ||
| 3 | "title": "Nested reverse folds", | ||
| 4 | "steps": [ | ||
| 5 | { | ||
| 6 | "kind": "fold", | ||
| 7 | "instruction": "Valley fold the top half down onto the bottom half.", | ||
| 8 | "creases": [[[0, 1], [2, 1]]], | ||
| 9 | "movingSide": [[1, 1.5]] | ||
| 10 | }, | ||
| 11 | { | ||
| 12 | "kind": "fold", | ||
| 13 | "technique": "insideReverse", | ||
| 14 | "instruction": "Inside reverse fold the right end down between the layers.", | ||
| 15 | "creases": [[[2, 1], [3, 0]], [[2, 1], [3, 2]]], | ||
| 16 | "movingSide": [[3.2, 0.5]], | ||
| 17 | "spine": [[0, 1], [2, 1]], | ||
| 18 | "faceOrders": [{"above": [3.2, 1.5], "below": [3.2, 0.5]}, {"above": [3.9, 1.1], "below": [3.9, 0.9]}] | ||
| 19 | }, | ||
| 20 | { | ||
| 21 | "kind": "fold", | ||
| 22 | "technique": "insideReverse", | ||
| 23 | "instruction": "Inside reverse fold the end of the flap up between its layers.", | ||
| 24 | "creases": [[[3.5, 1], [4, 0.5]], [[3.5, 1], [4, 1.5]]], | ||
| 25 | "movingSide": [[3.9, 0.9]], | ||
| 26 | "spine": [[3.5, 1], [4, 1]], | ||
| 27 | "openOn": [[0, 1], [2, 1]], | ||
| 28 | "faceOrders": [{"above": [3.9, 1.1], "below": [3.9, 0.9]}] | ||
| 29 | } | ||
| 30 | ] | ||
| 31 | } | ||
Packages/FoldKit/Sources/FoldKitTestSupport/Helpers.swift +13 −7
| @@ -407,10 +407,16 @@ private func axesAgree(_ a: [AxisRecord], _ b: [AxisRecord], _ tolerance: Double | |||
| 407 | } | 407 | } |
| 408 | 408 | ||
| 409 | /// Whether, in `reverse.fold`'s geometry at `positions`, the tip's point at sheet point | 409 | /// Whether, in `reverse.fold`'s geometry at `positions`, the tip's point at sheet point |
| 410 | /// (2.75, 0.75) lies strictly between the body's two layers: the planes of the faces containing | 410 | /// (2.75, 0.75) lies strictly between the body's two layers: the faces containing sheet points |
| 411 | /// sheet points (0.5, 0.5) and (0.5, 1.5), at the tip point's x and y. False when the tip point is | 411 | /// (0.5, 0.5) and (0.5, 1.5). |
| 412 | /// not over both layers. | ||
| 413 | public func tipIsBetweenBodyLayers(_ positions: [SIMD3<Double>], _ file: FoldFile) -> Bool { | 412 | public func tipIsBetweenBodyLayers(_ positions: [SIMD3<Double>], _ file: FoldFile) -> Bool { |
| 413 | pointIsBetweenLayers(positions, file, point: SIMD2(2.75, 0.75), lower: SIMD2(0.5, 0.5), upper: SIMD2(0.5, 1.5)) | ||
| 414 | } | ||
| 415 | |||
| 416 | /// Whether, at `positions`, sheet point `point` lies strictly between the planes of the faces | ||
| 417 | /// containing sheet points `lower` and `upper`, at its x and y. False when it is not over both. | ||
| 418 | public func pointIsBetweenLayers(_ positions: [SIMD3<Double>], _ file: FoldFile, point: SIMD2<Double>, | ||
| 419 | lower lowerPoint: SIMD2<Double>, upper upperPoint: SIMD2<Double>) -> Bool { | ||
| 414 | let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) } | 420 | let flat = file.frames[0].verticesCoords.map { SIMD2($0.x, $0.y) } |
| 415 | func face(containing p: SIMD2<Double>) -> Int? { | 421 | func face(containing p: SIMD2<Double>) -> Int? { |
| 416 | file.facesVertices.indices.first { f in | 422 | file.facesVertices.indices.first { f in |
| @@ -444,9 +450,9 @@ public func tipIsBetweenBodyLayers(_ positions: [SIMD3<Double>], _ file: FoldFil | |||
| 444 | guard inside else { return nil } | 450 | guard inside else { return nil } |
| 445 | return corners[0].z - (n.x * (q.x - corners[0].x) + n.y * (q.y - corners[0].y)) / n.z | 451 | return corners[0].z - (n.x * (q.x - corners[0].x) + n.y * (q.y - corners[0].y)) / n.z |
| 446 | } | 452 | } |
| 447 | guard let tip = face(containing: SIMD2(2.75, 0.75)), let lower = face(containing: SIMD2(0.5, 0.5)), | 453 | guard let tip = face(containing: point), let lower = face(containing: lowerPoint), |
| 448 | let upper = face(containing: SIMD2(0.5, 1.5)) else { return false } | 454 | let upper = face(containing: upperPoint) else { return false } |
| 449 | let probe = place(SIMD2(2.75, 0.75), on: tip) | 455 | let probe = place(point, on: tip) |
| 450 | let q = SIMD2(probe.x, probe.y) | 456 | let q = SIMD2(probe.x, probe.y) |
| 451 | guard let a = height(of: lower, at: q), let b = height(of: upper, at: q) else { return false } | 457 | guard let a = height(of: lower, at: q), let b = height(of: upper, at: q) else { return false } |
| 452 | return probe.z > min(a, b) && probe.z < max(a, b) | 458 | return probe.z > min(a, b) && probe.z < max(a, b) |
| @@ -475,7 +481,7 @@ private func replacing(_ s: ScriptStep, spine: CreaseRef?, openAngle: Double?) - | |||
| 475 | movingSide: s.movingSide, angles: s.angles, peakAngles: s.peakAngles, rotateDegrees: s.rotateDegrees, | 481 | movingSide: s.movingSide, angles: s.angles, peakAngles: s.peakAngles, rotateDegrees: s.rotateDegrees, |
| 476 | turnOverAxis: s.turnOverAxis, repeatOf: s.repeatOf, viewpoint: s.viewpoint, faceOrders: s.faceOrders, | 482 | turnOverAxis: s.turnOverAxis, repeatOf: s.repeatOf, viewpoint: s.viewpoint, faceOrders: s.faceOrders, |
| 477 | faceOrdersMidFold: s.faceOrdersMidFold, driver: s.driver, windows: s.windows, spine: spine, | 483 | faceOrdersMidFold: s.faceOrdersMidFold, driver: s.driver, windows: s.windows, spine: spine, |
| 478 | openAngle: openAngle) | 484 | openAngle: openAngle, openOn: s.openOn) |
| 479 | } | 485 | } |
| 480 | 486 | ||
| 481 | /// The repository's `Models/` directory: this file's path with its last five components, up to | 487 | /// The repository's `Models/` directory: this file's path with its last five components, up to |
Packages/FoldKit/Tests/FoldCompilerTests/CompilerTests.swift +8 −2
| @@ -102,11 +102,11 @@ func compilingASyntheticScriptReproducesItsHandWrittenFixture(_ name: String) th | |||
| 102 | 102 | ||
| 103 | private func halfFold(angles: [Double]? = nil, peakAngles: [Double]? = nil, kind: StepKind = .fold, | 103 | private func halfFold(angles: [Double]? = nil, peakAngles: [Double]? = nil, kind: StepKind = .fold, |
| 104 | movingSide: SIMD2<Double> = SIMD2(1.5, 1), faceOrders: [OrderOverride]? = nil, | 104 | movingSide: SIMD2<Double> = SIMD2(1.5, 1), faceOrders: [OrderOverride]? = nil, |
| 105 | spine: CreaseRef? = nil) -> FoldScript { | 105 | spine: CreaseRef? = nil, openOn: CreaseRef? = nil) -> FoldScript { |
| 106 | FoldScript(creasePattern: "half-cp.fold", title: "Half", steps: [ | 106 | FoldScript(creasePattern: "half-cp.fold", title: "Half", steps: [ |
| 107 | ScriptStep(kind: kind, instruction: "Fold the right half.", creases: [.betweenVertices(SIMD2(1, 0), SIMD2(1, 2))], | 107 | ScriptStep(kind: kind, instruction: "Fold the right half.", creases: [.betweenVertices(SIMD2(1, 0), SIMD2(1, 2))], |
| 108 | movingSide: [movingSide], angles: angles, peakAngles: peakAngles, faceOrders: faceOrders, | 108 | movingSide: [movingSide], angles: angles, peakAngles: peakAngles, faceOrders: faceOrders, |
| 109 | spine: spine), | 109 | spine: spine, openOn: openOn), |
| 110 | ]) | 110 | ]) |
| 111 | } | 111 | } |
| 112 | 112 | ||
| @@ -150,6 +150,12 @@ private func halfFold(angles: [Double]? = nil, peakAngles: [Double]? = nil, kind | |||
| 150 | } | 150 | } |
| 151 | } | 151 | } |
| 152 | 152 | ||
| 153 | @Test func anOpeningCreaseWithoutASpineIsRejected() throws { | ||
| 154 | #expect(throws: CompileError.missingSpine(step: 1)) { | ||
| 155 | try compile(halfFold(openOn: .edgeIndex(6)), pattern: FoldFile(contentsOf: fixture("half-cp.fold"))) | ||
| 156 | } | ||
| 157 | } | ||
| 158 | |||
| 153 | @Test func aLoopCreaseScriptedAtTheWrongAngleHasNoRigidMotion() throws { | 159 | @Test func aLoopCreaseScriptedAtTheWrongAngleHasNoRigidMotion() throws { |
| 154 | let step = degreeFourScript().steps[0] | 160 | let step = degreeFourScript().steps[0] |
| 155 | let script = FoldScript(creasePattern: "", title: "Degree-4 vertex", steps: [ | 161 | let script = FoldScript(creasePattern: "", title: "Degree-4 vertex", steps: [ |
Packages/FoldKit/Tests/FoldCompilerTests/NonRigidTests.swift +24
| @@ -119,6 +119,30 @@ import FoldKitTestSupport | |||
| 119 | #expect(meshInterpenetrations(i, samples: 64).isEmpty) | 119 | #expect(meshInterpenetrations(i, samples: 64).isEmpty) |
| 120 | } | 120 | } |
| 121 | 121 | ||
| 122 | @Test func aNestedReverseFoldOpensOnTheOuterSpine() throws { | ||
| 123 | // decision 0003: the head reopens the neck by turning the body's near side again, the neck's | ||
| 124 | // creases solved on their reversed branch, then pops and closes between the neck's layers | ||
| 125 | let file = try compiled("reverse-nested") | ||
| 126 | let step = try readSteps(file)[2] | ||
| 127 | let pop = try #require(step.pop) | ||
| 128 | #expect(pop.openAxes.first?.edge == 10) | ||
| 129 | #expect(Set(pop.openAxes.map(\.edge)).isSuperset(of: [13, 14])) | ||
| 130 | #expect(pop.openAxes.contains { $0.curve != nil }) | ||
| 131 | let i = FoldInterpolator(file: file, step: step) | ||
| 132 | let (lo, hi) = (pop.phases.lowerBound, pop.phases.upperBound) | ||
| 133 | for n in 0...256 { | ||
| 134 | let t = Double(n) / 256 | ||
| 135 | guard t <= lo || t >= hi else { continue } | ||
| 136 | #expect(maxEdgeLengthDrift(i.positions(at: t), file) < 1e-6 * sheetSize(file), "t \(t)") | ||
| 137 | } | ||
| 138 | let worst = (0...64).map { strain(i.meshPositions(at: lo + Double($0) / 64 * (hi - lo)), mesh: i.mesh) }.max()! | ||
| 139 | #expect(worst <= 0.10) | ||
| 140 | #expect(meshInterpenetrations(i, samples: 64).isEmpty) | ||
| 141 | #expect(pointIsBetweenLayers(i.positions(at: hi + 0.97 * (1 - hi)), file, point: SIMD2(3.9, 0.9), | ||
| 142 | lower: SIMD2(3.2, 0.5), upper: SIMD2(3.2, 1.5))) | ||
| 143 | #expect(layerMotionDefects(file).isEmpty) | ||
| 144 | } | ||
| 145 | |||
| 122 | @Test func theReverseFoldMovesThroughNoStillFace() throws { | 146 | @Test func theReverseFoldMovesThroughNoStillFace() throws { |
| 123 | // the open phase departs from frame 1 and the close phase arrives at frame 2 | 147 | // the open phase departs from frame 1 and the close phase arrives at frame 2 |
| 124 | #expect(layerMotionDefects(try compiled("reverse")).isEmpty) | 148 | #expect(layerMotionDefects(try compiled("reverse")).isEmpty) |