Cotton code
272 lines · 11.3 KB · SwiftRaw
// The fan's motion (lane fan, 14 Oct 2026): one angle, `theta`, driven a// frame at a time — by a finger, by the snap spring after a release, or by a// timed turn to a tile (a tap, a spoken "show"). Driven here rather than by a// SwiftUI animation because the fan must know, every frame, its angular speed// (the live page mounts only once it has dropped, ruling 2) and which tile is// crossing the centre line (the haptic tick, ruling 8); an animated value is// opaque between its ends. The geometry and the spring are pure// (`FanGeometry.swift`); this only steps them.#if os(iOS)import OSLogimport QuartzCoreimport SwiftUIimport UIKit@MainActor@Observablefinal class FanMotion {    /// The angle under the centre line, in degrees. Not observed: the arc    /// is moved by `onMove`, every frame, with no SwiftUI pass (`FanArc`).    @ObservationIgnored private(set) var theta: Double = 0    /// Degrees a second, signed. No view reads it: not observed, so a frame    /// changes one observed value (theta), not two.    @ObservationIgnored private(set) var velocity: Double = 0    /// The tile whose page is shown: where the fan last came to rest.    private(set) var settled = 0    /// The tile the fan will come to rest on: known the moment a finger    /// lifts or a turn starts, so its picture is decoded first.    private(set) var heading = 0    /// Something moves the fan: a finger, the spring or a turn.    private(set) var moving = false    /// What the page area draws: the live page or the nearest tile's picture    /// (`FanPageRule`). Set only when it changes, so the page area is not    /// asked to draw again every frame.    private(set) var shows: FanPageRule.Shows = .live(0)    /// The motion under way, or the last one, is a person's: a finger on the    /// arc, or a tap on a card (`turn(to:animated:byPerson:)`). A turn the    /// code asks for, a recount and the arc mounting are nobody's, so a rest    /// they bring acts on nothing (walker pass 4, 16 Oct 2026: every cold    /// launch flashed the Databases sheet, the caps' arc mounting at rest on    /// its last cap).    @ObservationIgnored private(set) var byPerson = false    /// The motion under way, or the last one, is a finger's swipe — released    /// to fling and spring — not a tap's timed turn. A swipe's heading is    /// where a fling may land, not a choice (walker294 row 18).    @ObservationIgnored private(set) var swiped = false    @ObservationIgnored var geometry: FanGeometry    @ObservationIgnored var spring: FanSpring    @ObservationIgnored var count = 0    /// A tile crossed the centre line while turning.    @ObservationIgnored var onCross: () -> Void = {}    /// The angle moved: the arc it turns is moved to it.    @ObservationIgnored var onMove: (Double) -> Void = { _ in }    @ObservationIgnored private var raw: Double = 0    @ObservationIgnored private var dragStart: Double = 0    /// The tile the finger came down on: a swipe turns one tile from it.    @ObservationIgnored private var dragFrom = 0    @ObservationIgnored private var crossing = 0    @ObservationIgnored private var mode = Mode.still    @ObservationIgnored private var link: CADisplayLink?    @ObservationIgnored private var lastFrame: CFTimeInterval = 0    /// Every frame interval of the turn under way, for the frame line.    @ObservationIgnored private var intervals: [Double] = []    private enum Mode {        case still        case dragging        case springing(target: Double)        case turning(from: Double, to: Double, started: CFTimeInterval, duration: Double)    }    init(geometry: FanGeometry, spring: FanSpring) {        self.geometry = geometry        self.spring = spring    }    private func updateShows() {        let next = FanPageRule.shows(theta: theta, moving: moving, count: count, geometry: geometry)        if next != shows { shows = next }    }    // ── A finger ─────────────────────────────────────────────────────────    /// A finger came down: whatever moved the fan stops where it is.    func beginDrag() {        stopLink()        mode = .dragging        byPerson = true        swiped = true        dragStart = theta        dragFrom = geometry.nearest(theta, count: count)        raw = theta        crossing = geometry.nearest(theta, count: count)        velocity = 0        moving = true        updateShows()        // Ticks under the finger too: the frame line counts the drag's frames.        startLink()    }    /// The finger has moved `dx` points sideways since it came down.    func drag(_ dx: Double) {        guard case .dragging = mode else { return }        raw = dragStart - dx * geometry.degreesPerPoint        move(to: geometry.shown(raw: raw, swipingFrom: dragFrom, count: count))    }    /// The finger lifted moving `dx` points a second sideways. A fling turns    /// on by its velocity before the spring snaps it to a tile; with    /// `flings` off (Reduce Motion) it lands on the nearest tile at once.    func release(pointsPerSecond dx: Double, flings: Bool) {        let velocity = -dx * geometry.degreesPerPoint        let target = Double(geometry.target(            from: dragFrom, releasing: theta, pointsPerSecond: dx, count: count, flings: flings)) * geometry.step        guard flings else { return land(at: target) }        heading = geometry.nearest(target, count: count)        self.velocity = velocity        mode = .springing(target: target)        updateShows()        startLink()    }    // ── A turn to a tile ────────────────────────────────────────────────    /// Turns to tile `index` over a time scaled by the distance; `animated`    /// off (Reduce Motion) puts it there at once. `byPerson` when a person    /// asked for it — a tap on a card.    func turn(to index: Int, animated: Bool, byPerson: Bool = false) {        self.byPerson = byPerson        swiped = false        let target = Double(min(max(index, 0), max(0, count - 1))) * geometry.step        guard animated else { return land(at: target) }        crossing = geometry.nearest(theta, count: count)        heading = geometry.nearest(target, count: count)        mode = .turning(from: theta, to: target, started: CACurrentMediaTime(),                        duration: geometry.turnDuration(degrees: target - theta))        moving = true        updateShows()        startLink()    }    /// The tiles changed: keep the settled tile in range.    func recount(_ count: Int) {        self.count = count        let last = Double(max(0, count - 1)) * geometry.step        if theta > last {            byPerson = false            land(at: last)        } else {            updateShows()        }    }    // ── Frames ──────────────────────────────────────────────────────────    private func land(at target: Double) {        stopLink()        mode = .still        velocity = 0        move(to: target)        rest()    }    private func rest() {        moving = false        settled = geometry.nearest(theta, count: count)        heading = settled        updateShows()    }    private func move(to angle: Double) {        theta = angle        onMove(angle)        defer { updateShows() }        let nearest = geometry.nearest(angle, count: count)        if nearest != crossing {            crossing = nearest            onCross()        }    }    private func frame(_ link: CADisplayLink) {        let now = link.timestamp        let dt = lastFrame == 0 ? link.duration : now - lastFrame        if lastFrame != 0 { intervals.append(dt) }        lastFrame = now        switch mode {        case .still:            stopLink()        case .dragging:            break        case .springing(let target):            let next = spring.step(theta: theta, velocity: velocity, target: target, dt: dt)            velocity = next.velocity            if FanSpring.rests(theta: next.theta, velocity: next.velocity, target: target) {                land(at: target)            } else {                move(to: next.theta)            }        case .turning(let from, let to, let started, let duration):            let progress = duration > 0 ? min(1, (now - started) / duration) : 1            // Ease out: quick away, gentle into the tile.            let eased = 1 - pow(1 - progress, 3)            let angle = from + (to - from) * eased            velocity = dt > 0 ? (angle - theta) / dt : 0            if progress >= 1 { land(at: to) } else { move(to: angle) }        }    }    private func startLink() {        guard link == nil else { return }        moving = true        lastFrame = 0        let link = CADisplayLink(target: FanFrameTarget(self), selector: #selector(FanFrameTarget.tick(_:)))        // The fan turns at the display's own rate: 120 Hz on ProMotion.        let most = Float(UIScreen.main.maximumFramesPerSecond)        link.preferredFrameRateRange = CAFrameRateRange(minimum: most / 2, maximum: most, preferred: most)        link.add(to: .main, forMode: .common)        self.link = link    }    private func stopLink() {        if link != nil { FanFrames.report(intervals, tiles: count) }        intervals = []        link?.invalidate()        link = nil    }    fileprivate func tick(_ link: CADisplayLink) { frame(link) }}/// What a turn cost, frame by frame: one log line per turn (subsystem/// `com.cottondb.fan`), read off a device or a simulator with `log show`, so a/// frame over the display's budget is a number, not a feeling.enum FanFrames {    private static let log = Logger(subsystem: "com.cottondb.fan", category: "frames")    static func report(_ intervals: [Double], tiles: Int) {        guard !intervals.isEmpty else { return }        let budget = 1.0 / Double(UIScreen.main.maximumFramesPerSecond)        let sorted = intervals.sorted()        let longest = sorted.last ?? 0        let p95 = sorted[min(sorted.count - 1, Int(Double(sorted.count) * 0.95))]        // A frame is late when it took longer than one and a half budgets:        // the display skipped a refresh for it.        let lateAt = intervals.indices.filter { intervals[$0] > budget * 1.5 }        // Where in the turn each late frame fell: its frame number, so a        // cost at the start (a finger landing) and at the end (the live page        // mounting) read apart.        let at = lateAt.map { String($0 + 1) }.joined(separator: ",")        let line = String(format: "turn: %d tiles, %d frames, budget %.2f ms, longest %.2f ms, p95 %.2f ms, late %d",                          tiles, intervals.count, budget * 1000, longest * 1000, p95 * 1000, lateAt.count)            + (at.isEmpty ? "" : " at \(at)")        log.notice("\(line, privacy: .public)")    }}/// The display link holds its target strongly; this holds the motion weakly,/// so a fan that goes away takes its link with it.@MainActorprivate final class FanFrameTarget: NSObject {    weak var motion: FanMotion?    init(_ motion: FanMotion) { self.motion = motion }    @objc func tick(_ link: CADisplayLink) {        guard let motion else { return link.invalidate() }        motion.tick(link)    }}#endif