App/Sources/FoldSession.swift

main
fold/App/Sources/FoldSession.swift history · blame · raw

277 lines · 11678 bytes

21 symbols in this file
  1import FoldFormat
  2import Folding
  3import Foundation
  4import Notation
  5import Observation
  6import simd
  7
  8/// One model being folded: the current step, its fold parameter `t` in 0...1, and the model
  9/// view's orientation. Nothing here changes `t` on its own; the step changes only when the user
 10/// completes it or opens another. Completing the last step finishes the model and locks it.
 11@MainActor @Observable
 12final class FoldSession {
 13    let model: FoldFile
 14    private(set) var step: FoldStep
 15    private(set) var interpolator: FoldInterpolator
 16    private(set) var diagram: Diagram
 17    private var order: LayerOrder
 18
 19    var t = 0.0 {
 20        didSet { if t != oldValue { pose() } }
 21    }
 22    /// Whether the last step has been completed and no drag, adjustment or other step has since
 23    /// left `t` below 1.
 24    private(set) var isFinished = false
 25    /// Whether the finished model ignores drags and adjustment. Orbit and zoom still work.
 26    private(set) var isLocked = false
 27    /// How many times the model has been finished.
 28    private(set) var finishCount = 0
 29    /// The unit vector from the camera's target toward its eye.
 30    var eyeDirection: SIMD3<Double> {
 31        didSet { if eyeDirection != oldValue { sortClusters(); cachedMapping = nil } }
 32    }
 33    /// A unit vector perpendicular to `eyeDirection`.
 34    var up: SIMD3<Double> {
 35        didSet { cachedMapping = nil }
 36    }
 37    /// The camera's vertical field of view in radians, which a pinch changes.
 38    var fieldOfView = FoldSession.defaultFieldOfView {
 39        didSet { cachedMapping = nil }
 40    }
 41    /// The paper view's size in points.
 42    var viewportSize = SIMD2(1.0, 1.0) {
 43        didSet { cachedMapping = nil }
 44    }
 45    private var aspect: Double { viewportSize.x / viewportSize.y }
 46
 47    /// The render mesh at `t`.
 48    private(set) var meshPositions: [SIMD3<Double>] = []
 49    /// The FOLD faces' clusters at `t`, back to front along the camera's view direction.
 50    private(set) var clusters: [CoplanarCluster] = []
 51    /// The FOLD vertices at `t`.
 52    private var positions: [SIMD3<Double>] = []
 53    /// The centre of the bounding box of the frame the step starts from.
 54    private var target: SIMD3<Double>
 55    @ObservationIgnored private var cachedMapping: FoldParameterMapping?
 56    /// Half the flat sheet's diagonal, the radius the camera keeps in view.
 57    private let radius: Double
 58    private static let defaultFieldOfView = Double.pi / 6
 59    /// The fields of view a pinch can reach, from about 2.5 times the default magnification to half of it.
 60    static let fieldOfViewRange = 0.21...0.98
 61
 62    /// `step` counts from 1. The camera starts at the step's authored viewpoint.
 63    init(model: FoldFile, step n: Int) throws {
 64        self.model = model
 65        let step = try readStep(n, in: model)
 66        self.step = step
 67        interpolator = FoldInterpolator(file: model, step: step)
 68        order = try LayerOrder.active(for: step, in: model)
 69        diagram = buildDiagram(file: model, step: step)
 70        let (low, high) = bounds(model.frames[0].verticesCoords)
 71        radius = length(high - low) / 2
 72        target = startCentre(model, step)
 73        let eye = normalize(step.viewpoint.eye)
 74        eyeDirection = eye
 75        up = normalize(step.viewpoint.up - dot(step.viewpoint.up, eye) * eye)
 76        pose()
 77    }
 78
 79    /// Moves to the next step at t = 0, seen from its viewpoint, once the current step is complete.
 80    /// Completing the last step finishes the model at t = 1 and locks it.
 81    func completeStep() {
 82        guard t == 1 else { return }
 83        if step.index + 1 < model.frames.count {
 84            open(step: step.index + 1)
 85        } else if !isFinished {
 86            isFinished = true
 87            isLocked = true
 88            finishCount += 1
 89        }
 90    }
 91
 92    /// Locks or unlocks a finished model. Unlocked, its last step can be dragged back to unfold it.
 93    func toggleLock() {
 94        guard isFinished else { return }
 95        isLocked.toggle()
 96        guard isLocked else { return }
 97        if let grab { t = grab.start }
 98        cancelDrag()
 99    }
100
101    /// Leaves the finished state if `t` is below 1.
102    private func settle() {
103        if t < 1 { isFinished = false; isLocked = false }
104    }
105
106    /// Opens step `n`, counting from 1, at t = 0, seen from its viewpoint at the default zoom. A
107    /// drag in progress no longer moves `t` or completes a step, and a finished model is no longer
108    /// finished. Opening the current step leaves it as it is. A step that cannot be read leaves the
109    /// session as it is and stops a Debug build.
110    func open(step n: Int) {
111        guard n != step.index else { return }
112        cancelDrag()
113        let next: FoldStep, nextOrder: LayerOrder
114        do {
115            next = try readStep(n, in: model)
116            nextOrder = try LayerOrder.active(for: next, in: model)
117        } catch {
118            assertionFailure("step \(n) of \(model.fileTitle ?? "?"): \(error)")
119            return
120        }
121        step = next
122        interpolator = FoldInterpolator(file: model, step: next)
123        order = nextOrder
124        diagram = buildDiagram(file: model, step: next)
125        target = startCentre(model, next)
126        let eye = normalize(next.viewpoint.eye)
127        eyeDirection = eye
128        up = normalize(next.viewpoint.up - dot(next.viewpoint.up, eye) * eye)
129        fieldOfView = Self.defaultFieldOfView
130        cachedMapping = nil
131        if t == 0 { pose() } else { t = 0 }
132        settle()
133    }
134
135    /// What maps a one-finger drag's translation to `t`.
136    private enum DragMapping {
137        /// `position` is where the latest movement left the drag on the path.
138        case fold(FoldParameterMapping, grabbedAt: SIMD2<Double>, position: FoldParameterMapping.Position)
139        case reorient(ReorientMapping)
140    }
141
142    /// The current one-finger drag's mapping and `t` when it began, while one is in progress.
143    @ObservationIgnored private var grab: (mapping: DragMapping, start: Double)?
144    /// Two-finger gestures in progress.
145    @ObservationIgnored private var orbits = 0
146    /// Whether a two-finger gesture began during the current drag. The drag then leaves `t` as it
147    /// was when the drag began until the finger lifts, and does not complete the step.
148    @ObservationIgnored private(set) var isDragSuspended = false
149
150    /// Called when a one-finger drag on a fold step begins: the moving faces then follow the
151    /// finger along `mapping`'s path.
152    func beginFoldDrag() {
153        guard !isLocked else { return }
154        let mapping = self.mapping
155        beginDrag(.fold(mapping, grabbedAt: mapping.point(at: t), position: mapping.position(at: t)))
156    }
157
158    /// Called when a one-finger drag on a turn-over or rotate step begins: its horizontal
159    /// component then turns the model across its on-screen width, measured on the frame the step
160    /// starts from, which a vertical turn-over would otherwise shrink to an edge midway.
161    func beginReorientDrag() {
162        guard !isLocked else { return }
163        beginDrag(.reorient(ReorientMapping(positions: interpolator.positions(at: 0), camera: camera,
164                                            viewportSize: viewportSize)))
165    }
166
167    private func beginDrag(_ mapping: DragMapping) {
168        grab = (mapping, t)
169        isDragSuspended = orbits > 0
170    }
171
172    /// Moves `t` to where the drag's `translation` maps it, unless the drag is suspended.
173    func drag(translation: SIMD2<Double>) {
174        guard let grab, !isDragSuspended else { return }
175        switch grab.mapping {
176        case let .fold(mapping, grabbedAt, position):
177            let next = mapping.position(grabbedAt: grabbedAt, translation: translation,
178                                        current: mapping.isDegenerate ? mapping.position(at: grab.start) : position)
179            self.grab?.mapping = .fold(mapping, grabbedAt: grabbedAt, position: next)
180            t = next.t
181        case let .reorient(mapping):
182            t = mapping.parameter(translation: translation.x, current: grab.start)
183        }
184    }
185
186    /// Called when the drag's finger lifts at `translation`: moves `t` there as `drag(translation:)`
187    /// does, then completes the step unless the drag was suspended.
188    func endDrag(translation: SIMD2<Double>) {
189        drag(translation: translation)
190        if !isDragSuspended { completeStep() }
191        cancelDrag()
192    }
193
194    /// Called when the drag ends by any means, including cancellation. A finished model left below
195    /// t = 1 is no longer finished.
196    func cancelDrag() {
197        grab = nil
198        isDragSuspended = false
199        settle()
200    }
201
202    /// Called when a two-finger gesture begins. A drag in progress is suspended and its effect on
203    /// `t` undone.
204    func beginOrbit() {
205        orbits += 1
206        if let grab {
207            t = grab.start
208            isDragSuspended = true
209        }
210    }
211
212    func endOrbit() {
213        orbits = max(orbits - 1, 0)
214    }
215
216    /// Turns the view of the model by `angles` radians, as `Camera.orbited(by:)` does.
217    func orbit(by angles: SIMD2<Double>) {
218        let turned = camera.orbited(by: angles)
219        eyeDirection = normalize(turned.eye - turned.target)
220        up = turned.up
221    }
222
223    /// Magnifies the view of the model by `scale`, within `fieldOfViewRange`.
224    func zoom(by scale: Double) {
225        fieldOfView = camera.zoomed(by: scale, within: Self.fieldOfViewRange).fieldOfView
226    }
227
228    /// Moves `t` to the next multiple of 0.1 above it (`direction` 1) or below it (−1), within
229    /// 0...1, for VoiceOver's adjustable action. Reaching 1 completes the step, as lifting the
230    /// finger there does.
231    func adjust(_ direction: Int) {
232        guard !isLocked else { return }
233        let tenths = direction > 0 ? (t * 10 + 1e-9).rounded(.down) + 1 : (t * 10 - 1e-9).rounded(.up) - 1
234        t = min(max(tenths, 0), 10) / 10
235        settle()
236        if t == 1 { completeStep() }
237    }
238
239    /// Maps drags on the paper view to `t` for the current step, camera and view size.
240    var mapping: FoldParameterMapping {
241        if let cachedMapping { return cachedMapping }
242        let mapping = FoldParameterMapping(file: model, step: step, camera: camera, viewportSize: viewportSize)
243        cachedMapping = mapping
244        return mapping
245    }
246
247    /// Looks at the step's start frame from `eyeDirection`, far enough that a sphere of `radius`
248    /// about it fits the paper view at `aspect` at the default field of view.
249    var camera: Camera {
250        let half = Self.defaultFieldOfView / 2
251        let horizontalHalf = atan(tan(half) * aspect)
252        let distance = radius / sin(min(half, horizontalHalf))
253        return Camera(eye: target + distance * eyeDirection, target: target, up: up, fieldOfView: fieldOfView)
254    }
255
256    private func pose() {
257        positions = interpolator.positions(at: t)
258        meshPositions = interpolator.meshPositions(at: t)
259        sortClusters()
260    }
261
262    /// Membership and order come from one `LayerOrder.clusters` call, so both are recomputed when
263    /// either `t` or the view direction changes.
264    private func sortClusters() {
265        clusters = order.clusters(positions: positions, faces: model.facesVertices, viewDirection: -eyeDirection)
266    }
267}
268
269/// The centre of the bounding box of the frame `step` starts from.
270private func startCentre(_ model: FoldFile, _ step: FoldStep) -> SIMD3<Double> {
271    let (low, high) = bounds(model.frames[step.index - 1].verticesCoords)
272    return (low + high) / 2
273}
274
275private func bounds(_ points: [SIMD3<Double>]) -> (SIMD3<Double>, SIMD3<Double>) {
276    points.dropFirst().reduce((points[0], points[0])) { (simd_min($0.0, $1), simd_max($0.1, $1)) }
277}