krz/moonrise

Night-sky companion for iPhone, Apple Watch and Vision Pro: what's up tonight, the Moon, planets, launches and missions, and a Library of the solar system. SwiftUI app with a Cloudflare Workers backend. astronomy cloudflare-workers ios night-sky space swiftui visionos watchos

App/Sources/SkyScreen.swift

04b2b1d914788057bcd20945b876847386eb8f65
moonrise/App/Sources/SkyScreen.swift history · blame · raw

396 lines · 19399 bytes

19 symbols in this file
  1import Library
  2import ObservingLog
  3import SkyEngine
  4import SkyRenderer
  5import SwiftUI
  6
  7struct SkyScreen: View {
  8    @State private var model = SkyModel()
  9    @State private var pointer = MotionPointer()
 10    @State private var azimuth = 180.0
 11    @State private var altitude = 45.0
 12    @State private var fieldOfView = 100.0
 13    @AppStorage(SettingsKey.nightMode) private var nightMode = "auto"
 14    @AppStorage(SettingsKey.skyCulture) private var skyCulture = "western"
 15    @State private var showSettings = false
 16    @State private var showEvents = false
 17    @State private var showLog = false
 18    @State private var logEntry: Observation?
 19    @AppStorage(SettingsKey.onboarded) private var onboarded = false
 20    @AppStorage(SettingsKey.nightActive) private var nightActive = false
 21    @State private var showToday = false
 22    @State private var showYear = false
 23    @State private var showTours = false
 24    @State private var tour: Tour?
 25    @State private var tourStep = 0
 26    @State private var turning: Task<Void, Never>?
 27    @Environment(\.scenePhase) private var scenePhase
 28    @State private var libraryPage: LibraryPage?
 29    @State private var selection: SkyObject?
 30    @State private var details: BodyDetails?
 31    @GestureState private var drag: CGSize = .zero
 32    @GestureState private var zoom: CGFloat = 1
 33    private let stats = DrawStats()
 34
 35    private var night: Bool { nightMode == "on" || (nightMode == "auto" && model.sunAltitude < -12) }
 36    private var style: SkyStyle { night ? .night : SkyStyle() }
 37    private var ink: Color { night ? SkyStyle.nightRed : Color(red: 0.95, green: 0.95, blue: 0.93) }
 38
 39    var body: some View {
 40        GeometryReader { geo in
 41            ZStack {
 42                style.background.ignoresSafeArea()
 43                if let scene = model.scene {
 44                    let view = current(width: geo.size.width)
 45                    SkyView(scene: scene, centerAzimuth: view.azimuth, centerAltitude: view.altitude, fieldOfView: view.fieldOfView, style: style, culture: Catalog.skyCultures.first { $0.id == skyCulture }, highlight: tour.flatMap { highlight($0.steps[tourStep].target) }) { [stats] d in
 46                        stats.record(d)
 47                    }
 48                    .ignoresSafeArea()
 49                    .gesture(panGesture(width: geo.size.width).simultaneously(with: zoomGesture))
 50                    .onTapGesture(coordinateSpace: .local) { location in
 51                        let p = Projection(centerAzimuth: view.azimuth, centerAltitude: view.altitude, fieldOfView: view.fieldOfView, size: geo.size)
 52                        select(scene.object(at: location, projection: p))
 53                    }
 54                    .accessibilityElement()
 55                    .accessibilityLabel(skyDescription(scene, azimuth: view.azimuth))
 56                    .accessibilityHint("Swipe up or down to turn. Planets and the Moon are listed in the Tonight summary.")
 57                    .accessibilityAdjustableAction { direction in
 58                        azimuth = (azimuth + (direction == .increment ? 45 : -45) + 360).truncatingRemainder(dividingBy: 360)
 59                    }
 60                }
 61                VStack(spacing: 0) {
 62                    header
 63                    if pointer.active {
 64                        Button { pointer.stop() } label: {
 65                            Label("Following your phone · Stop", systemImage: "iphone.gen3.radiowaves.left.and.right")
 66                                .font(.caption.weight(.medium))
 67                                .padding(.horizontal, 12).padding(.vertical, 8)
 68                                .glassEffect(in: .capsule)
 69                        }
 70                        .buttonStyle(.plain)
 71                        .padding(.top, 4)
 72                    }
 73                    if let selection { card(for: selection).padding(.horizontal, 16).padding(.top, 8) }
 74                    Spacer()
 75                    if let tour {
 76                        TourCard(tour: tour, step: $tourStep, belowHorizon: (tourTarget(tour.steps[tourStep].target)?.altitude ?? 0) < 0,
 77                                 ink: ink, background: style.ground, onOpen: { libraryPage = $0 }, onEnd: { self.tour = nil })
 78                    } else if model.historicalYear == nil {
 79                        TodayBar(model: model, ink: ink, background: style.ground) { showToday = true }
 80                    }
 81                }
 82            }
 83        }
 84        .foregroundStyle(ink)
 85        .environment(\.nightMode, night)
 86        .sheet(isPresented: $showLog) {
 87            LogScreen { newObservation("") }.preferredColorScheme(.dark).tint(.blue)
 88        }
 89        .sheet(item: $logEntry) { o in
 90            ObservationEditor(observation: o) {}.preferredColorScheme(.dark).tint(.blue)
 91        }
 92        .sheet(isPresented: $showEvents) {
 93            EventsScreen(observer: model.observer, placeName: model.placeName)
 94                .preferredColorScheme(.dark)
 95        }
 96        .sheet(isPresented: $showTours) {
 97            TourPicker { tour = $0; tourStep = 0; aim(at: $0.steps[0].target) }.preferredColorScheme(.dark)
 98        }
 99        .onChange(of: tourStep) { if let tour { aim(at: tour.steps[tourStep].target) } }
100        .sheet(isPresented: $showYear) {
101            YearSheet(year: $model.historicalYear, south: model.observer.latitude < 0).preferredColorScheme(.dark)
102        }
103        .sheet(isPresented: $showSettings, onDismiss: rescheduleSummary) {
104            SettingsScreen { model.applyLocationSettings() }
105                .preferredColorScheme(.dark)
106                .tint(.blue)
107        }
108        .sheet(item: $libraryPage) { page in
109            NavigationStack { LibraryPageView(page: page) }
110        }
111        .sheet(isPresented: $showToday) {
112            TodaySheet(model: model, ink: ink, background: style.ground)
113                .environment(\.nightMode, night)
114                .presentationDetents([.medium, .large])
115        }
116        .onChange(of: model.offsetHours) { select(selection) }
117        .onChange(of: onboarded) { if onboarded { model.start() } }
118        .onChange(of: night, initial: true) { nightActive = night }
119        .onChange(of: model.observer) { rescheduleSummary() }
120        .onChange(of: scenePhase) { if scenePhase == .active { rescheduleSummary() } }
121        .task {
122            if onboarded { model.start() }
123            while !Task.isCancelled {
124                try? await Task.sleep(for: .seconds(30))
125                model.refresh()
126            }
127        }
128    }
129
130    /// Where a tour target is in the current scene; constellations use the mean direction of their stars.
131    private func tourTarget(_ t: Tour.Target) -> Horizontal? {
132        guard let scene = model.scene else { return nil }
133        if let hr = t.hr { return scene.starsByHR[hr] }
134        if let b = t.body { return scene.bodies.first { $0.body.rawValue == b }?.position }
135        guard let c = t.constellation, let figure = Catalog.constellations.first(where: { $0.id == c }) else { return nil }
136        let positions = Set(figure.lines.joined()).compactMap { scene.starsByHR[$0] }
137        guard !positions.isEmpty else { return nil }
138        var v = SIMD3<Double>.zero
139        for h in positions {
140            let alt = h.altitude * .pi / 180, az = h.azimuth * .pi / 180
141            v += SIMD3(cos(alt) * sin(az), cos(alt) * cos(az), sin(alt))
142        }
143        var az = atan2(v.x, v.y) * 180 / .pi
144        if az < 0 { az += 360 }
145        return Horizontal(altitude: asin(v.z / (v * v).sum().squareRoot()) * 180 / .pi, azimuth: az)
146    }
147
148    private func highlight(_ t: Tour.Target) -> SkyHighlight? {
149        if let c = t.constellation { return .constellation(c) }
150        if let hr = t.hr { return .star(hr) }
151        if let b = t.body.flatMap(SkyBody.init(rawValue:)) { return .body(b) }
152        return nil
153    }
154
155    /// Pans the view to a tour target over a second, the short way round, keeping it at least
156    /// 10° up so the horizon stays in view. The Canvas redraws each frame, so the turn is stepped by hand.
157    private func aim(at t: Tour.Target) {
158        guard let h = tourTarget(t) else { return }
159        pointer.stop()
160        turning?.cancel()
161        let from = (az: azimuth, alt: altitude, fov: fieldOfView)
162        let dAz = (h.azimuth - from.az + 540).truncatingRemainder(dividingBy: 360) - 180
163        let to = (alt: max(h.altitude, 10), fov: 80.0)
164        turning = Task {
165            let frames = 60
166            for f in 1...frames {
167                try? await Task.sleep(for: .milliseconds(16))
168                if Task.isCancelled { return }
169                let x = Double(f) / Double(frames)
170                let e = x < 0.5 ? 4 * x * x * x : 1 - pow(-2 * x + 2, 3) / 2
171                azimuth = (from.az + dAz * e + 360).truncatingRemainder(dividingBy: 360)
172                altitude = from.alt + (to.alt - from.alt) * e
173                fieldOfView = from.fov + (to.fov - from.fov) * e
174            }
175        }
176    }
177
178    private func rescheduleSummary() {
179        Task { await DailySummaryNotifications.reschedule(model) }
180    }
181
182    private func select(_ object: SkyObject?) {
183        selection = object
184        details = nil
185        guard case .body(let body) = object else { return }
186        Task { details = await model.details(of: body) }
187    }
188
189    /// The view direction with any in-progress gestures applied.
190    private func current(width: CGFloat) -> (azimuth: Double, altitude: Double, fieldOfView: Double) {
191        let fov = min(max(fieldOfView / Double(zoom), 30), 140)
192        if pointer.active { return (pointer.direction.azimuth, pointer.direction.altitude, fov) }
193        let degreesPerPoint = fov / Double(max(width, 1))
194        let az = (azimuth - Double(drag.width) * degreesPerPoint).truncatingRemainder(dividingBy: 360)
195        let alt = min(max(altitude + Double(drag.height) * degreesPerPoint, 0), 90)
196        return ((az + 360).truncatingRemainder(dividingBy: 360), alt, fov)
197    }
198
199    private func panGesture(width: CGFloat) -> some Gesture {
200        DragGesture(minimumDistance: 6)
201            .onChanged { _ in
202                turning?.cancel()
203                if pointer.active {
204                    azimuth = pointer.direction.azimuth
205                    altitude = min(max(pointer.direction.altitude, 0), 90)
206                    pointer.stop()
207                }
208            }
209            .updating($drag) { value, state, _ in state = value.translation }
210            .onEnded { value in
211                let degreesPerPoint = fieldOfView / Double(max(width, 1))
212                azimuth = ((azimuth - Double(value.translation.width) * degreesPerPoint).truncatingRemainder(dividingBy: 360) + 360).truncatingRemainder(dividingBy: 360)
213                altitude = min(max(altitude + Double(value.translation.height) * degreesPerPoint, 0), 90)
214            }
215    }
216
217    private var zoomGesture: some Gesture {
218        MagnifyGesture()
219            .updating($zoom) { value, state, _ in state = value.magnification }
220            .onEnded { value in fieldOfView = min(max(fieldOfView / Double(value.magnification), 30), 140) }
221    }
222
223    private var header: some View {
224        HStack(alignment: .top) {
225            VStack(alignment: .leading, spacing: 4) {
226                if let y = model.historicalYear {
227                    Text("Sky in \(YearSheet.label(y))").font(.title2.weight(.medium))
228                    if let p = model.poleStar {
229                        Text(String(format: "Pole star: %@, %.1f° from the pole", p.name, p.degrees)).font(.caption2).dimmed(0.8)
230                    }
231                    Button("Back to today") { model.historicalYear = nil }.font(.caption.weight(.medium))
232                } else {
233                    Text(model.offsetHours == 0 ? "Tonight" : "Sky at \(model.displayedDate.formatted(date: .omitted, time: .shortened))")
234                        .font(.title2.weight(.medium))
235                }
236                Text(model.placeName)
237                    .font(.caption2).dimmed(0.7)
238                #if DEBUG
239                TimelineView(.periodic(from: .now, by: 1)) { _ in
240                    Text(stats.summary(build: model.lastBuild))
241                        .font(.caption2.monospacedDigit()).dimmed(0.7)
242                }
243                #endif
244            }
245            Spacer()
246            Menu {
247                Section("Tonight") {
248                    Button { showTours = true } label: { Label("Guided tours", systemImage: "figure.walk") }
249                    Button { showEvents = true } label: { Label("Events and eclipses", systemImage: "calendar") }
250                    if pointer.available {
251                        Button { pointer.active ? pointer.stop() : pointer.start() } label: {
252                            Label(pointer.active ? "Stop following the phone" : "Point the phone at the sky", systemImage: "iphone.gen3.radiowaves.left.and.right")
253                        }
254                    }
255                }
256                Section("Explore") {
257                    Button { showYear = true } label: { Label("Sky in another year", systemImage: "hourglass") }
258                    Button { showLog = true } label: { Label("Observing log", systemImage: "book.closed") }
259                }
260                Section {
261                    Button { nightMode = night ? "off" : "on" } label: {
262                        Label(night ? "Turn off night mode" : "Night mode (red light)", systemImage: night ? "eye.slash" : "eye")
263                    }
264                    Button { showSettings = true } label: { Label("Settings", systemImage: "gearshape") }
265                }
266            } label: {
267                Label("Explore", systemImage: "sparkle.magnifyingglass")
268                    .font(.subheadline.weight(.medium))
269                    .padding(.horizontal, 14)
270                    .frame(minHeight: 44)
271                    .glassEffect(in: .capsule)
272            }
273            .accessibilityHint("Tours, events, night mode, settings and more")
274        }
275        .padding(.horizontal, 20)
276        .padding(.top, 8)
277    }
278
279    @ViewBuilder
280    private func card(for object: SkyObject) -> some View {
281        VStack(alignment: .leading, spacing: 8) {
282            HStack {
283                Text(title(for: object)).font(.title3.weight(.medium))
284                Spacer()
285                Button { selection = nil } label: { Image(systemName: "xmark").frame(width: 32, height: 32) }
286                    .accessibilityLabel("Close")
287            }
288            switch object {
289            case .body:
290                if let d = details { bodyFacts(d) } else { ProgressView().tint(ink) }
291            case .constellation(let id):
292                Text("Constellation · \(id)").font(.footnote).dimmed(0.7)
293            }
294            HStack(spacing: 20) {
295                Button { logEntry = newObservation(title(for: object)) } label: {
296                    Label("Log", systemImage: "square.and.pencil").font(.footnote.weight(.medium))
297                }
298                .buttonStyle(.plain)
299                .frame(minHeight: 44)
300                if let page = libraryPage(for: object) {
301                    Button { libraryPage = page } label: {
302                        Label("Read more", systemImage: "book").font(.footnote.weight(.medium))
303                    }
304                    .buttonStyle(.plain)
305                    .frame(minHeight: 44)
306                }
307            }
308        }
309        .padding(16)
310        .background(style.background.opacity(0.92), in: .rect(cornerRadius: 12))
311        .overlay(RoundedRectangle(cornerRadius: 12).stroke(ink.opacity(0.25), lineWidth: 0.5))
312    }
313
314    private func newObservation(_ object: String) -> Observation {
315        Observation(object: object, date: model.displayedDate, place: model.placeName == "Your location" ? "" : model.placeName,
316                    latitude: model.observer.latitude, longitude: model.observer.longitude)
317    }
318
319    private func libraryPage(for object: SkyObject) -> LibraryPage? {
320        switch object {
321        case .body(let b): Library.page(body: b.rawValue)
322        case .constellation(let id): Library.page(constellation: id)
323        }
324    }
325
326    private func title(for object: SkyObject) -> String {
327        switch object {
328        case .body(let b): b.rawValue.capitalized
329        case .constellation(let id): constellationNames[id] ?? id
330        }
331    }
332
333    private func bodyFacts(_ d: BodyDetails) -> some View {
334        let time: (Date?) -> String = { $0?.formatted(date: .omitted, time: .shortened) ?? "–" }
335        let distance = d.body == .moon
336            ? "\(Int((d.distanceAU * 149_597_870.7).rounded()).formatted()) km"
337            : String(format: "%.2f AU", d.distanceAU)
338        let rows: [(String, String)] = [
339            ("Altitude", String(format: "%.0f°", d.position.altitude)),
340            ("Direction", String(format: "%.0f° %@", d.position.azimuth, compass(d.position.azimuth))),
341            ("Magnitude", String(format: "%.1f", d.magnitude)),
342            (d.body == .moon ? "Illuminated" : "Phase", String(format: "%.0f%%", d.phaseFraction * 100)),
343            ("Distance", distance),
344            ("Next rise", time(d.rise)),
345            ("Next set", time(d.set)),
346        ]
347        return Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 4) {
348            ForEach(rows, id: \.0) { row in
349                GridRow {
350                    Text(row.0).dimmed(0.7)
351                    Text(row.1).monospacedDigit()
352                }
353                .font(.footnote)
354            }
355        }
356    }
357
358    /// VoiceOver summary: which way the view faces and what bright bodies are up.
359    private func skyDescription(_ scene: SkyScene, azimuth: Double) -> String {
360        let up = scene.bodies.filter { $0.position.altitude > 0 && $0.magnitude <= 6 }.map { b -> String in
361            let name = b.body.rawValue.capitalized
362            return "\(name), \(Int(b.position.altitude.rounded())) degrees up in the \(compass(b.position.azimuth))"
363        }
364        let facing = "Sky facing \(compass(azimuth))."
365        return up.isEmpty ? facing + " No planets or Moon above the horizon." : facing + " Above the horizon: " + up.joined(separator: "; ") + "."
366    }
367
368    private func compass(_ azimuth: Double) -> String {
369        let points = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]
370        return points[Int(((azimuth + 22.5) / 45).rounded(.down)) % 8]
371    }
372}
373
374/// Draw timings for the debug readout. Written from the Canvas closure, read once a second.
375final class DrawStats: @unchecked Sendable {
376    private let lock = NSLock()
377    private var samples: [Duration] = []
378
379    func record(_ d: Duration) {
380        lock.withLock {
381            samples.append(d)
382            if samples.count > 120 { samples.removeFirst(samples.count - 120) }
383        }
384    }
385
386    func summary(build: Duration) -> String {
387        let s = lock.withLock { samples }
388        let ms = s.map { Double($0.components.attoseconds) / 1e15 + Double($0.components.seconds) * 1000 }.sorted()
389        guard let median = ms.isEmpty ? nil : ms[ms.count / 2], let worst = ms.last else { return "draw –" }
390        let b = Double(build.components.attoseconds) / 1e15 + Double(build.components.seconds) * 1000
391        return String(format: "draw %.1f ms median, %.1f ms max · scene %.0f ms", median, worst, b)
392    }
393}
394
395/// SkyEngine's Body, named so it isn't shadowed by View.Body.
396private typealias SkyBody = Body