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

411 lines · 20065 bytes

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