import FoldFormat import Folding import simd /// The spine's fold angle when the flap is open, in degrees from flat, when the script gives none /// (decision 0003). private let defaultOpenAngle = 20.0 /// The boundaries of the pop on the step's t (decision 0002). private let phases = [1.0 / 3, 2.0 / 3] /// The largest relative change in a render-mesh edge's length the pop may reach (decision 0002). private let strainBound = 0.10 /// Samples of the pop measured for strain. private let popSamples = 64 /// Samples of the open and close phases along which end angles are unwrapped. private let angleSamples = 256 /// Decision 0002's open, pop and close for step `n`, whose script names the `spine` its flap opens /// on, with decision 0003's opening. `before` is frame n − 1; `after` is frame n as the step's axes /// place it, carrying the step's record; `file` holds frames 0…n − 1. /// /// The flap opens on the opening crease: `openOn`, or the named spine crease. Both are folded flat. /// The paper is cut along every edge on either crease's line in `before`, and, with `openOn`, along /// the creases of the earlier reverse fold that opened on `openOn` and whose flap holds this /// step's. Of the opening crease's line, the edges whose faces then fall on different sides are /// kept; of the spine's, those whose faces fall on different sides of the two lines alone, the /// paper's halves. Each kept edge is folded flat or flat; a flat one is a bend line, which bends /// while the flap is open and is never creased. The side of the opening crease nearer the viewpoint /// opens, with the earlier fold's flap: the open axes are a tree grown from the other faces across /// the kept edges, the opening crease first and driven from ±180 to ±`openAngle`, the earlier /// fold's creases and the spine solved to keep the paper whole. The pop and close move on a tree /// cut along those edges and the step's creases, grown from the faces neither the opening nor the /// step moves, the opening crease first. In `popped` the opening crease and the spine's edges in /// the flap are held as the open phase leaves them, the latter reversed, and the other tree axes /// are solved, starting where the open phase leaves them or `openAngle / 180` of their way. The /// close axes drive the opening crease back to ±180 and solve the rest, as for a rigid step, and /// must arrive at `after`'s coordinates. The record's `spine` holds the kept edges of both lines. /// /// The starting guess can lead the solver to another branch of the vertex's motion. Closing the /// loops does not catch that: every branch is closed. A branch is caught when the close does not /// reach `after`'s coordinates, when it leaves a crease of the last frame assigned against the /// crease pattern, or when frame n breaks the validator's layer-order rules; the reverse fixtures' /// tests that the tip lands between the flap's layers cover them. `layerMotionDefects` does not /// add a check here: frame n's orders for the faces the step's axes move are guessed from the same /// close, read near the same moment. /// /// - Throws: `unresolvedCrease` when the spine or `openOn` names no edge, `invalidSpine` when one /// of them is not folded flat or a kept edge is neither folded flat nor flat, `noRigidMotion` /// when the flap cannot open, `popped` does not close or the close does not reach `after`, and /// `popTooStrained` when the pop's strain exceeds 10%, `noEarlierOpening` when no earlier reverse /// fold holding the flap opened on `openOn`. public func compilePop(step n: Int, script: ScriptStep, before: FoldFrame, after: FoldFrame, file: FoldFile) throws -> PopRecord { guard let reference = script.spine, let record = after.step else { preconditionFailure("compilePop needs a script step with a spine and a frame with its record") } let edgeFaces = edgesFaces(file) let faceCount = file.facesVertices.count let tolerance = sheetExtent(file) * relativeTolerance let openAngle = script.openAngle ?? defaultOpenAngle func foldedFlat(_ e: Int) -> Bool { abs(abs(before.edgesFoldAngle[e]) - 180) <= angleSnapTolerance } func edge(_ ref: CreaseRef) throws -> Int { guard let e = resolve(ref, file, edgeFaces) else { throw CompileError.unresolvedCrease(step: n, crease: ref) } guard foldedFlat(e) else { throw CompileError.invalidSpine(step: n) } return e } let named = try edge(reference) let opener = try script.openOn.map(edge) ?? named var group = Array(repeating: -1, count: faceCount) for (a, axis) in record.axes.enumerated() { for f in axis.movingFaces { group[f] = a } } let moving = group.map { $0 >= 0 } let creased = edgeFaces.indices.filter { edgeFaces[$0].count == 2 && group[edgeFaces[$0][0]] != group[edgeFaces[$0][1]] } // the earlier reverse fold this step's flap is in, which opened on the opening crease let tip = Set((0.. Bool { sides[edgeFaces[e][0]] != sides[edgeFaces[e][1]] } let openLine = openerLine.filter(across) // the spine joins the paper's two halves, split by the two lines alone: an edge on the spine's // line inside the earlier fold's flap can be cut off by its creases yet join layers of one half let halves = regions(cut: Set(openerLine + spineLine), file, edgeFaces) let spine = spineLine.filter { halves[edgeFaces[$0][0]] != halves[edgeFaces[$0][1]] } guard (openLine + spine).allSatisfy({ foldedFlat($0) || abs(before.edgesFoldAngle[$0]) <= angleSnapTolerance }) else { throw CompileError.invalidSpine(step: n) } let tipSpine = Set(spine.filter { edgeFaces[$0].allSatisfy(tip.contains) }) // the layer nearer the viewer opens: of the opening crease's faces, the one a valley puts on // the first face's normal side, or a mountain on the other let (f, g) = (edgeFaces[opener][0], edgeFaces[opener][1]) let normals = faceNormals(before, file) let gNearer = (before.edgesFoldAngle[opener] > 0) == (dot(normals[f], record.viewpoint.eye) > 0) let (near, far) = gNearer ? (g, f) : (f, g) guard sides[far] != sides[near], !earlierFlap.contains(far) else { throw CompileError.noRigidMotion(step: n) } let opening = Set((0.. 0 ? 1.0 : -1.0 let openAxes = try openingAxes(n, openTree, end: openSign * openAngle, before: before, record, file) let opened = try openEndAngles(n, openAxes, edges: openEdges, before: before, record, file) // the tree the pop and the close move on let fixed = Set((0.. Double { opened[e] == nil ? after.edgesFoldAngle[e] : (tipSpine.contains(e) ? -1 : 1) * before.edgesFoldAngle[e] } var guess: [Int: Double] = [:] for axis in tree.axes { let start = before.edgesFoldAngle[axis.edge] guess[axis.edge] = opened[axis.edge].map { tipSpine.contains(axis.edge) ? -$0 : $0 } ?? start + (closed(axis.edge) - start) * openAngle / 180 } let popped = try solvedPose(n, tree, from: before, angles: guess, holding: Set(openLine).union(tipSpine), record, file) var poppedFrame = before poppedFrame.verticesCoords = popped.positions let closeAxes = try closing(n, tree, from: poppedFrame, start: popped.angles, end: closed, record, file) let pop = PopRecord(spine: unique(spine + openLine), openAngle: openAngle, phases: phases, openAxes: openAxes, popped: popped.positions, closeAxes: closeAxes) var draft = file draft.frames.append(FoldFrame(verticesCoords: after.verticesCoords, edgesAssignment: after.edgesAssignment, edgesFoldAngle: after.edgesFoldAngle, faceOrders: [], step: withPop(record, pop))) let interpolator = FoldInterpolator(file: draft, step: try readStep(n, in: draft)) guard zip(interpolator.positions(at: 1), after.verticesCoords).allSatisfy({ simd_distance($0, $1) <= tolerance }) else { throw CompileError.noRigidMotion(step: n) } let worst = (0...popSamples).map { k in let t = phases[0] + Double(k) / Double(popSamples) * (phases[1] - phases[0]) return strain(interpolator.meshPositions(at: t), mesh: interpolator.mesh) }.max() ?? 0 guard worst <= strainBound else { throw CompileError.popTooStrained(step: n, strain: worst) } return pop } /// `edges` without repeats, in order. private func unique(_ edges: [Int]) -> [Int] { var seen = Set() return edges.filter { seen.insert($0).inserted } } /// The open axes on `[0, phases[0]]`: the tree's first axis, the opening crease, linear from its /// angle in `before` to `end`; the axes on a loop's cycle solved so the loops close, continued /// from `before` along the window to find where they end and then solved as for a rigid step; the /// rest held. private func openingAxes(_ n: Int, _ tree: RegionTree, end: Double, before: FoldFrame, _ record: StepRecord, _ file: FoldFile) throws -> [AxisRecord] { let opener = tree.axes[0].edge func draft(_ ends: [Int: Double]) -> (StepRecord, FoldFile) { let axes = records(tree, start: { before.edgesFoldAngle[$0] }, end: { ends[$0] ?? before.edgesFoldAngle[$0] }, window: [0, phases[0]]) let open = withAxes(record, axes) var draft = file draft.frames.append(FoldFrame(verticesCoords: before.verticesCoords, edgesAssignment: before.edgesAssignment, edgesFoldAngle: before.edgesFoldAngle, faceOrders: [], step: open)) return (open, draft) } let (held, heldFile) = draft([opener: end]) guard !tree.loops.isEmpty else { return held.axes } let step = try readStep(n, in: heldFile) let driver = step.axes.firstIndex { $0.edge == opener }! let free = axesOnCycles(step, loops: tree.loops, heldFile).subtracting([driver]).sorted() guard !free.isEmpty else { return held.axes } let kinematics = LoopKinematics(step: step, file: heldFile) let tolerance = sheetExtent(file) * relativeTolerance var previous = step.axes.map(\.startAngle), angles = previous for k in 1...angleSamples { var guess = zip(angles, previous).map { 2 * $0 - $1 } guess[driver] = step.axes[driver].startAngle + Double(k) / Double(angleSamples) * (end - step.axes[driver].startAngle) guard kinematics.solve(&guess, free: free) <= tolerance else { throw CompileError.noRigidMotion(step: n) } (previous, angles) = (angles, guess) } let (open, openFile) = draft(Dictionary(uniqueKeysWithValues: zip(step.axes.map(\.edge), angles))) let solved = try solveLoops(n, open, try readStep(n, in: openFile), loops: tree.loops, openFile) var solvedFile = openFile solvedFile.frames[n].step = solved try checkClosure(n, try readStep(n, in: solvedFile), driver: opener, solvedFile, solved: solved.axes.contains { $0.angles != nil }) return solved.axes } /// `named` and every other interior edge on its line in `frame`. private func onLine(_ named: Int, _ frame: FoldFrame, _ file: FoldFile, _ edgeFaces: [[Int]], _ tolerance: Double) -> [Int] { let ends = file.edgesVertices[named].map { frame.verticesCoords[$0] } return [named] + edgeFaces.indices.filter { e in e != named && edgeFaces[e].count == 2 && file.edgesVertices[e].allSatisfy { onLine(frame.verticesCoords[$0], ends[0], ends[1], tolerance) } } } /// The fold angle of each of `edges` where `openAxes` leave the paper at the end of the open /// phase, measured from the faces' normals along it and unwrapped from `before`'s angle. private func openEndAngles(_ n: Int, _ openAxes: [AxisRecord], edges: [Int], before: FoldFrame, _ record: StepRecord, _ file: FoldFile) throws -> [Int: Double] { var draft = file draft.frames.append(FoldFrame(verticesCoords: before.verticesCoords, edgesAssignment: before.edgesAssignment, edgesFoldAngle: before.edgesFoldAngle, faceOrders: [], step: withAxes(record, openAxes))) let interpolator = FoldInterpolator(file: draft, step: try readStep(n, in: draft)) let edgeFaces = edgesFaces(file) var current = Dictionary(uniqueKeysWithValues: edges.map { ($0, before.edgesFoldAngle[$0]) }) for k in 1...angleSamples { let positions = interpolator.positions(at: phases[0] * Double(k) / Double(angleSamples)) let normals = faceNormals(positions: positions, faces: file.facesVertices) for e in edges { let measured = dihedral(e, edgeFaces[e], positions, normals, file) current[e] = measured + 360 * ((current[e]! - measured) / 360).rounded() } } for axis in openAxes { current[axis.edge] = axis.endAngle } return current } /// `record`, flagged non-rigid, with `pop`. func withPop(_ record: StepRecord, _ pop: PopRecord) -> StepRecord { StepRecord(kind: record.kind, technique: record.technique, instruction: record.instruction, axes: record.axes, rotateDegrees: record.rotateDegrees, turnOverAxis: record.turnOverAxis, repeatOf: record.repeatOf, nonRigid: true, pop: pop, viewpoint: record.viewpoint) } /// The fold angle at the end of a non-rigid step of every edge its close axes crease, measured /// from the faces' normals along the open phase, at `popped` and along the close phase, unwrapped /// from frame n − 1's angle and taken to be ±180 or 0 when within 1e-6° of one. A close axis's /// edge ends at its end angle exactly. func popEndAngles(_ step: FoldStep, _ interpolator: FoldInterpolator, previous: FoldFrame, file: FoldFile) -> [Int: Double] { guard let pop = step.pop else { return [:] } let edgeFaces = edgesFaces(file) var axisOfFace = Array(repeating: -1, count: file.facesVertices.count) for (a, axis) in pop.closeAxes.enumerated() { for f in axis.movingFaces { axisOfFace[f] = a } } let edges = edgeFaces.indices.filter { edgeFaces[$0].count == 2 && axisOfFace[edgeFaces[$0][0]] != axisOfFace[edgeFaces[$0][1]] } let (lower, upper) = (pop.phases.lowerBound, pop.phases.upperBound) let times = (1...angleSamples).map { lower * Double($0) / Double(angleSamples) } + [upper] + (1...angleSamples).map { upper + (1 - upper) * Double($0) / Double(angleSamples) } var current = Dictionary(uniqueKeysWithValues: edges.map { ($0, previous.edgesFoldAngle[$0]) }) for t in times { let positions = interpolator.positions(at: t) let normals = faceNormals(positions: positions, faces: file.facesVertices) for e in edges { let measured = dihedral(e, edgeFaces[e], positions, normals, file) current[e] = measured + 360 * ((current[e]! - measured) / 360).rounded() } } for (e, angle) in current { current[e] = [180, -180, 0].first { abs(angle - $0) <= angleSnapTolerance } ?? angle } for axis in pop.closeAxes { current[axis.edge] = axis.endAngle } return current } /// A tree of regions over the faces: the faces connected across edges not in `order`, grown from /// the regions holding a `fixed` face across the edges in `order`. Each tree edge is an axis /// moving its child region's faces; each other edge of `order` between different regions closes /// a loop. private struct RegionTree { var axes: [(edge: Int, movingFaces: [Int], parent: Int?)] var loops: [Int] } private func growTree(order: [Int], fixed: Set, _ file: FoldFile, _ edgeFaces: [[Int]]) -> RegionTree { let region = regions(cut: Set(order), file, edgeFaces) let regionCount = (region.max() ?? -1) + 1 var node = Array(repeating: -1, count: regionCount) for f in fixed { node[region[f]] = 0 } var nodeCount = 1 for r in 0.. Int { var x = x while component[x] != x { x = component[x] } return x } var links: [(edge: Int, ends: (Int, Int))] = [] var loops: [Int] = [] for e in order { let a = nodeOfFace[edgeFaces[e][0]], b = nodeOfFace[edgeFaces[e][1]] guard a != b else { continue } if find(a) != find(b) { component[find(a)] = find(b) links.append((e, (a, b))) } else { loops.append(e) } } var parentNode = Array(repeating: nil, count: nodeCount) var linkOfNode = Array(repeating: nil, count: nodeCount) var reached: Set = [0] var queue = [0] while !queue.isEmpty { let a = queue.removeFirst() for (k, link) in links.enumerated() where link.ends.0 == a || link.ends.1 == a { let b = link.ends.0 == a ? link.ends.1 : link.ends.0 guard reached.insert(b).inserted else { continue } parentNode[b] = a linkOfNode[b] = k queue.append(b) } } let axes = links.enumerated().map { k, link in let child = linkOfNode[link.ends.0] == k ? link.ends.0 : link.ends.1 return (edge: link.edge, movingFaces: nodeOfFace.indices.filter { nodeOfFace[$0] == child }, parent: parentNode[child].flatMap { linkOfNode[$0] }) } return RegionTree(axes: axes, loops: loops) } /// The region of each face: faces connected across interior edges not in `cut`. private func regions(cut: Set, _ file: FoldFile, _ edgeFaces: [[Int]]) -> [Int] { var region = Array(repeating: -1, count: file.facesVertices.count) var count = 0 for seed in region.indices where region[seed] < 0 { region[seed] = count var stack = [seed] while let f = stack.popLast() { for (e, faces) in edgeFaces.enumerated() where faces.count == 2 && faces.contains(f) && !cut.contains(e) { let g = faces[0] == f ? faces[1] : faces[0] if region[g] < 0 { region[g] = count stack.append(g) } } } count += 1 } return region } /// The tree's axes as records from `start` angles to `end` angles, on `window`. private func records(_ tree: RegionTree, start: (Int) -> Double, end: (Int) -> Double, window: [Double]?) -> [AxisRecord] { tree.axes.map { axis in AxisRecord(edge: axis.edge, movingFaces: axis.movingFaces, startAngle: start(axis.edge), endAngle: end(axis.edge), parent: axis.parent, window: window) } } /// `record` with `axes` in place of its own. private func withAxes(_ record: StepRecord, _ axes: [AxisRecord]) -> StepRecord { StepRecord(kind: .fold, technique: record.technique, instruction: record.instruction, axes: axes, viewpoint: record.viewpoint) } /// The pose with the tree's axes at `angles`, the edges in `holding` held there and the axes on a /// loop's cycle solved so the loops close. Returns the vertex positions and the solved angles. private func solvedPose(_ n: Int, _ tree: RegionTree, from before: FoldFrame, angles: [Int: Double], holding: Set, _ record: StepRecord, _ file: FoldFile) throws -> (positions: [SIMD3], angles: [Int: Double]) { func draft(_ angles: [Int: Double]) -> FoldFile { var draft = file draft.frames.append(FoldFrame(verticesCoords: before.verticesCoords, edgesAssignment: before.edgesAssignment, edgesFoldAngle: before.edgesFoldAngle, faceOrders: [], step: withAxes(record, records(tree, start: { before.edgesFoldAngle[$0] }, end: { angles[$0]! }, window: nil)))) return draft } var solved = angles let first = draft(angles) let step = try readStep(n, in: first) let free = axesOnCycles(step, loops: tree.loops, first).filter { !holding.contains(step.axes[$0].edge) }.sorted() var values = step.axes.map(\.endAngle) let tolerance = sheetExtent(file) * relativeTolerance guard LoopKinematics(step: step, file: first).solve(&values, free: free) <= tolerance else { throw CompileError.noRigidMotion(step: n) } for (a, axis) in step.axes.enumerated() { solved[axis.edge] = values[a] } let last = draft(solved) return (FoldInterpolator(file: last, step: try readStep(n, in: last)).positions(at: 1), solved) } /// The close axes from `popped`: the named spine edge, first in the tree, linear from its popped /// angle to its end; the axes on a loop's cycle solved as for a rigid step; all on /// `[phases[1], 1]`. private func closing(_ n: Int, _ tree: RegionTree, from popped: FoldFrame, start: [Int: Double], end: (Int) -> Double, _ record: StepRecord, _ file: FoldFile) throws -> [AxisRecord] { var draft = file draft.frames[n - 1] = popped var close = withAxes(record, records(tree, start: { start[$0]! }, end: end, window: [phases[1], 1])) draft.frames.append(FoldFrame(verticesCoords: popped.verticesCoords, edgesAssignment: popped.edgesAssignment, edgesFoldAngle: popped.edgesFoldAngle, faceOrders: [], step: close)) var step = try readStep(n, in: draft) guard !tree.loops.isEmpty else { return close.axes } close = try solveLoops(n, close, step, loops: tree.loops, draft) draft.frames[n].step = close step = try readStep(n, in: draft) try checkClosure(n, step, driver: close.axes[0].edge, draft, solved: close.axes.contains { $0.angles != nil }) return close.axes }