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

Commit c455497599

c455497599fad7ea435b94359845791fa30e3a09

parent: f2a4ee5c57

Unsigned

cmc <hello@cleberg.net> · 2026-10-22 03:19 UTC

Eclipse: drive to the nearest place with 95% of the centre-line duration (!112)

- `EclipsePath.candidates(near:share:limit:spacingKm:)`: points between the minute cross-sections (4 per minute) and across the band within √(1 − share²) of the half-width from the centre line (31% for 95%, uniform-shadow approximation), nearest first, each ≥ 25 km from the ones before.
- `EclipsePath.site(_:share:)`: confirms with `LocalEclipse.at` that the central phase lasts ≥ 95% of the centre line at the same point of the path.
- Eclipse screen, "Getting to the path": inside the band, says so; otherwise tries up to 40 candidates, about one `MKReverseGeocodingRequest` a second, and takes the first on land. Offshore, Apple returns the country as the city ("Alboran Sea, Spain"), so land means a city that differs from the region. Shows place, straight-line distance and both durations; "Directions in Maps" opens driving directions.
- Checked against Apple's geocoder on 2 August 2027: Madrid → Tarifa, 518 km, 280 of 293 s (13 lookups); Seville → Tarifa, 158 km; Cairo → Minya, 276 km, 374 of 383 s; London → Ain Tedles, Algeria, 1,726 km.
- Test for band candidates. SkyEngine tests pass; iOS builds.

Layout: unified · split

