Packages/FoldKit/Sources/Folding/StepReader.swift

00ea029d0652da12d0f4237769e7020b72cfa7f3
fold/Packages/FoldKit/Sources/Folding/StepReader.swift history · blame · raw

131 lines · 6165 bytes

6 symbols in this file
  1import FoldFormat
  2import simd
  3
  4/// Reads every frame's authored `krz:step`. `result[k]` is step `k + 1`.
  5///
  6/// - Precondition: `validate(file)` is empty. On a file it rejects, this may trap on an
  7///   out-of-range index.
  8public func readSteps(_ file: FoldFile) throws -> [FoldStep] {
  9    try file.frames.indices.dropFirst().map { n in try readStep(n, in: file) }
 10}
 11
 12/// Reads step `n` from frame n's `krz:step`, directing its axes against frame n − 1's
 13/// coordinates. Only frames 0…n are read, so frames after n need not exist.
 14///
 15/// - Precondition: frames 0…n are well formed: frame n − 1 has a coordinate for every vertex
 16///   and the topology's indices are in range.
 17public func readStep(_ n: Int, in file: FoldFile) throws -> FoldStep {
 18    guard let record = file.frames[n].step else { throw FoldError.missingStepRecord(step: n) }
 19    return try readStep(n, record, file, edgesFaces(file))
 20}
 21
 22private func readStep(_ n: Int, _ record: StepRecord, _ file: FoldFile, _ edgeFaces: [[Int]]) throws -> FoldStep {
 23    guard let instruction = record.instruction, !instruction.allSatisfy(\.isWhitespace) else {
 24        throw StepError.missingInstruction(step: n)
 25    }
 26    if record.kind == .rotate && record.rotateDegrees == nil {
 27        throw StepError.rotateWithoutDegrees(step: n)
 28    }
 29    if record.kind == .turnOver && record.turnOverAxis == nil {
 30        throw StepError.turnOverWithoutAxis(step: n)
 31    }
 32    if record.kind == .foldAndUnfold && record.axes.contains(where: { $0.peakAngle == nil }) {
 33        throw StepError.foldAndUnfoldWithoutPeak(step: n)
 34    }
 35    if record.kind == .foldAndUnfold && record.axes.contains(where: { $0.endAngle != $0.startAngle }) {
 36        throw StepError.foldAndUnfoldDoesNotReturn(step: n)
 37    }
 38    if record.nonRigid && record.pop == nil {
 39        throw StepError.nonRigidWithoutPop(step: n)
 40    }
 41
 42    let start = file.frames[n - 1].verticesCoords
 43    let axes = try readAxes(record.axes, step: n, points: start, file, edgeFaces)
 44
 45    var pop: Pop?
 46    if let p = record.pop {
 47        guard p.phases.count == 2, 0 < p.phases[0], p.phases[0] < p.phases[1], p.phases[1] < 1 else {
 48            throw StepError.popPhasesOutOfOrder(step: n)
 49        }
 50        pop = Pop(spine: p.spine, openAngle: p.openAngle, phases: p.phases[0]...p.phases[1],
 51                  openAxes: try readAxes(p.openAxes, step: n, points: start, file, edgeFaces),
 52                  popped: p.popped,
 53                  closeAxes: try readAxes(p.closeAxes, step: n, points: p.popped, file, edgeFaces))
 54    }
 55
 56    return FoldStep(index: n, kind: record.kind, technique: record.technique, instruction: instruction,
 57                    axes: axes, rotateDegrees: record.rotateDegrees, turnOverAxis: record.turnOverAxis,
 58                    repeatOf: record.repeatOf, nonRigid: record.nonRigid, pop: pop,
 59                    viewpoint: record.viewpoint)
 60}
 61
 62/// One step's axes, directed against `points`, reordered so every parent precedes its children.
 63private func readAxes(_ records: [AxisRecord], step n: Int, points: [SIMD3<Double>], _ file: FoldFile,
 64                      _ edgeFaces: [[Int]]) throws -> [FoldAxis] {
 65    var lines: [(origin: SIMD3<Double>, direction: SIMD3<Double>)] = []
 66    var moved = Set<Int>()
 67    for r in records {
 68        guard file.edgesVertices.indices.contains(r.edge) else {
 69            throw StepError.axisNotAnEdge(step: n, edge: r.edge)
 70        }
 71        guard r.movingFaces.allSatisfy(file.facesVertices.indices.contains) else {
 72            throw StepError.movingFacesOutOfRange(step: n)
 73        }
 74        let sides = edgeFaces[r.edge]
 75        let movingSides = sides.filter(r.movingFaces.contains)
 76        guard sides.count == 2, movingSides.count == 1 else {
 77            throw StepError.axisNotOnMovingSetBoundary(step: n, edge: r.edge)
 78        }
 79        let window = r.window ?? [0, 1]
 80        guard window.count == 2, 0 <= window[0], window[0] < window[1], window[1] <= 1 else {
 81            throw StepError.axisWindowOutOfRange(step: n)
 82        }
 83        if let curve = r.angles, curve.count < 2 {
 84            throw StepError.curveTooShort(step: n)
 85        }
 86        let faceSet = Set(r.movingFaces)
 87        guard moved.isDisjoint(with: faceSet) else {
 88            throw StepError.overlappingMovingSetsWithinAStep(step: n)
 89        }
 90        moved.formUnion(faceSet)
 91        lines.append(traversal(of: file.edgesVertices[r.edge], by: file.facesVertices[movingSides[0]], points))
 92    }
 93
 94    // place each axis after its parent, keeping the authored order otherwise
 95    var state = Array(repeating: 0, count: records.count) // 0 unplaced, 1 placing, 2 placed
 96    var order: [Int] = []
 97    func place(_ i: Int) throws {
 98        if state[i] == 2 { return }
 99        guard state[i] == 0 else { throw StepError.axisParentCycle(step: n) }
100        state[i] = 1
101        if let p = records[i].parent {
102            guard records.indices.contains(p) else { throw StepError.axisParentCycle(step: n) }
103            try place(p)
104        }
105        state[i] = 2
106        order.append(i)
107    }
108    for i in records.indices { try place(i) }
109
110    var position = Array(repeating: 0, count: records.count)
111    for (k, i) in order.enumerated() { position[i] = k }
112    return order.map { i in
113        let r = records[i]
114        let window = r.window ?? [0, 1]
115        return FoldAxis(edge: r.edge, origin: lines[i].origin, direction: lines[i].direction,
116                        movingFaces: Set(r.movingFaces), startAngle: r.startAngle, endAngle: r.endAngle,
117                        peakAngle: r.peakAngle, parent: r.parent.map { position[$0] },
118                        window: window[0]...window[1], curve: r.angles)
119    }
120}
121
122/// The edge as `face` traverses it in `faces_vertices` order: the corner it leaves from and the
123/// unit direction toward the next.
124private func traversal(of edge: [Int], by face: [Int], _ points: [SIMD3<Double>])
125    -> (origin: SIMD3<Double>, direction: SIMD3<Double>) {
126    let i = face.indices.first { i in
127        Set([face[i], face[(i + 1) % face.count]]) == Set(edge)
128    }!
129    let origin = points[face[i]]
130    return (origin, normalize(points[face[(i + 1) % face.count]] - origin))
131}