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 ed4ae2da67

ed4ae2da6744a7ac132e649fb8d070e261c595e2

parent: 4615aa0258

Unsigned

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

Sky: the Milky Way from Gaia (!121)

- `scripts/make-milkyway.swift`: finds the map ellipse (semi-axes 1999.5 × 999 px, 2:1), converts each 2° J2000 cell centre to galactic l, b (IAU 1958 pole), samples a 5 × 5 patch at its Hammer–Aitoff position, subtracts the median at |b| > 60°, scales the 99.5th percentile to 255. Checks: galactic centre 209, both poles 0, LMC 181, Cygnus 104.
- `Catalog.milkyWay` (16 KB resource) and `SkyScene.milkyWay`: cells over 48 and above −3°, placed with the stars. `SkyView.drawMilkyWay`: discs 1.2° in radius in eight opacity steps, in a layer blurred by about a cell; red in night mode.
- Settings → "Milky Way" (`showMilkyWay`, on); credit in the Settings footnote and THIRD_PARTY.org.
- Rendered on macOS (Greenwich, 15 Aug 23:00 UTC): band from Cygnus to Sagittarius with the rift. Draw time on a device not measured; the Sky tab shows it. All package tests pass; iOS builds.

Layout: unified · split

App/Sources/SettingsScreen.swift +4 −1
@@ -23,6 +23,7 @@ enum SettingsKey {
2323 static let dailySummaryMinutes = "dailySummaryMinutes"
2424 /// Messier objects on the sky chart.
2525 static let showDeepSky = "showDeepSky"
26 static let showMilkyWay = "showMilkyWay"
2627 /// Cloud forecasts from Apple Weather; off unless turned on.
2728 static let cloudForecast = "cloudForecast"
2829 /// The eclipse eye-safety note has been shown before a countdown or rehearsal.
@@ -77,6 +78,7 @@ struct SettingsScreen: View {
7778 @AppStorage(SettingsKey.nightMode) private var nightMode = "auto"
7879 @AppStorage(SettingsKey.skyCulture) private var skyCulture = "western"
7980 @AppStorage(SettingsKey.showDeepSky) private var showDeepSky = true
81 @AppStorage(SettingsKey.showMilkyWay) private var showMilkyWay = true
8082 @AppStorage(SettingsKey.onboarded) private var onboarded = true
8183 @Environment(\.dismiss) private var dismiss
8284 @State private var alerts = AuroraAlerts.shared
@@ -158,6 +160,7 @@ struct SettingsScreen: View {
158160 ForEach(Catalog.skyCultures) { Text($0.name).tag($0.id) }
159161 }
160162 Toggle("Messier objects", isOn: $showDeepSky)
163 Toggle("Milky Way", isOn: $showMilkyWay)
161164 Picker("Night mode", selection: $nightMode) {
162165 Text("Off").tag("off")
163166 Text("On").tag("on")
@@ -166,7 +169,7 @@ struct SettingsScreen: View {
166169 } header: {
167170 Text("Display")
168171 } footer: {
169 Text("Constellations from other cultures come from Stellarium's sky cultures and are drawn over the same stars; figures with stars fainter than the app's catalogue are shortened. Messier objects are galaxies, clusters and nebulae, drawn with atlas symbols; most need binoculars. Night mode draws the sky in red to keep your eyes adapted to the dark. After dark turns it on once the Sun is 12° below the horizon.")
172 Text("Constellations from other cultures come from Stellarium's sky cultures and are drawn over the same stars; figures with stars fainter than the app's catalogue are shortened. Messier objects are galaxies, clusters and nebulae, drawn with atlas symbols; most need binoculars. The Milky Way is from ESA's Gaia (ESA/Gaia/DPAC, CC BY-SA 3.0 IGO). Night mode draws the sky in red to keep your eyes adapted to the dark. After dark turns it on once the Sun is 12° below the horizon.")
170173 }
171174 Section("About") {
172175 LabeledContent("Version", value: Bundle.main.versionString)
App/Sources/SkyScreen.swift +2 −1
@@ -13,6 +13,7 @@ struct SkyScreen: View {
1313 @AppStorage(SettingsKey.nightMode) private var nightMode = "auto"
1414 @AppStorage(SettingsKey.skyCulture) private var skyCulture = "western"
1515 @AppStorage(SettingsKey.showDeepSky) private var showDeepSky = true
16 @AppStorage(SettingsKey.showMilkyWay) private var showMilkyWay = true
1617 @State private var showSettings = false
1718 @State private var showEvents = false
1819 @State private var showLog = false
@@ -46,7 +47,7 @@ struct SkyScreen: View {
4647 style.background.ignoresSafeArea()
4748 if let scene = model.scene {
4849 let view = current(width: geo.size.width)
49 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), showDeepSky: showDeepSky) { [stats] d in
50 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), showDeepSky: showDeepSky, showMilkyWay: showMilkyWay) { [stats] d in
5051 stats.record(d)
5152 }
5253 .ignoresSafeArea()
PLAN.org +3 −1
@@ -530,7 +530,9 @@ Worker; DSN Now freshness; NASA/ESA image licences; 26 LoC plates bundled.
530530
531531** v5.2: Sky
532532- Milky Way from ESA's "Gaia's sky in colour" (CC BY-SA), clipped before
533 projection.
533 projection. Done: 2° equatorial grid from the Hammer–Aitoff image
534 (=scripts/make-milkyway.swift=), cells under −3° dropped before
535 projection, drawn as blurred discs; Settings switch.
534536- Comets in the Sky tab and the orrery from JPL SBDB, fetched daily by the
535537 Worker. The orrery has periodic comets (Kepler.swift); needs parabolic and
536538 hyperbolic orbits. Then bright asteroids.
Packages/MoonriseKit/Package.swift +1 −1
@@ -23,7 +23,7 @@ let package = Package(
2323 .target(
2424 name: "SkyRenderer",
2525 dependencies: ["SkyEngine"],
26 resources: [.copy("Resources/bsc5.json"), .copy("Resources/constellations.json"), .copy("Resources/coastline.json"), .copy("Resources/spacecraft.json"), .copy("Resources/skycultures.json"), .copy("Resources/messier.json")]
26 resources: [.copy("Resources/bsc5.json"), .copy("Resources/constellations.json"), .copy("Resources/coastline.json"), .copy("Resources/spacecraft.json"), .copy("Resources/skycultures.json"), .copy("Resources/messier.json"), .copy("Resources/milkyway.bin")]
2727 ),
2828 .target(name: "Feeds", dependencies: ["SkyEngine"]),
2929 .target(name: "ObservingLog", dependencies: ["Library", "SkyRenderer"]),
Packages/MoonriseKit/Sources/SkyRenderer/Resources/milkyway.bin added

Binary file not shown.

Packages/MoonriseKit/Sources/SkyRenderer/SkyScene.swift +15
@@ -97,6 +97,13 @@ public enum Catalog {
9797 return try! JSONDecoder().decode([Constellation].self, from: Data(contentsOf: url))
9898 }()
9999
100 /// Milky Way brightness on a 2° J2000 grid (rows Dec −89° to +89°, columns RA 1° to 359°), from ESA's "Gaia's sky
101 /// in colour" (ESA/Gaia/DPAC, CC BY-SA 3.0 IGO), built by scripts/make-milkyway.swift.
102 public static let milkyWay: [UInt8] = {
103 let url = Bundle.module.url(forResource: "milkyway", withExtension: "bin")!
104 return [UInt8](try! Data(contentsOf: url))
105 }()
106
100107 /// Built by scripts/make-messier.py.
101108 public static let deepSky: [DeepSkyObject] = {
102109 let url = Bundle.module.url(forResource: "messier", withExtension: "json")!
@@ -133,6 +140,10 @@ public struct SkyScene: Sendable {
133140 public var deepSky: [PlacedDeepSky]
134141 /// Moon's elongation east of the sun, degrees (0 new, 180 full).
135142 public var moonPhase: Double
143 /// Milky Way cells brighter than `milkyWayFloor`, above −3° (the rest are dropped before projection).
144 public var milkyWay: [(position: Horizontal, value: UInt8)]
145
146 static let milkyWayFloor: UInt8 = 48
136147
137148 public init(date: Date, observer: Observer, magnitudeLimit: Double = 6.5) throws {
138149 self.date = date
@@ -153,5 +164,9 @@ public struct SkyScene: Sendable {
153164 )
154165 }
155166 moonPhase = try SkyEngine.moonPhase(at: date)
167 let cells = Catalog.milkyWay.enumerated().filter { $0.element > Self.milkyWayFloor }
168 let centres = cells.map { (ra: 1 + 2 * Double($0.offset % 180), dec: -89 + 2 * Double($0.offset / 180)) }
169 let placed = SkyEngine.horizontal(j2000: centres, at: date, from: observer)
170 milkyWay = zip(placed, cells).filter { $0.0.altitude > -3 }.map { ($0.0, $0.1.element) }
156171 }
157172}
Packages/MoonriseKit/Sources/SkyRenderer/SkyView.swift +25 −1
@@ -40,6 +40,7 @@ public struct SkyStyle: Sendable {
4040 public var moonLight = Color(red: 0.93, green: 0.91, blue: 0.85)
4141 public var moonDark = Color(red: 0.16, green: 0.20, blue: 0.27)
4242 public var planet = Color(red: 0.95, green: 0.84, blue: 0.60)
43 public var milkyWay = Color(red: 0.75, green: 0.80, blue: 0.95)
4344 /// Rings and lines for whatever a tour is pointing at.
4445 public var highlight = Color(red: 1.0, green: 0.78, blue: 0.35)
4546 /// Draw stars in a single red, for dark-adapted eyes.
@@ -63,6 +64,7 @@ public struct SkyStyle: Sendable {
6364 s.highlight = red
6465 s.moonDark = Color(red: 0.12, green: 0, blue: 0)
6566 s.planet = red
67 s.milkyWay = red
6668 s.monochromeStars = red
6769 return s
6870 }()
@@ -112,15 +114,17 @@ public struct SkyView: View {
112114 public var culture: SkyCulture?
113115 public var highlight: SkyHighlight?
114116 public var showDeepSky: Bool
117 public var showMilkyWay: Bool
115118 /// Called after each draw with the time the draw took.
116119 public var onDraw: (@Sendable (Duration) -> Void)?
117120
118 public init(scene: SkyScene, centerAzimuth: Double = 180, centerAltitude: Double = 55, fieldOfView: Double = 110, style: SkyStyle = SkyStyle(), culture: SkyCulture? = nil, highlight: SkyHighlight? = nil, showDeepSky: Bool = true, onDraw: (@Sendable (Duration) -> Void)? = nil) {
121 public init(scene: SkyScene, centerAzimuth: Double = 180, centerAltitude: Double = 55, fieldOfView: Double = 110, style: SkyStyle = SkyStyle(), culture: SkyCulture? = nil, highlight: SkyHighlight? = nil, showDeepSky: Bool = true, showMilkyWay: Bool = true, onDraw: (@Sendable (Duration) -> Void)? = nil) {
119122 self.scene = scene
120123 self.style = style
121124 self.culture = culture
122125 self.highlight = highlight
123126 self.showDeepSky = showDeepSky
127 self.showMilkyWay = showMilkyWay
124128 self.centerAzimuth = centerAzimuth
125129 self.centerAltitude = centerAltitude
126130 self.fieldOfView = fieldOfView
@@ -132,6 +136,7 @@ public struct SkyView: View {
132136 let start = ContinuousClock.now
133137 let p = Projection(centerAzimuth: centerAzimuth, centerAltitude: centerAltitude, fieldOfView: fieldOfView, size: size)
134138 context.fill(Path(CGRect(origin: .zero, size: size)), with: .color(style.background))
139 if showMilkyWay { drawMilkyWay(&context, p) }
135140 drawConstellations(&context, p)
136141 drawStars(&context, p)
137142 if showDeepSky { drawDeepSky(&context, p) }
@@ -142,6 +147,25 @@ public struct SkyView: View {
142147 }
143148 }
144149
150 /// Discs a little larger than a 2° cell in eight steps of brightness, blurred by about a cell so the band reads
151 /// as a glow rather than as cells.
152 func drawMilkyWay(_ context: inout GraphicsContext, _ p: Projection) {
153 let r = 1.2 * Double(p.size.width) / fieldOfView
154 let floor = Double(SkyScene.milkyWayFloor)
155 var bins = [Path](repeating: Path(), count: 8)
156 for cell in scene.milkyWay {
157 guard let pt = p.point(cell.position), pt.x > -r, pt.y > -r, pt.x < p.size.width + r, pt.y < p.size.height + r else { continue }
158 let step = Int((Double(cell.value) - floor) / (256 - floor) * 8)
159 bins[min(7, max(0, step))].addEllipse(in: CGRect(x: pt.x - r, y: pt.y - r, width: 2 * r, height: 2 * r))
160 }
161 context.drawLayer { layer in
162 layer.addFilter(.blur(radius: r))
163 for (i, path) in bins.enumerated() where !path.isEmpty {
164 layer.fill(path, with: .color(style.milkyWay.opacity(0.05 + 0.035 * Double(i))))
165 }
166 }
167 }
168
145169 func drawConstellations(_ context: inout GraphicsContext, _ p: Projection) {
146170 if let culture {
147171 drawCulture(culture, &context, p)
THIRD_PARTY.org +1
@@ -12,6 +12,7 @@
1212| Sun texture for the 3D solar system (=App/Globes/sun.jpg=) | generated noise, made for this app | — | — |
1313| Orbital elements for Ceres, Haumea, Makemake, Eris and seven comets (=Packages/MoonriseKit/Sources/SkyEngine/Kepler.swift=) | JPL Small-Body Database, fetched 2026-10-19 | NASA/JPL, no published restrictions | https://ssd.jpl.nasa.gov/tools/sbdb_lookup.html |
1414| ConstellationLines v1.4, Copyright (c) 2005-2026 Marc van der Sluys | =Packages/MoonriseKit/Sources/SkyRenderer/Resources/constellations.json= | CC BY 4.0 | https://github.com/MarcvdSluys/ConstellationLines, doi:10.5281/zenodo.10397192 |
15| Gaia's sky in colour, ESA/Gaia/DPAC: Milky Way brightness on a 2° grid (=scripts/make-milkyway.swift=) | =Packages/MoonriseKit/Sources/SkyRenderer/Resources/milkyway.bin= | CC BY-SA 3.0 IGO; the derived grid is under the same licence | https://www.esa.int/ESA_Multimedia/Images/2018/04/Gaia_s_sky_in_colour2 |
1516| Natural Earth 1:110m coastline v5.1.2 | =Packages/MoonriseKit/Sources/SkyRenderer/Resources/coastline.json= | Public domain | https://www.naturalearthdata.com |
1617| Launch Library 2 (The Space Devs) | fetched at runtime by =server/= | Free API; credit shown in the app | https://thespacedevs.com/llapi |
1718| JPL Horizons spacecraft vectors (Voyager 1, 2, Pioneer 10, 11, New Horizons) | =Packages/MoonriseKit/Sources/SkyRenderer/Resources/spacecraft.json= | NASA/JPL, no published restrictions | https://ssd.jpl.nasa.gov/horizons/ |
scripts/make-milkyway.swift added +75
@@ -0,0 +1,75 @@
1// Milky Way brightness on a 2° equatorial grid from ESA's "Gaia's sky in colour" (ESA/Gaia/DPAC, CC BY-SA 3.0 IGO),
2// a Hammer–Aitoff map in galactic coordinates with longitude increasing to the left.
3//
4// swift scripts/make-milkyway.swift Gaia_s_sky_in_colour.jpg
5//
6// Writes Packages/MoonriseKit/Sources/SkyRenderer/Resources/milkyway.bin: 180 × 90 bytes, rows from Dec −89° to
7// +89°, columns from RA 1° to 359°, each the cell's brightness above the high-latitude sky, scaled so the
8// 99.5th percentile is 255. The file is an adaptation of the image and is under the same licence.
9import CoreGraphics
10import Foundation
11import ImageIO
12
13let input = URL(fileURLWithPath: CommandLine.arguments[1])
14let source = CGImageSourceCreateWithURL(input as CFURL, nil)!
15let image = CGImageSourceCreateImageAtIndex(source, 0, nil)!
16let w = image.width, h = image.height
17var pixels = [UInt8](repeating: 0, count: w * h * 4)
18let context = CGContext(data: &pixels, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 4,
19 space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!
20context.draw(image, in: CGRect(x: 0, y: 0, width: w, height: h))
21
22func luminance(_ x: Int, _ y: Int) -> Double {
23 let i = (y * w + x) * 4
24 return (0.2126 * Double(pixels[i]) + 0.7152 * Double(pixels[i + 1]) + 0.0722 * Double(pixels[i + 2])) / 255
25}
26
27// The map's ellipse: the extent of pixels brighter than the black surround along the middle row and column.
28let midY = h / 2, midX = w / 2
29let xs = (0..<w).filter { luminance($0, midY) > 0.05 }, ys = (0..<h).filter { luminance(midX, $0) > 0.05 }
30let cx = Double(xs.first! + xs.last!) / 2, cy = Double(ys.first! + ys.last!) / 2
31let ax = Double(xs.last! - xs.first!) / 2, ay = Double(ys.last! - ys.first!) / 2
32print("ellipse centre", cx, cy, "semi-axes", ax, ay)
33
34let r = Double.pi / 180
35/// J2000 equatorial to galactic (IAU 1958 pole at RA 192.85948°, Dec 27.12825°; node 32.93192°).
36func galactic(ra: Double, dec: Double) -> (l: Double, b: Double) {
37 let a0 = 192.85948 * r, d0 = 27.12825 * r, l0 = 122.93192 * r
38 let a = ra * r, d = dec * r
39 let sinb = sin(d) * sin(d0) + cos(d) * cos(d0) * cos(a - a0)
40 let y = cos(d) * sin(a - a0), x = sin(d) * cos(d0) - cos(d) * sin(d0) * cos(a - a0)
41 return ((l0 - atan2(y, x)) / r, asin(sinb) / r)
42}
43
44/// Mean luminance in a 5 × 5 patch at the Hammer–Aitoff position of (l, b).
45func sample(l: Double, b: Double) -> Double {
46 let lw = remainder(l, 360) * r, bb = b * r
47 let z = (1 + cos(bb) * cos(lw / 2)).squareRoot()
48 let x = 2 * 2.0.squareRoot() * cos(bb) * sin(lw / 2) / z, y = 2.0.squareRoot() * sin(bb) / z
49 let px = Int(cx - x / (2 * 2.0.squareRoot()) * ax), py = Int(cy - y / 2.0.squareRoot() * ay)
50 var sum = 0.0, n = 0.0
51 for dy in -2...2 { for dx in -2...2 {
52 let qx = min(max(px + dx, 0), w - 1), qy = min(max(py + dy, 0), h - 1)
53 sum += luminance(qx, qy); n += 1
54 } }
55 return sum / n
56}
57
58var raw: [Double] = [], high: [Double] = []
59for row in 0..<90 {
60 let dec = -89 + 2 * Double(row)
61 for col in 0..<180 {
62 let ra = 1 + 2 * Double(col)
63 let g = galactic(ra: ra, dec: dec)
64 let v = sample(l: g.l, b: g.b)
65 raw.append(v)
66 if abs(g.b) > 60 { high.append(v) }
67 }
68}
69let floor = high.sorted()[high.count / 2]
70let above = raw.map { max(0, $0 - floor) }
71let top = above.sorted()[Int(Double(above.count) * 0.995)]
72let bytes = above.map { UInt8(min(255, ($0 / top * 255).rounded())) }
73let out = URL(fileURLWithPath: "Packages/MoonriseKit/Sources/SkyRenderer/Resources/milkyway.bin")
74try! Data(bytes).write(to: out)
75print("floor", floor, "top", top, "cells over 40:", bytes.filter { $0 > 40 }.count)