App/Sources/EclipseDrive.swift added +67
@@ -0,0 +1,67 @@
1import MapKit
2import SkyEngine
3import SwiftUI
4
5/// The nearest place on land where the central phase lasts at least 95% of its centre-line length, with directions.
6struct EclipseDrive: View {
7 var path: EclipsePath
8 var site: Observer
9 var accent: Color
10 @State private var found: (site: EclipseSite, item: MKMapItem)?
11 @State private var inBand = false
12 @State private var searched = false
13
14 private var central: String { path.kind == "Total" ? "totality" : "the annular phase" }
15
16 var body: some View {
17 VStack(alignment: .leading, spacing: 8) {
18 Text("Getting to the path").font(.caption2.weight(.medium)).textCase(.uppercase).tracking(0.8).dimmed(0.6)
19 if inBand {
20 Text("You are within the band where \(central) lasts at least 95% as long as on the centre line.").font(.subheadline)
21 } else if let (s, item) = found {
22 Text("Nearest place with at least 95% of the centre-line duration: \(item.address?.shortAddress ?? item.name ?? "unnamed place"), \(Int(s.distanceKm.rounded())) km away in a straight line. \(central.prefix(1).uppercased() + central.dropFirst()) there lasts \(minutes(s.duration)); on the centre line, \(minutes(s.centerDuration)).")
23 .font(.subheadline)
24 Button("Directions in Maps") {
25 item.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving])
26 }
27 .tint(accent)
28 Text("Arrive the day before if you can: roads near the path fill up. Do not drive during the eclipse.")
29 .font(.footnote).dimmed(0.7)
30 } else if searched {
31 Text("No place on land within reach of the path could be found. Check your connection.").font(.footnote).dimmed(0.7)
32 } else {
33 ProgressView().tint(accent)
34 }
35 }
36 .task(id: [(site.latitude * 10).rounded(), (site.longitude * 10).rounded()]) {
37 found = nil
38 inBand = false
39 searched = false
40 let path = path, site = site
41 let candidates = await Task.detached { path.candidates(near: site) }.value
42 if let first = candidates.first, first.distanceKm < 3, await Task.detached(operation: { path.site(first) }).value != nil {
43 inBand = true
44 return
45 }
46 // Nearest first, about one lookup a second. Offshore, Apple's geocoder names the sea and gives the country as
47 // the city ("Alboran Sea, Spain"); on land the city is a locality.
48 for c in candidates.prefix(40) {
49 guard !Task.isCancelled else { return }
50 guard let s = await Task.detached(operation: { path.site(c) }).value else { continue }
51 if let request = MKReverseGeocodingRequest(location: CLLocation(latitude: c.latitude, longitude: c.longitude)),
52 let item = try? await request.mapItems.first, let a = item.addressRepresentations,
53 let region = a.regionName, let city = a.cityName, !city.isEmpty, city != region {
54 found = (s, item)
55 break
56 }
57 try? await Task.sleep(for: .seconds(1))
58 }
59 searched = true
60 }
61 }
62
63 private func minutes(_ s: TimeInterval) -> String {
64 let n = Int(s.rounded())
65 return "\(n / 60) min \(n % 60) s"
66 }
67}
App/Sources/EclipseScreen.swift +1
@@ -52,6 +52,7 @@ struct EclipseScreen: View {
52 ProgressView().tint(ink).frame(maxWidth: .infinity, minHeight: 200) 52 ProgressView().tint(ink).frame(maxWidth: .infinity, minHeight: 200)
53 } 53 }
54 if loaded { here } 54 if loaded { here }
55 if let path { EclipseDrive(path: path, site: site, accent: accent) }
55 if let timeline { 56 if let timeline {
56 SunDiagram(timeline: timeline, ink: ink, accent: accent) 57 SunDiagram(timeline: timeline, ink: ink, accent: accent)
57 dayTools(timeline) 58 dayTools(timeline)
Packages/MoonriseKit/Sources/SkyEngine/EclipseSite.swift added +74
@@ -0,0 +1,74 @@
1import Foundation
2
3/// A place where totality or annularity lasts nearly as long as on the centre line, for driving to.
4public struct EclipseSite: Sendable {
5 public var latitude: Double
6 public var longitude: Double
7 public var duration: TimeInterval
8 /// On the centre line at the same point of the path.
9 public var centerDuration: TimeInterval
10 /// Straight-line distance from the observer.
11 public var distanceKm: Double
12}
13
14extension EclipsePath {
15 /// A point in the band of the path where the central phase should last at least `share` of its centre-line length.
16 public struct Candidate: Sendable {
17 public var latitude: Double
18 public var longitude: Double
19 var center: (lat: Double, lon: Double)
20 public var distanceKm: Double
21 }
22
23 /// Points in the band nearest `observer` first, each at least `spacingKm` from those before it, up to `limit`.
24 /// With a uniform shadow the duration falls off as √(1 − x²) at a fraction x of the way to the limit, so the band
25 /// is within √(1 − share²) of the centre line (31% for 95%). Some may be at sea; check each with `site(_:share:)`.
26 public func candidates(near observer: Observer, share: Double = 0.95, limit: Int = 60, spacingKm: Double = 25) -> [Candidate] {
27 let reach = (1 - share * share).squareRoot()
28 var out: [Candidate] = []
29 for (a, b) in zip(points, points.dropFirst()) {
30 guard let an = a.north, let asouth = a.south, let bn = b.north, let bs = b.south else { continue }
31 for step in 0..<4 {
32 let u = Double(step) / 4
33 let c = Self.mix(a.center, b.center, u), n = Self.mix(an, bn, u), s = Self.mix(asouth, bs, u)
34 for k in -4...4 {
35 let t = reach * Double(k) / 4
36 let p = Self.mix(c, t >= 0 ? n : s, abs(t))
37 out.append(Candidate(latitude: p.lat, longitude: p.lon, center: c,
38 distanceKm: Self.distanceKm(p, (observer.latitude, observer.longitude))))
39 }
40 }
41 }
42 var picked: [Candidate] = []
43 for c in out.sorted(by: { $0.distanceKm < $1.distanceKm }) where picked.count < limit {
44 if picked.allSatisfy({ Self.distanceKm(($0.latitude, $0.longitude), (c.latitude, c.longitude)) >= spacingKm }) { picked.append(c) }
45 }
46 return picked
47 }
48
49 /// The candidate with its durations, if a full local calculation confirms at least `share` of the centre line.
50 public func site(_ c: Candidate, share: Double = 0.95) -> EclipseSite? {
51 guard let center = Self.duration(at: c.center, near: peak), let d = Self.duration(at: (c.latitude, c.longitude), near: peak),
52 d >= share * center else { return nil }
53 return EclipseSite(latitude: c.latitude, longitude: c.longitude, duration: d, centerDuration: center, distanceKm: c.distanceKm)
54 }
55
56 static func duration(at p: (lat: Double, lon: Double), near date: Date) -> TimeInterval? {
57 guard let l = LocalEclipse.at(Observer(latitude: p.lat, longitude: p.lon), near: date),
58 let b = l.centralBegin, let e = l.centralEnd else { return nil }
59 return e.timeIntervalSince(b)
60 }
61
62 /// Linear in latitude and longitude, the short way round in longitude.
63 static func mix(_ a: (lat: Double, lon: Double), _ b: (lat: Double, lon: Double), _ u: Double) -> (lat: Double, lon: Double) {
64 let dLon = remainder(b.lon - a.lon, 360)
65 return (a.lat + (b.lat - a.lat) * u, remainder(a.lon + dLon * u, 360))
66 }
67
68 /// Great-circle distance on a 6,371 km sphere.
69 static func distanceKm(_ a: (lat: Double, lon: Double), _ b: (lat: Double, lon: Double)) -> Double {
70 let r = Double.pi / 180
71 let h = pow(sin((b.lat - a.lat) * r / 2), 2) + cos(a.lat * r) * cos(b.lat * r) * pow(sin((b.lon - a.lon) * r / 2), 2)
72 return 2 * 6371 * asin(min(1, h.squareRoot()))
73 }
74}
Packages/MoonriseKit/Tests/SkyEngineTests/EclipsePathTests.swift +14
@@ -84,3 +84,17 @@ private let nasa2027: [(name: String, lat: Double, lon: Double, contacts: [Doubl
84 let d = ((craft - moon) * (craft - moon)).sum().squareRoot() 84 let d = ((craft - moon) * (craft - moon)).sum().squareRoot()
85 #expect(d < 3_000) 85 #expect(d < 3_000)
86} 86}
87
88@Test func bandCandidatesHaveNinetyFivePercentOfTheCentreLine() throws {
89 let path = try #require(EclipsePath.compute(near: Date(timeIntervalSince1970: 1_817_201_220)))
90 // Madrid is north of the 2 August 2027 path; Tarifa is near its centre line.
91 let madrid = path.candidates(near: Observer(latitude: 40.4168, longitude: -3.7038))
92 #expect(madrid.count == 60)
93 #expect(zip(madrid, madrid.dropFirst()).allSatisfy { $0.distanceKm <= $1.distanceKm })
94 let sites = madrid.prefix(10).compactMap { path.site($0) }
95 #expect(sites.count >= 8)
96 #expect(sites.allSatisfy { $0.duration >= 0.95 * $0.centerDuration && $0.latitude < 38 })
97 let tarifa = try #require(path.candidates(near: Observer(latitude: 36.0143, longitude: -5.6044)).first)
98 #expect(tarifa.distanceKm < 30)
99 #expect(path.site(tarifa) != nil)
100}