import FoldFormat import Folding import simd public enum DiagramLine: Equatable, Sendable { /// `B` edges and creases folded in the drawn frame. case solid /// Creases made in an earlier step and flat again. case light /// The step's valley, as seen. case dashed /// The step's mountain, as seen. case dashDot } /// A diagram symbol in screen coordinates, the drawn frame projected along the step's viewpoint /// in the sheet's units. A fold arrow curves from `from`, a point of the moving set before the /// step, through `over`, the apex of its arc, to `to`, the same point after the fold (at the peak /// for a fold-and-unfold). public enum DiagramArrow: Equatable, Sendable { case valleyFold(from: SIMD2, over: SIMD2, to: SIMD2) case mountainFold(from: SIMD2, over: SIMD2, to: SIMD2) case foldAndUnfold(from: SIMD2, over: SIMD2, to: SIMD2, mountain: Bool) /// A crease folded before the step opened out again. case unfold(from: SIMD2, over: SIMD2, to: SIMD2) /// The technique's symbol at the midpoint of the step's first crease, pointing toward where /// that axis's moving set ends. case technique(StepTechnique, at: SIMD2, toward: SIMD2) case turnOver(TurnOverAxis) /// Counterclockwise as seen when positive. case rotate(degrees: Double) /// The step repeats step `of`. case repeatMark(of: Int) } /// A visible piece of FOLD edge `edge`, in the arrows' screen coordinates. public struct DiagramEdge: Equatable, Sendable { public let edge: Int public let from: SIMD2 public let to: SIMD2 public let style: DiagramLine public init(edge: Int, from: SIMD2, to: SIMD2, style: DiagramLine) { self.edge = edge self.from = from self.to = to self.style = style } } /// Edges in FOLD edge order. public struct Diagram: Equatable, Sendable { public let edges: [DiagramEdge] public let arrows: [DiagramArrow] public init(edges: [DiagramEdge], arrows: [DiagramArrow]) { self.edges = edges self.arrows = arrows } } /// The arc's apex lies this fraction of the chord from the chord's midpoint. private let arcBulge = 0.3 /// The diagram for step `step.index`: frame `step.index − 1` seen orthographically from the /// step's viewpoint, with the step's creases and symbols. /// /// Edges whose `edges_krz:firstCreasedAtStep` is later than the step, and subdivision edges, are /// not drawn. An edge the step creases (its two faces move differently) is dashed for a valley as /// seen and dash-dot for a mountain, whatever its assignment, unless it is folded in the drawn /// frame; `B` edges and folded creases are solid; earlier creases flat again are light. An axis /// that moves toward flat gets the unfold arrow. Each edge is clipped by `visibleSegments`, and /// a piece coincident with one already drawn is drawn once, step creases before solid before light. /// /// - Precondition: `validate(file)` is empty. public func buildDiagram(file: FoldFile, step: FoldStep) -> Diagram { let n = step.index let frame = file.frames[n - 1] let normals = faceNormals(frame, file) // a validated frame's orders have no cycle let order = try! LayerOrder(faceOrders: frame.faceOrders, normals: normals) let occlusion = Occlusion(frame: frame, file: file, order: order, viewpoint: step.viewpoint) let eye = step.viewpoint.eye let valley = step.axes.map { axis -> Bool in let face = occlusion.edgeFaces[axis.edge].first { axis.movingFaces.contains($0) }! let turn = (step.kind == .foldAndUnfold ? axis.peakAngle ?? axis.endAngle : axis.endAngle) - axis.startAngle return turn * dot(normals[face], eye) > 0 } let creasing = creasingAxes(step, faceCount: file.facesVertices.count, edgeFaces: occlusion.edgeFaces) var candidates: [(edge: Int, style: DiagramLine, rank: Int)] = [] for e in file.edgesVertices.indices { let created = file.edgesFirstCreasedAtStep[e] if let created, created > n { continue } if frame.edgesAssignment[e] == .boundary { candidates.append((e, .solid, 1)) } else if created == nil { continue } else if let axis = creasing[e], abs(frame.edgesFoldAngle[e]) <= 1e-9 { candidates.append((e, valley[axis] ? .dashed : .dashDot, 0)) } else if abs(frame.edgesFoldAngle[e]) > 1e-9 { candidates.append((e, .solid, 1)) } else if created! < n { candidates.append((e, .light, 2)) } } candidates.sort { ($0.rank, $0.edge) < ($1.rank, $1.edge) } var drawn: [DiagramEdge] = [] for c in candidates { for (a, b) in occlusion.visibleSegments(of: c.edge) { for (p, q) in uncovered(a, b, by: drawn, tolerance: occlusion.tolerance) { drawn.append(DiagramEdge(edge: c.edge, from: p, to: q, style: c.style)) } } } let edges = drawn.enumerated().sorted { ($0.element.edge, $0.offset) < ($1.element.edge, $1.offset) }.map(\.element) let symbols = arrows(file, step, valley: valley, project: ViewProjection(step.viewpoint), edgeFaces: occlusion.edgeFaces) return Diagram(edges: edges, arrows: symbols) } /// For each edge, the index in `step.axes` of the axis whose motion creases it, or nil. Each face /// belongs to the axis whose moving set holds it, or to the fixed group; an edge is creased when /// its faces' groups differ, by the deeper group's axis. private func creasingAxes(_ step: FoldStep, faceCount: Int, edgeFaces: [[Int]]) -> [Int?] { var group = Array(repeating: nil, count: faceCount) for (i, axis) in step.axes.enumerated() { for f in axis.movingFaces { group[f] = i } } func depth(_ axis: Int?) -> Int { guard let axis else { return -1 } return 1 + depth(step.axes[axis].parent) } return edgeFaces.map { faces in guard faces.count == 2, group[faces[0]] != group[faces[1]] else { return nil } let (a, b) = (group[faces[0]], group[faces[1]]) return depth(a) >= depth(b) ? a : b } } /// The parts of `a`–`b` not lying along an edge already drawn. private func uncovered(_ a: SIMD2, _ b: SIMD2, by drawn: [DiagramEdge], tolerance: Double) -> [(SIMD2, SIMD2)] { let d = b - a, length2 = length_squared(d) let normal = normalize(SIMD2(-d.y, d.x)) var covered: [ClosedRange] = [] for e in drawn where abs(dot(e.from - a, normal)) <= tolerance && abs(dot(e.to - a, normal)) <= tolerance { let s = dot(e.from - a, d) / length2, t = dot(e.to - a, d) / length2 let low = max(min(s, t), 0), high = min(max(s, t), 1) if high > low { covered.append(low...high) } } var pieces: [ClosedRange] = [] var start = 0.0 for range in covered.sorted(by: { $0.lowerBound < $1.lowerBound }) { if range.lowerBound > start { pieces.append(start...range.lowerBound) } start = max(start, range.upperBound) } if start < 1 { pieces.append(start...1) } let minimum = tolerance / length2.squareRoot() return pieces.filter { $0.upperBound - $0.lowerBound > minimum } .map { (a + $0.lowerBound * d, a + $0.upperBound * d) } } private func arrows(_ file: FoldFile, _ step: FoldStep, valley: [Bool], project: ViewProjection, edgeFaces: [[Int]]) -> [DiagramArrow] { var arrows: [DiagramArrow] = [] let start = file.frames[step.index - 1].verticesCoords switch step.kind { case .turnOver: if let axis = step.turnOverAxis { arrows.append(.turnOver(axis)) } case .rotate: if let degrees = step.rotateDegrees { arrows.append(.rotate(degrees: degrees)) } case .fold, .foldAndUnfold: let interpolator = step.kind == .foldAndUnfold ? FoldInterpolator(file: file, step: step) : nil // a point of the axis's moving set and where it is at the end of the step, or at the peak func track(_ axis: FoldAxis, _ point: SIMD3) -> (SIMD2, SIMD2) { let end = interpolator?.positions(at: (axis.window.lowerBound + axis.window.upperBound) / 2) ?? file.frames[step.index].verticesCoords let face = edgeFaces[axis.edge].first { axis.movingFaces.contains($0) }! return (project(point), project(carried(point, with: file.facesVertices[face], from: start, to: end))) } if step.technique != .plain { guard let axis = step.axes.first else { break } let ends = file.edgesVertices[axis.edge].map { project(start[$0]) } let toward = track(axis, centroid(of: axis.movingFaces, file, positions: start)).1 arrows.append(.technique(step.technique, at: (ends[0] + ends[1]) / 2, toward: toward)) break } // simultaneous arrows are spread along their creases, in one screen direction, so that // they do not meet let count = Double(step.axes.count) for (i, axis) in step.axes.enumerated() { let ends = file.edgesVertices[axis.edge].map { start[$0] } let shift = (Double(i) - (count - 1) / 2) / (count + 1) * distance(ends[0], ends[1]) let along = project(axis.direction) let sign = along.y < -1e-9 || (abs(along.y) <= 1e-9 && along.x < 0) ? -1.0 : 1.0 let point = centroid(of: axis.movingFaces, file, positions: start) + sign * shift * axis.direction let (from, to) = track(axis, point) let over = apex(from, to) if step.kind == .foldAndUnfold { arrows.append(.foldAndUnfold(from: from, over: over, to: to, mountain: !valley[i])) } else if abs(axis.endAngle) < abs(axis.startAngle) - 1e-9 { arrows.append(.unfold(from: from, over: over, to: to)) } else if valley[i] { arrows.append(.valleyFold(from: from, over: over, to: to)) } else { arrows.append(.mountainFold(from: from, over: over, to: to)) } } } if let repeated = step.repeatOf { arrows.append(.repeatMark(of: repeated)) } return arrows } /// The area-weighted mean of the faces' vertex means. private func centroid(of faces: Set, _ file: FoldFile, positions: [SIMD3]) -> SIMD3 { var sum = SIMD3.zero, total = 0.0 for f in faces.sorted() { let corners = file.facesVertices[f].map { positions[$0] } let area = length(corners.indices.reduce(SIMD3.zero) { s, i in s + simd.cross(corners[i], corners[(i + 1) % corners.count]) }) / 2 sum += area * corners.reduce(.zero, +) / Double(corners.count) total += area } return sum / total } /// `point` moved rigidly with the face whose corners are `corners`, from `start` to `end`. private func carried(_ point: SIMD3, with corners: [Int], from start: [SIMD3], to end: [SIMD3]) -> SIMD3 { let o = start[corners[0]], u = start[corners[1]] - o // the corner farthest from the line of the first two spans the face's plane best let spread = { (i: Int) in length(cross(u, start[corners[i]] - o)) } let k = corners.indices.dropFirst(2).max { spread($0) < spread($1) }! func basis(_ x: [SIMD3]) -> simd_double3x3 { let e1 = x[corners[1]] - x[corners[0]], e2 = x[corners[k]] - x[corners[0]] return simd_double3x3(columns: (e1, e2, normalize(cross(e1, e2)))) } return end[corners[0]] + basis(end) * (basis(start).inverse * (point - o)) } /// The apex of an arc from `from` to `to`, to the side of the chord toward screen-up, or toward /// screen-right for a vertical chord. private func apex(_ from: SIMD2, _ to: SIMD2) -> SIMD2 { let chord = to - from var side = SIMD2(-chord.y, chord.x) if side.y < -1e-12 * length(chord) || (abs(side.y) <= 1e-12 * length(chord) && side.x < 0) { side = -side } return (from + to) / 2 + arcBulge * side }