Packages/FoldKit/Sources/Folding/ReorientMapping.swift

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

27 lines · 1242 bytes

2 symbols in this file
 1import simd
 2
 3/// Maps a horizontal drag on the paper view to the parameter of a `turnOver` or `rotate` step: the
 4/// drag's rightward distance over the model's on-screen width. A leftward drag turns it back.
 5/// Screen points are UIKit's, in a viewport of `viewportSize`.
 6public struct ReorientMapping: Sendable {
 7    /// The width in points of the projected bounding box of `positions`, at least 44 points.
 8    public let width: Double
 9
10    private static let minimumWidth = 44.0
11
12    /// `positions` are the model's vertices in the frame the step starts from.
13    public init(positions: [SIMD3<Double>], camera: Camera, viewportSize: SIMD2<Double>) {
14        let viewProjection = camera.viewProjection(aspect: viewportSize.x / viewportSize.y)
15        let xs = positions.map { p in
16            let clip = viewProjection * SIMD4(p, 1)
17            return (clip.x / clip.w + 1) / 2 * viewportSize.x
18        }
19        width = max(xs.max()! - xs.min()!, Self.minimumWidth)
20    }
21
22    /// The parameter, in 0...1, after a drag of `translation` points rightward from where the
23    /// parameter was `current`.
24    public func parameter(translation: Double, current: Double) -> Double {
25        min(max(current + translation / width, 0), 1)
26    }
27}