import FoldFormat import simd /// Maps a drag on the paper view to the fold parameter of a step, so the moving faces follow the /// finger. Screen points are UIKit's: origin top left, y down, in a viewport of `viewportSize`. /// /// The step is split into segments at the ends of every axis's window, at the middle of each /// window of a fold-and-unfold (its peak), and at a non-rigid step's phases. Within a segment the /// drag follows the area centroid of one axis's moving faces: of the axes whose window covers the /// segment, the one whose centroid travels furthest on screen, keeping the previous segment's /// axis on a tie. A non-rigid step's axes all count as covering every segment. The centroid is /// projected at the depth of the camera's target, so that a face nearing the eye as it lands flat /// does not overshoot its end on screen and leave t = 1 unreachable by a finger dragged past it. public struct FoldParameterMapping: Sendable { /// The drag's path at 129 evenly spaced values of t: the followed centroids, each segment's /// translated to begin where the segment before it ended. A segment along which no covering /// axis's centroid travels 8 points is instead a straight line down, `fallbackThrow` points per /// unit of t. public let path: [SIMD2] /// Whether every segment is a straight line down, so a drag cannot follow the fold anywhere. public let isDegenerate: Bool /// Where a drag is on the path: its parameter and the segment it is in. At a boundary `t` /// alone does not say which: a drag that reaches a boundary has crossed it. public struct Position: Sendable, Equatable { public let t: Double let segment: Int } /// The search polyline: `path`'s samples with the segment boundaries added. private let ts: [Double] private let points: [SIMD2] /// Index ranges of `ts`, one per segment, in order. private let segments: [ClosedRange] /// Per segment, whether a drag can cross back over its start: not at a fold-and-unfold's peak. private let reversible: [Bool] private static let samples = 129 private static let minimumLength = 8.0 /// Points dragged down for the whole step where a segment's path is under `minimumLength`: 160, /// or half the view's height when that is less. A stretch that starts in the upper half of the /// view then ends inside it; one that starts lower can run past its bottom edge, as the crane's /// head pop does on iPhone (it starts at y ≈ 316 of 362 points). Its direction stays down /// pending a check on a device (ruling R84). private let fallbackThrow: Double /// How much further, in points, another axis's centroid must travel to replace the previous /// segment's axis. private static let preference = 0.5 /// How far past the best point so far the search continues, in points. private static let slack = 8.0 /// How near the path's end, measured along it, a point counts as the end, in points. private static let endTolerance = 0.5 public init(file: FoldFile, step: FoldStep, camera: Camera, viewportSize: SIMD2) { fallbackThrow = min(160, viewportSize.y / 2) var followed: [(faces: [Int], window: ClosedRange)] var boundaries: Set = [0, 1], peaks: Set = [] if step.nonRigid, let pop = step.pop { followed = step.axes.map { (Array($0.movingFaces), 0...1) } boundaries.formUnion([pop.phases.lowerBound, pop.phases.upperBound]) } else { followed = step.axes.map { (Array($0.movingFaces), $0.window) } for w in step.axes.map(\.window) { boundaries.formUnion([w.lowerBound, w.upperBound]) if step.kind == .foldAndUnfold { peaks.insert((w.lowerBound + w.upperBound) / 2) } } } if followed.isEmpty { followed = [(Array(file.facesVertices.indices), 0...1)] } let bounds = boundaries.union(peaks).sorted() reversible = bounds.dropLast().map { $0 > 0 && !peaks.contains($0) } let n = Double(Self.samples - 1) let grid = (0...zero } var previous: Int? var fallbacks = 0 for segment in segments { func travel(_ c: Int) -> Double { segment.dropLast().reduce(0) { $0 + distance(screen[$1][c], screen[$1 + 1][c]) } } let (a, b) = (ts[segment.lowerBound], ts[segment.upperBound]) let covering = followed.indices.filter { followed[$0].window.lowerBound <= a && b <= followed[$0].window.upperBound } var choice: Int? for c in (previous.map { [$0] } ?? []) + covering where covering.contains(c) && travel(c) >= Self.minimumLength { if choice.map({ travel(c) > travel($0) + Self.preference }) ?? true { choice = c } } let start = segment.lowerBound == 0 ? screen[0][choice ?? 0] : points[segment.lowerBound] for i in segment { points[i] = choice.map { start + screen[i][$0] - screen[segment.lowerBound][$0] } ?? start + SIMD2(0, (ts[i] - a) * fallbackThrow) } if choice == nil { fallbacks += 1 } previous = choice ?? previous } self.points = points isDegenerate = fallbacks == segments.count path = grid.map { t in points[ts.firstIndex(of: t)!] } } /// The point of `path` at `t`. public func point(at t: Double) -> SIMD2 { let t = min(max(t, 0), 1) let i = min(ts.lastIndex { $0 <= t }!, ts.count - 2) let u = (t - ts[i]) / (ts[i + 1] - ts[i]) return points[i] + u * (points[i + 1] - points[i]) } /// The position at `t`, clamped to 0...1; at a boundary, in the later segment. public func position(at t: Double) -> Position { let t = min(max(t, 0), 1) return Position(t: t, segment: segments.lastIndex { ts[$0.lowerBound] <= t }!) } /// The parameter `position(grabbedAt:translation:current:)` gives from `position(at: current)`. public func parameter(grabbedAt: SIMD2, translation: SIMD2, current: Double) -> Double { position(grabbedAt: grabbedAt, translation: translation, current: position(at: current)).t } /// The position whose point of `path` is nearest `grabbedAt + translation`, where `grabbedAt` /// is `point(at:)` of t when the drag began. /// /// The search walks the path outward from `current` within its segment. It also searches the /// segment beyond a boundary when `current` is within one sample of the boundary, or when the /// nearest point is the boundary itself, so that the finger has reached it. A neighbour's point /// is taken only if strictly nearer. So where the path doubles back on screen at a boundary, a /// finger moving along the retraced stretch stays in the segment the drag is in, and changes /// segment only at the turnaround. A drag that reaches a boundary crosses it, so the next /// movement along a retraced stretch continues into the segment beyond. Boundaries are crossed /// both ways, except a fold-and-unfold's peak, which is crossed only forward. A point within /// half a point of the path's end, measured along the path, is the end. /// /// When the path is degenerate the drag's downward component advances the fold over /// `fallbackThrow` points from `current`, which is then the position when the drag began. public func position(grabbedAt: SIMD2, translation: SIMD2, current: Position) -> Position { if isDegenerate { return position(at: current.t + translation.y / fallbackThrow) } let target = grabbedAt + translation let s = current.segment // the polyline edge from point i to point i + 1 holding current var start = segments[s].lowerBound while start + 1 < segments[s].upperBound && ts[start + 1] <= current.t { start += 1 } let own = nearest(target, in: s, from: start, directions: [1, -1]) var best = own for direction in [1, -1] { let edge = direction > 0 ? segments[s].upperBound - 1 : segments[s].lowerBound + 1 var near = direction > 0 ? current.t >= ts[edge] : current.t <= ts[edge] var from = own while near || from.toBoundary(direction) == 0 { let n = from.segment + direction guard n >= 0 && n < segments.count && (direction > 0 || reversible[from.segment]) else { break } let candidate = nearest(target, in: n, from: direction > 0 ? segments[n].lowerBound : segments[n].upperBound - 1, directions: [direction]) guard candidate.distance < best.distance else { break } best = candidate from = candidate near = false } } if best.segment == segments.count - 1 && best.toBoundary(1) <= Self.endTolerance { return Position(t: 1, segment: best.segment) } let t = (1 - best.u) * ts[best.edge] + best.u * ts[best.edge + 1] var segment = best.segment if t != current.t { if best.toBoundary(1) == 0 && segment + 1 < segments.count { segment += 1 } else if best.toBoundary(-1) == 0 && reversible[segment] { segment -= 1 } } return Position(t: t, segment: segment) } /// A point of the search polyline: `u` of the way along edge `edge` of segment `segment`. private struct Nearest { let segment: Int let edge: Int let u: Double let distance: Double /// Distance along the path to the segment's end (`direction` 1) or start (−1). let toEnd: Double let toStart: Double func toBoundary(_ direction: Int) -> Double { direction > 0 ? toEnd : toStart } } /// The point of segment `s` nearest `target`, walking outward from edge `start` in each of /// `directions` until an edge is `slack` farther than the best so far. private func nearest(_ target: SIMD2, in s: Int, from start: Int, directions: [Int]) -> Nearest { let segment = segments[s] func onEdge(_ i: Int) -> (edge: Int, u: Double, distance: Double) { let a = points[i], d = points[i + 1] - points[i] let lengthSquared = dot(d, d) let u = lengthSquared > 0 ? min(max(dot(target - a, d) / lengthSquared, 0), 1) : 0 return (i, u, distance(a + u * d, target)) } var best = onEdge(start) for direction in directions { var i = start + direction while i >= segment.lowerBound && i < segment.upperBound { let candidate = onEdge(i) if candidate.distance < best.distance { best = candidate } else if candidate.distance > best.distance + Self.slack { break } i += direction } } let length = distance(points[best.edge], points[best.edge + 1]) var toEnd = (1 - best.u) * length, toStart = best.u * length for i in best.edge + 1 ..< segment.upperBound { toEnd += distance(points[i], points[i + 1]) } for i in segment.lowerBound ..< best.edge { toStart += distance(points[i], points[i + 1]) } return Nearest(segment: s, edge: best.edge, u: best.u, distance: best.distance, toEnd: toEnd, toStart: toStart) } } /// The area centroids of sets of faces. private struct Centroids { /// Per set, fan triangles of its faces with their areas in frame 0. let triangles: [[(SIMD3, Double)]] init(file: FoldFile, sets: [[Int]]) { let flat = file.frames[0].verticesCoords triangles = sets.map { faces in faces.flatMap { f in let face = file.facesVertices[f] return (1..]) -> [SIMD3] { triangles.map { set in var sum = SIMD3.zero, area = 0.0 for (v, a) in set { sum += a * (positions[v.x] + positions[v.y] + positions[v.z]) / 3 area += a } return sum / area } } } /// Projects to screen points at the depth of the camera's target. private struct Projection { let viewProjection: simd_double4x4 /// Clip-space w of the camera's target. let depth: Double let viewportSize: SIMD2 init(camera: Camera, viewportSize: SIMD2) { viewProjection = camera.viewProjection(aspect: viewportSize.x / viewportSize.y) depth = (viewProjection * SIMD4(camera.target, 1)).w self.viewportSize = viewportSize } func point(_ p: SIMD3) -> SIMD2 { let clip = viewProjection * SIMD4(p, 1) return SIMD2((clip.x / depth + 1) / 2 * viewportSize.x, (1 - clip.y / depth) / 2 * viewportSize.y) } }