Commit b54fbb21d2
Unsigned
Layout: unified · split
App/Sources/SkyModel.swift +21 −3
| @@ -9,8 +9,8 @@ import SkyRenderer | |||
| 9 | 9 | ||
| 10 | /// Serializes Astronomy Engine calls, which are not thread-safe. | 10 | /// Serializes Astronomy Engine calls, which are not thread-safe. |
| 11 | actor Astronomer { | 11 | actor Astronomer { |
| 12 | func scene(at date: Date, from observer: Observer) throws -> SkyScene { | 12 | func scene(at date: Date, from observer: Observer, smallBodies: [SmallBody] = []) throws -> SkyScene { |
| 13 | try SkyScene(date: date, observer: observer) | 13 | try SkyScene(date: date, observer: observer, smallBodies: smallBodies) |
| 14 | } | 14 | } |
| 15 | 15 | ||
| 16 | func details(of body: Body, at date: Date, from observer: Observer) throws -> BodyDetails { | 16 | func details(of body: Body, at date: Date, from observer: Observer) throws -> BodyDetails { |
| @@ -57,6 +57,9 @@ final class SkyModel: NSObject, CLLocationManagerDelegate { | |||
| 57 | private(set) var spaceWeather: SpaceWeather? | 57 | private(set) var spaceWeather: SpaceWeather? |
| 58 | private(set) var passes: [SatellitePass] = [] | 58 | private(set) var passes: [SatellitePass] = [] |
| 59 | private var elements: [OrbitalElements] = [] | 59 | private var elements: [OrbitalElements] = [] |
| 60 | /// Comets and asteroids from the backend's /v1/smallbodies (JPL SBDB, refreshed daily). | ||
| 61 | private(set) var smallBodies: [SmallBody] = [] | ||
| 62 | private var smallBodiesFetched: Date? | ||
| 60 | private var elementsFetched: Date? | 63 | private var elementsFetched: Date? |
| 61 | private var passesComputed: (at: Date, observer: Observer, elementsFetched: Date?)? | 64 | private var passesComputed: (at: Date, observer: Observer, elementsFetched: Date?)? |
| 62 | private var weatherFetched: Date? | 65 | private var weatherFetched: Date? |
| @@ -138,11 +141,15 @@ final class SkyModel: NSObject, CLLocationManagerDelegate { | |||
| 138 | guard !building else { pending = true; return } | 141 | guard !building else { pending = true; return } |
| 139 | building = true | 142 | building = true |
| 140 | let date = displayedDate, observer = observer, astronomer = astronomer | 143 | let date = displayedDate, observer = observer, astronomer = astronomer |
| 144 | if smallBodiesFetched.map({ Date.now.timeIntervalSince($0) > 3600 }) ?? true { | ||
| 145 | Task { if await refreshSmallBodies() { refresh() } } | ||
| 146 | } | ||
| 147 | let small = smallBodies | ||
| 141 | Task { | 148 | Task { |
| 142 | let clock = ContinuousClock() | 149 | let clock = ContinuousClock() |
| 143 | var scene: SkyScene? | 150 | var scene: SkyScene? |
| 144 | let start = clock.now | 151 | let start = clock.now |
| 145 | scene = try? await astronomer.scene(at: date, from: observer) | 152 | scene = try? await astronomer.scene(at: date, from: observer, smallBodies: small) |
| 146 | lastBuild = clock.now - start | 153 | lastBuild = clock.now - start |
| 147 | if let scene { self.scene = scene } | 154 | if let scene { self.scene = scene } |
| 148 | if offsetHours == 0, historicalYear == nil { tonight = try? await astronomer.tonight(at: date, from: observer) } | 155 | if offsetHours == 0, historicalYear == nil { tonight = try? await astronomer.tonight(at: date, from: observer) } |
| @@ -152,6 +159,17 @@ final class SkyModel: NSObject, CLLocationManagerDelegate { | |||
| 152 | } | 159 | } |
| 153 | } | 160 | } |
| 154 | 161 | ||
| 162 | private struct SmallBodyList: Decodable { var bodies: [SmallBody] } | ||
| 163 | |||
| 164 | /// At most once an hour; the backend refreshes daily. Returns whether the list changed. | ||
| 165 | func refreshSmallBodies() async -> Bool { | ||
| 166 | smallBodiesFetched = .now | ||
| 167 | guard let apiBase, let (data, _) = try? await URLSession.shared.data(from: apiBase.appending(path: "v1/smallbodies")), | ||
| 168 | let list = try? JSONDecoder().decode(SmallBodyList.self, from: data), list.bodies != smallBodies else { return false } | ||
| 169 | smallBodies = list.bodies | ||
| 170 | return true | ||
| 171 | } | ||
| 172 | |||
| 155 | private struct SatelliteList: Decodable { var satellites: [OrbitalElements] } | 173 | private struct SatelliteList: Decodable { var satellites: [OrbitalElements] } |
| 156 | 174 | ||
| 157 | /// Orbital elements from the backend (refreshed hourly), then passes for the next three days. | 175 | /// Orbital elements from the backend (refreshed hourly), then passes for the next three days. |
App/Sources/SolarSystem3D.swift +5
| @@ -372,6 +372,11 @@ struct SolarSystem3DView: View { | |||
| 372 | let shown = layers.comets && (Self.mainComets.contains(c.id) || showerParents.contains(c.id)) | 372 | let shown = layers.comets && (Self.mainComets.contains(c.id) || showerParents.contains(c.id)) |
| 373 | out.append(SolarMarker(id: "comet:\(c.id)", name: c.name, kind: .comet, scene: s, radius: dot(s), visible: shown)) | 373 | out.append(SolarMarker(id: "comet:\(c.id)", name: c.name, kind: .comet, scene: s, radius: dot(s), visible: shown)) |
| 374 | } | 374 | } |
| 375 | // Comets near perihelion from JPL's Small-Body Database, through the backend. | ||
| 376 | for b in SkyModel.shared.smallBodies where b.isComet { | ||
| 377 | let s = map.point(b.position(at: date)) | ||
| 378 | out.append(SolarMarker(id: "sbdb:\(b.name)", name: b.name, kind: .comet, scene: s, radius: dot(s), visible: layers.comets)) | ||
| 379 | } | ||
| 375 | return out | 380 | return out |
| 376 | } | 381 | } |
| 377 | 382 | ||
PLAN.org +5 −1
| @@ -535,7 +535,11 @@ Worker; DSN Now freshness; NASA/ESA image licences; 26 LoC plates bundled. | |||
| 535 | projection, drawn as blurred discs; Settings switch. | 535 | projection, drawn as blurred discs; Settings switch. |
| 536 | - Comets in the Sky tab and the orrery from JPL SBDB, fetched daily by the | 536 | - Comets in the Sky tab and the orrery from JPL SBDB, fetched daily by the |
| 537 | Worker. The orrery has periodic comets (Kepler.swift); needs parabolic and | 537 | Worker. The orrery has periodic comets (Kepler.swift); needs parabolic and |
| 538 | hyperbolic orbits. Then bright asteroids. | 538 | hyperbolic orbits. Then bright asteroids. Done: =/v1/smallbodies= (comets with q < 3 AU and perihelion |
| 539 | within 400 days, numbered asteroids H < 7 inside 6 AU; two SBDB requests a | ||
| 540 | day); =SmallBody= propagates elliptic, near-parabolic and hyperbolic orbits | ||
| 541 | (Ceres 23″ and 0.001 mag from Horizons); shown to magnitude 9 on the sky | ||
| 542 | chart and as comet markers on the 3D orrery. | ||
| 539 | - Stars fainter than V 6.5 from Tycho-2 to V 9 (about 110k stars, about | 543 | - Stars fainter than V 6.5 from Tycho-2 to V 9 (about 110k stars, about |
| 540 | 1.6 MB binary), NGC objects, a deeper zoom and eyepiece field-of-view | 544 | 1.6 MB binary), NGC objects, a deeper zoom and eyepiece field-of-view |
| 541 | circles from the equipment inventory. Merge: drop Tycho-2 stars matched to | 545 | circles from the equipment inventory. Merge: drop Tycho-2 stars matched to |
Packages/MoonriseKit/Sources/SkyEngine/SmallBody.swift added +92
| @@ -0,0 +1,92 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | /// A comet or asteroid from JPL's Small-Body Database, propagated as a two-body orbit from its perihelion: elliptic, | ||
| 4 | /// near-parabolic or hyperbolic. Planetary perturbations are ignored, so positions drift by up to a degree or so | ||
| 5 | /// over a year from the elements' epoch. | ||
| 6 | public struct SmallBody: Sendable, Equatable, Codable, Identifiable { | ||
| 7 | public enum Brightness: Sendable, Equatable, Codable { | ||
| 8 | /// Total magnitude M1 and slope K1: m = M1 + 5 log Δ + K1 log r. | ||
| 9 | case comet(m1: Double, k1: Double) | ||
| 10 | /// H–G system. | ||
| 11 | case asteroid(h: Double, g: Double) | ||
| 12 | } | ||
| 13 | |||
| 14 | public var name: String | ||
| 15 | /// Perihelion distance, AU; eccentricity; inclination, ascending node and argument of perihelion, degrees | ||
| 16 | /// (J2000 ecliptic); time of perihelion, TDB Julian date. | ||
| 17 | public var q: Double, e: Double, i: Double, node: Double, peri: Double, tp: Double | ||
| 18 | public var brightness: Brightness | ||
| 19 | public var id: String { name } | ||
| 20 | |||
| 21 | public init(name: String, q: Double, e: Double, i: Double, node: Double, peri: Double, tp: Double, brightness: Brightness) { | ||
| 22 | self.name = name; self.q = q; self.e = e; self.i = i; self.node = node; self.peri = peri; self.tp = tp; self.brightness = brightness | ||
| 23 | } | ||
| 24 | |||
| 25 | public var isComet: Bool { if case .comet = brightness { true } else { false } } | ||
| 26 | |||
| 27 | /// Gaussian gravitational constant, radians per day. | ||
| 28 | static let k = 0.01720209895 | ||
| 29 | |||
| 30 | /// Heliocentric position in AU on J2000 ecliptic axes. | ||
| 31 | public func position(at date: Date) -> SIMD3<Double> { | ||
| 32 | let dt = date.timeIntervalSince1970 / 86_400 + 2_440_587.5 - tp | ||
| 33 | var x: Double, y: Double | ||
| 34 | if abs(e - 1) < 1e-4 { | ||
| 35 | // Barker's equation: s + s³/3 = k Δt / √(2q³), s = tan(ν/2). | ||
| 36 | let w = 3 * Self.k * dt / (2 * q * q * q).squareRoot() | ||
| 37 | let c = cbrt(w / 2 + (w * w / 4 + 1).squareRoot()) | ||
| 38 | let s = c - 1 / c | ||
| 39 | (x, y) = (q * (1 - s * s), 2 * q * s) | ||
| 40 | } else if e < 1 { | ||
| 41 | let a = q / (1 - e), m = Self.k * dt / pow(a, 1.5) | ||
| 42 | let mm = remainder(m, 2 * .pi) | ||
| 43 | var E = e < 0.8 ? mm : .pi * (mm < 0 ? -1 : 1) | ||
| 44 | for _ in 0..<60 { | ||
| 45 | let d = (E - e * sin(E) - mm) / (1 - e * cos(E)) | ||
| 46 | E -= d | ||
| 47 | if abs(d) < 1e-13 { break } | ||
| 48 | } | ||
| 49 | (x, y) = (a * (cos(E) - e), a * (1 - e * e).squareRoot() * sin(E)) | ||
| 50 | } else { | ||
| 51 | let a = q / (e - 1), m = Self.k * dt / pow(a, 1.5) | ||
| 52 | var h = asinh(m / e) | ||
| 53 | for _ in 0..<60 { | ||
| 54 | let d = (e * sinh(h) - h - m) / (e * cosh(h) - 1) | ||
| 55 | h -= d | ||
| 56 | if abs(d) < 1e-13 { break } | ||
| 57 | } | ||
| 58 | (x, y) = (a * (e - cosh(h)), a * (e * e - 1).squareRoot() * sinh(h)) | ||
| 59 | } | ||
| 60 | let r = Double.pi / 180 | ||
| 61 | let (cO, sO) = (cos(node * r), sin(node * r)), (cw, sw) = (cos(peri * r), sin(peri * r)), (ci, si) = (cos(i * r), sin(i * r)) | ||
| 62 | return SIMD3( | ||
| 63 | (cO * cw - sO * sw * ci) * x + (-cO * sw - sO * cw * ci) * y, | ||
| 64 | (sO * cw + cO * sw * ci) * x + (-sO * sw + cO * cw * ci) * y, | ||
| 65 | (sw * si) * x + (cw * si) * y | ||
| 66 | ) | ||
| 67 | } | ||
| 68 | |||
| 69 | /// Astrometric J2000 right ascension and declination (degrees), distances (AU) and magnitude from Earth at `date`; | ||
| 70 | /// light time is ignored. | ||
| 71 | public func apparent(at date: Date) throws -> (ra: Double, dec: Double, r: Double, delta: Double, magnitude: Double) { | ||
| 72 | let p = position(at: date), earth = try SkyEngine.heliocentricEarth(at: date) | ||
| 73 | let g = p - earth | ||
| 74 | let eps = 23.4392911 * Double.pi / 180 | ||
| 75 | let eq = SIMD3(g.x, g.y * cos(eps) - g.z * sin(eps), g.y * sin(eps) + g.z * cos(eps)) | ||
| 76 | let delta = (eq * eq).sum().squareRoot(), r = (p * p).sum().squareRoot(), big = (earth * earth).sum().squareRoot() | ||
| 77 | var ra = atan2(eq.y, eq.x) * 180 / .pi | ||
| 78 | if ra < 0 { ra += 360 } | ||
| 79 | let dec = asin(eq.z / delta) * 180 / .pi | ||
| 80 | let m: Double | ||
| 81 | switch brightness { | ||
| 82 | case .comet(let m1, let k1): | ||
| 83 | m = m1 + 5 * log10(delta) + k1 * log10(r) | ||
| 84 | case .asteroid(let h, let gSlope): | ||
| 85 | let alpha = acos(max(-1, min(1, (r * r + delta * delta - big * big) / (2 * r * delta)))) | ||
| 86 | let t = tan(alpha / 2) | ||
| 87 | let phi1 = exp(-3.33 * pow(t, 0.63)), phi2 = exp(-1.87 * pow(t, 1.22)) | ||
| 88 | m = h + 5 * log10(r * delta) - 2.5 * log10((1 - gSlope) * phi1 + gSlope * phi2) | ||
| 89 | } | ||
| 90 | return (ra, dec, r, delta, m) | ||
| 91 | } | ||
| 92 | } | ||
Packages/MoonriseKit/Sources/SkyRenderer/SkyScene.swift +13 −1
| @@ -153,6 +153,12 @@ public struct PlacedDeepSky: Sendable { | |||
| 153 | public var north: Horizontal | 153 | public var north: Horizontal |
| 154 | } | 154 | } |
| 155 | 155 | ||
| 156 | public struct PlacedSmallBody: Sendable { | ||
| 157 | public var body: SmallBody | ||
| 158 | public var position: Horizontal | ||
| 159 | public var magnitude: Double | ||
| 160 | } | ||
| 161 | |||
| 156 | public struct PlacedBody: Sendable { | 162 | public struct PlacedBody: Sendable { |
| 157 | public var body: Body | 163 | public var body: Body |
| 158 | public var position: Horizontal | 164 | public var position: Horizontal |
| @@ -169,6 +175,9 @@ public struct SkyScene: Sendable { | |||
| 169 | public var bodies: [PlacedBody] | 175 | public var bodies: [PlacedBody] |
| 170 | public var deepSky: [PlacedDeepSky] | 176 | public var deepSky: [PlacedDeepSky] |
| 171 | public var ngc: [PlacedDeepSky] | 177 | public var ngc: [PlacedDeepSky] |
| 178 | /// Comets and asteroids brighter than `smallBodyLimit`. | ||
| 179 | public var smallBodies: [PlacedSmallBody] | ||
| 180 | public static let smallBodyLimit = 9.0 | ||
| 172 | /// Moon's elongation east of the sun, degrees (0 new, 180 full). | 181 | /// Moon's elongation east of the sun, degrees (0 new, 180 full). |
| 173 | public var moonPhase: Double | 182 | public var moonPhase: Double |
| 174 | /// Milky Way cells brighter than `milkyWayFloor`, above −3° (the rest are dropped before projection). | 183 | /// Milky Way cells brighter than `milkyWayFloor`, above −3° (the rest are dropped before projection). |
| @@ -189,7 +198,7 @@ public struct SkyScene: Sendable { | |||
| 189 | return zip(near, placed).map { PlacedStar(star: $0, position: $1) } | 198 | return zip(near, placed).map { PlacedStar(star: $0, position: $1) } |
| 190 | } | 199 | } |
| 191 | 200 | ||
| 192 | public init(date: Date, observer: Observer, magnitudeLimit: Double = 6.5) throws { | 201 | public init(date: Date, observer: Observer, magnitudeLimit: Double = 6.5, smallBodies: [SmallBody] = []) throws { |
| 193 | self.date = date | 202 | self.date = date |
| 194 | self.observer = observer | 203 | self.observer = observer |
| 195 | let visible = Catalog.stars.filter { $0.magnitude <= magnitudeLimit } | 204 | let visible = Catalog.stars.filter { $0.magnitude <= magnitudeLimit } |
| @@ -210,6 +219,9 @@ public struct SkyScene: Sendable { | |||
| 210 | ) | 219 | ) |
| 211 | } | 220 | } |
| 212 | moonPhase = try SkyEngine.moonPhase(at: date) | 221 | moonPhase = try SkyEngine.moonPhase(at: date) |
| 222 | let bright = smallBodies.compactMap { b in (try? b.apparent(at: date)).flatMap { $0.magnitude <= Self.smallBodyLimit ? (b, $0) : nil } } | ||
| 223 | let placedSmall = SkyEngine.horizontal(j2000: bright.map { ($0.1.ra, $0.1.dec) }, at: date, from: observer) | ||
| 224 | self.smallBodies = zip(bright, placedSmall).map { PlacedSmallBody(body: $0.0, position: $1, magnitude: $0.1.magnitude) } | ||
| 213 | let cells = Catalog.milkyWay.enumerated().filter { $0.element > Self.milkyWayFloor } | 225 | let cells = Catalog.milkyWay.enumerated().filter { $0.element > Self.milkyWayFloor } |
| 214 | let centres = cells.map { (ra: 1 + 2 * Double($0.offset % 180), dec: -89 + 2 * Double($0.offset / 180)) } | 226 | let centres = cells.map { (ra: 1 + 2 * Double($0.offset % 180), dec: -89 + 2 * Double($0.offset / 180)) } |
| 215 | let placed = SkyEngine.horizontal(j2000: centres, at: date, from: observer) | 227 | let placed = SkyEngine.horizontal(j2000: centres, at: date, from: observer) |
Packages/MoonriseKit/Sources/SkyRenderer/SkyView.swift +29
| @@ -149,6 +149,7 @@ public struct SkyView: View { | |||
| 149 | drawConstellations(&context, p) | 149 | drawConstellations(&context, p) |
| 150 | drawStars(&context, p) | 150 | drawStars(&context, p) |
| 151 | if showDeepSky { drawDeepSky(&context, p) } | 151 | if showDeepSky { drawDeepSky(&context, p) } |
| 152 | drawSmallBodies(&context, p) | ||
| 152 | drawBodies(&context, p) | 153 | drawBodies(&context, p) |
| 153 | if let highlight { drawHighlight(highlight, &context, p) } | 154 | if let highlight { drawHighlight(highlight, &context, p) } |
| 154 | drawHorizon(&context, p, size: size) | 155 | drawHorizon(&context, p, size: size) |
| @@ -332,6 +333,34 @@ public struct SkyView: View { | |||
| 332 | label(&context, String(format: "%.2f°", degrees), at: CGPoint(x: c.x, y: c.y + r + 4), anchor: .top, color: style.highlight) | 333 | label(&context, String(format: "%.2f°", degrees), at: CGPoint(x: c.x, y: c.y + r + 4), anchor: .top, color: style.highlight) |
| 333 | } | 334 | } |
| 334 | 335 | ||
| 336 | /// Comets as open circles, asteroids as small diamonds, named at 90° field or closer. | ||
| 337 | func drawSmallBodies(_ context: inout GraphicsContext, _ p: Projection) { | ||
| 338 | var comets = Path(), asteroids = Path() | ||
| 339 | for b in scene.smallBodies where b.position.altitude > 0 { | ||
| 340 | guard let pt = p.point(b.position) else { continue } | ||
| 341 | let r = max(2.5, 4.5 - 0.3 * b.magnitude) | ||
| 342 | if b.body.isComet { | ||
| 343 | comets.addEllipse(in: CGRect(x: pt.x - r, y: pt.y - r, width: 2 * r, height: 2 * r)) | ||
| 344 | } else { | ||
| 345 | asteroids.move(to: CGPoint(x: pt.x, y: pt.y - r)) | ||
| 346 | asteroids.addLine(to: CGPoint(x: pt.x + r, y: pt.y)) | ||
| 347 | asteroids.addLine(to: CGPoint(x: pt.x, y: pt.y + r)) | ||
| 348 | asteroids.addLine(to: CGPoint(x: pt.x - r, y: pt.y)) | ||
| 349 | asteroids.closeSubpath() | ||
| 350 | } | ||
| 351 | if fieldOfView <= 90 { | ||
| 352 | label(&context, Self.shortName(b.body.name), at: CGPoint(x: pt.x + r + 3, y: pt.y), anchor: .leading, color: style.muted) | ||
| 353 | } | ||
| 354 | } | ||
| 355 | context.stroke(comets, with: .color(style.planet), lineWidth: 1.2) | ||
| 356 | context.fill(asteroids, with: .color(style.planet.opacity(0.8))) | ||
| 357 | } | ||
| 358 | |||
| 359 | /// "1 Ceres" for "1 Ceres (A801 AA)"; comets as given. | ||
| 360 | static func shortName(_ name: String) -> String { | ||
| 361 | name.range(of: " (").map { String(name[..<$0.lowerBound]) } ?? name | ||
| 362 | } | ||
| 363 | |||
| 335 | func drawBodies(_ context: inout GraphicsContext, _ p: Projection) { | 364 | func drawBodies(_ context: inout GraphicsContext, _ p: Projection) { |
| 336 | // Naked-eye bodies only; Neptune (about mag 7.8) is left out. | 365 | // Naked-eye bodies only; Neptune (about mag 7.8) is left out. |
| 337 | for b in scene.bodies where b.position.altitude > 0 && b.magnitude <= 6 { | 366 | for b in scene.bodies where b.position.altitude > 0 && b.magnitude <= 6 { |
Packages/MoonriseKit/Tests/SkyEngineTests/SmallBodyTests.swift added +38
| @@ -0,0 +1,38 @@ | |||
| 1 | import Foundation | ||
| 2 | import Testing | ||
| 3 | @testable import SkyEngine | ||
| 4 | |||
| 5 | private let date = Date(timeIntervalSince1970: 1_792_627_200) // 2026-10-22 00:00 UTC | ||
| 6 | |||
| 7 | private func separation(_ a: (Double, Double), _ b: (Double, Double)) -> Double { | ||
| 8 | let r = Double.pi / 180 | ||
| 9 | return acos(min(1, sin(a.1 * r) * sin(b.1 * r) + cos(a.1 * r) * cos(b.1 * r) * cos((a.0 - b.0) * r))) / r | ||
| 10 | } | ||
| 11 | |||
| 12 | @Test func ceresAgainstHorizons() throws { | ||
| 13 | // SBDB elements fetched 2026-10-22; Horizons: RA 112.46538, Dec 23.64840, V 8.400, r 2.65745, Δ 2.33374. | ||
| 14 | let ceres = SmallBody(name: "1 Ceres", q: 2.545, e: 0.0797, i: 10.59, node: 80.25, peri: 73.29, tp: 2461599.84, brightness: .asteroid(h: 3.34, g: 0.12)) | ||
| 15 | let a = try ceres.apparent(at: date) | ||
| 16 | #expect(separation((a.ra, a.dec), (112.46538, 23.64840)) < 1) | ||
| 17 | #expect(abs(a.r - 2.65745) < 0.02 && abs(a.delta - 2.33374) < 0.02) | ||
| 18 | #expect(abs(a.magnitude - 8.40) < 0.3) | ||
| 19 | } | ||
| 20 | |||
| 21 | @Test func cometAgainstHorizons() throws { | ||
| 22 | // 24P/Schaumasse; Horizons: RA 245.75004, Dec −21.65566, r 3.23966, Δ 3.94765. | ||
| 23 | let c = SmallBody(name: "24P/Schaumasse", q: 1.185, e: 0.7079, i: 11.50, node: 78.29, peri: 58.48, tp: 2461049.06, brightness: .comet(m1: 14.6, k1: 8)) | ||
| 24 | let a = try c.apparent(at: date) | ||
| 25 | #expect(separation((a.ra, a.dec), (245.75004, -21.65566)) < 1) | ||
| 26 | #expect(abs(a.r - 3.23966) < 0.03 && abs(a.delta - 3.94765) < 0.03) | ||
| 27 | } | ||
| 28 | |||
| 29 | @Test func parabolicAndHyperbolicOrbitsMeetTheEllipseAtPerihelion() { | ||
| 30 | for e in [0.99999, 1.0, 1.00001, 1.5] { | ||
| 31 | let b = SmallBody(name: "x", q: 0.5, e: e, i: 0, node: 0, peri: 0, tp: 2_461_000, brightness: .comet(m1: 5, k1: 10)) | ||
| 32 | let atPerihelion = b.position(at: Date(timeIntervalSince1970: (2_461_000 - 2_440_587.5) * 86_400)) | ||
| 33 | #expect(abs(atPerihelion.x - 0.5) < 1e-6 && abs(atPerihelion.y) < 1e-6) | ||
| 34 | let later = b.position(at: Date(timeIntervalSince1970: (2_461_100 - 2_440_587.5) * 86_400)) | ||
| 35 | let r = (later * later).sum().squareRoot() | ||
| 36 | #expect(r > 0.5 && later.y > 0, "e \(e): r \(r)") | ||
| 37 | } | ||
| 38 | } | ||
server/src/index.ts +12 −2
| @@ -6,6 +6,7 @@ import { activeEvent, fetchTrajectory, STEP_MINUTES } from "./live"; | |||
| 6 | import { fetchLaunch, fetchLaunches, PREVIOUS_URL, throttleSeconds, Throttled, UPCOMING_URL, type Launch } from "./ll2"; | 6 | import { fetchLaunch, fetchLaunches, PREVIOUS_URL, throttleSeconds, Throttled, UPCOMING_URL, type Launch } from "./ll2"; |
| 7 | import { digestPayload, dueOffsets, fetchLatest, localDate, pickHeadlines, type Article } from "./news"; | 7 | import { digestPayload, dueOffsets, fetchLatest, localDate, pickHeadlines, type Article } from "./news"; |
| 8 | import { fetchSolarWind, STORM_KP, stormLikely, type SolarWind } from "./solarwind"; | 8 | import { fetchSolarWind, STORM_KP, stormLikely, type SolarWind } from "./solarwind"; |
| 9 | import { fetchSmallBodies } from "./smallbodies"; | ||
| 9 | import { fetchCcor2, fetchCycle, fetchEnlil } from "./sun"; | 10 | import { fetchCcor2, fetchCycle, fetchEnlil } from "./sun"; |
| 10 | import { fetchSpaceWeather, next24h, type SpaceWeather } from "./swpc"; | 11 | import { fetchSpaceWeather, next24h, type SpaceWeather } from "./swpc"; |
| 11 | 12 | ||
| @@ -50,7 +51,7 @@ const json = (body: unknown, status = 200, maxAge?: number) => | |||
| 50 | const PRIVACY_URL = "https://krz.sh/privacy/moonrise/"; | 51 | const PRIVACY_URL = "https://krz.sh/privacy/moonrise/"; |
| 51 | 52 | ||
| 52 | /** Read-only endpoints whose responses are the same for everyone. */ | 53 | /** Read-only endpoints whose responses are the same for everyone. */ |
| 53 | const API = new Set(["/v1/today", "/v1/launches", "/v1/live", "/v1/satellites", "/v1/news", "/v1/sun"]); | 54 | const API = new Set(["/v1/today", "/v1/launches", "/v1/live", "/v1/satellites", "/v1/news", "/v1/sun", "/v1/smallbodies"]); |
| 54 | 55 | ||
| 55 | function api(url: URL, env: Env, now: Date): Promise<Response> { | 56 | function api(url: URL, env: Env, now: Date): Promise<Response> { |
| 56 | switch (url.pathname) { | 57 | switch (url.pathname) { |
| @@ -59,10 +60,17 @@ function api(url: URL, env: Env, now: Date): Promise<Response> { | |||
| 59 | case "/v1/live": return live(env, url, now); | 60 | case "/v1/live": return live(env, url, now); |
| 60 | case "/v1/news": return news(env); | 61 | case "/v1/news": return news(env); |
| 61 | case "/v1/sun": return sun(env); | 62 | case "/v1/sun": return sun(env); |
| 63 | case "/v1/smallbodies": return smallBodies(env); | ||
| 62 | default: return satellites(env); | 64 | default: return satellites(env); |
| 63 | } | 65 | } |
| 64 | } | 66 | } |
| 65 | 67 | ||
| 68 | /** Comets near perihelion and bright asteroids, refreshed daily. */ | ||
| 69 | async function smallBodies(env: Env): Promise<Response> { | ||
| 70 | const row = await env.DB.prepare("SELECT fetched_at, body FROM feed_snapshots WHERE feed = 'sbdb' AND ok = 1").first<{ fetched_at: string; body: string }>(); | ||
| 71 | return json({ fetchedAt: row?.fetched_at ?? null, bodies: row ? JSON.parse(row.body) : [] }, 200, MAX_AGE.smallBodies); | ||
| 72 | } | ||
| 73 | |||
| 66 | /** WSA-Enlil at Earth, CCOR-2 frames and solar cycle 25, each with the time it was fetched. */ | 74 | /** WSA-Enlil at Earth, CCOR-2 frames and solar cycle 25, each with the time it was fetched. */ |
| 67 | async function sun(env: Env): Promise<Response> { | 75 | async function sun(env: Env): Promise<Response> { |
| 68 | const rows = await env.DB.prepare("SELECT feed, fetched_at, body FROM feed_snapshots WHERE feed IN ('sun:enlil', 'sun:ccor2', 'sun:cycle') AND ok = 1") | 76 | const rows = await env.DB.prepare("SELECT feed, fetched_at, body FROM feed_snapshots WHERE feed IN ('sun:enlil', 'sun:ccor2', 'sun:cycle') AND ok = 1") |
| @@ -101,7 +109,7 @@ async function cached(request: Request, ctx: ExecutionContext | undefined, respo | |||
| 101 | } | 109 | } |
| 102 | 110 | ||
| 103 | /** How long clients may reuse each GET response, matched to how often its source is polled. */ | 111 | /** How long clients may reuse each GET response, matched to how often its source is polled. */ |
| 104 | export const MAX_AGE = { today: 60, launches: 300, satellites: 3600, live: 300, news: 600, sun: 1800 } as const; | 112 | export const MAX_AGE = { today: 60, launches: 300, satellites: 3600, live: 300, news: 600, sun: 1800, smallBodies: 3600 } as const; |
| 105 | 113 | ||
| 106 | function validDevice(d: Partial<DeviceRequest>): d is DeviceRequest { | 114 | function validDevice(d: Partial<DeviceRequest>): d is DeviceRequest { |
| 107 | return ( | 115 | return ( |
| @@ -511,6 +519,8 @@ async function pollSun(env: Env, now: Date): Promise<void> { | |||
| 511 | const jobs: [string, () => Promise<unknown>][] = [["sun:enlil", () => fetchEnlil(now)], ["sun:ccor2", () => fetchCcor2(now)]]; | 519 | const jobs: [string, () => Promise<unknown>][] = [["sun:enlil", () => fetchEnlil(now)], ["sun:ccor2", () => fetchCcor2(now)]]; |
| 512 | const cycle = await env.DB.prepare("SELECT 1 FROM feed_snapshots WHERE feed = 'sun:cycle' AND ok = 1").first(); | 520 | const cycle = await env.DB.prepare("SELECT 1 FROM feed_snapshots WHERE feed = 'sun:cycle' AND ok = 1").first(); |
| 513 | if (now.getUTCHours() === 0 || !cycle) jobs.push(["sun:cycle", () => fetchCycle()]); | 521 | if (now.getUTCHours() === 0 || !cycle) jobs.push(["sun:cycle", () => fetchCycle()]); |
| 522 | const sbdb = await env.DB.prepare("SELECT 1 FROM feed_snapshots WHERE feed = 'sbdb' AND ok = 1").first(); | ||
| 523 | if (now.getUTCHours() === 3 || !sbdb) jobs.push(["sbdb", () => fetchSmallBodies(now)]); | ||
| 514 | for (const [feed, job] of jobs) { | 524 | for (const [feed, job] of jobs) { |
| 515 | try { | 525 | try { |
| 516 | await save.bind(feed, now.toISOString(), JSON.stringify(await job())).run(); | 526 | await save.bind(feed, now.toISOString(), JSON.stringify(await job())).run(); |
server/src/smallbodies.ts added +45
| @@ -0,0 +1,45 @@ | |||
| 1 | // Comets near perihelion and bright main-belt asteroids from JPL's Small-Body Database, once a day (JPL's SSD API fair | ||
| 2 | // use: one request at a time, results cached). Output matches SkyEngine.SmallBody's Codable form. | ||
| 3 | import { USER_AGENT } from "./agent.ts"; | ||
| 4 | |||
| 5 | const API = "https://ssd-api.jpl.nasa.gov/sbdb_query.api"; | ||
| 6 | |||
| 7 | export interface SmallBody { | ||
| 8 | name: string; q: number; e: number; i: number; node: number; peri: number; tp: number; | ||
| 9 | brightness: { comet: { m1: number; k1: number } } | { asteroid: { h: number; g: number } }; | ||
| 10 | } | ||
| 11 | |||
| 12 | /** Rows of [full_name, e, q, i, om, w, tp, M1|H, K1|G]; rows without a brightness are left out. */ | ||
| 13 | export function parse(rows: (string | null)[][], kind: "comet" | "asteroid"): SmallBody[] { | ||
| 14 | const out: SmallBody[] = []; | ||
| 15 | for (const r of rows) { | ||
| 16 | const [name, e, q, i, om, w, tp, b1, b2] = r; | ||
| 17 | const n = [e, q, i, om, w, tp, b1].map((v) => Number(v)); | ||
| 18 | if (n.some((v) => !Number.isFinite(v)) || r[7] == null) continue; | ||
| 19 | const base = { name: String(name).trim(), e: n[0], q: n[1], i: n[2], node: n[3], peri: n[4], tp: n[5] }; | ||
| 20 | out.push(kind === "comet" | ||
| 21 | ? { ...base, brightness: { comet: { m1: n[6], k1: b2 == null ? 10 : Number(b2) } } } | ||
| 22 | : { ...base, brightness: { asteroid: { h: n[6], g: b2 == null ? 0.15 : Number(b2) } } }); | ||
| 23 | } | ||
| 24 | return out; | ||
| 25 | } | ||
| 26 | |||
| 27 | async function query(params: Record<string, string>): Promise<(string | null)[][]> { | ||
| 28 | const res = await fetch(`${API}?${new URLSearchParams(params)}`, { headers: { "user-agent": USER_AGENT } }); | ||
| 29 | if (!res.ok) throw new Error(`SBDB ${res.status}`); | ||
| 30 | return ((await res.json()) as { data?: (string | null)[][] }).data ?? []; | ||
| 31 | } | ||
| 32 | |||
| 33 | /** Comets with perihelion inside 3 AU within 400 days of now; numbered asteroids with H < 7 inside 6 AU. */ | ||
| 34 | export async function fetchSmallBodies(now: Date): Promise<SmallBody[]> { | ||
| 35 | const jd = Math.round(now.getTime() / 86_400_000 + 2440587.5); | ||
| 36 | const comets = await query({ | ||
| 37 | fields: "full_name,e,q,i,om,w,tp,M1,K1", "sb-kind": "c", | ||
| 38 | "sb-cdata": JSON.stringify({ AND: ["q|LT|3", `tp|RG|${jd - 400}|${jd + 400}`] }), | ||
| 39 | }); | ||
| 40 | const asteroids = await query({ | ||
| 41 | fields: "full_name,e,q,i,om,w,tp,H,G", "sb-kind": "a", "sb-ns": "n", | ||
| 42 | "sb-cdata": JSON.stringify({ AND: ["H|LT|7", "a|LT|6"] }), | ||
| 43 | }); | ||
| 44 | return [...parse(comets, "comet"), ...parse(asteroids, "asteroid")]; | ||
| 45 | } | ||
server/test/smallbodies.test.ts added +11
| @@ -0,0 +1,11 @@ | |||
| 1 | import assert from "node:assert/strict"; | ||
| 2 | import { test } from "node:test"; | ||
| 3 | import { parse } from "../src/smallbodies.ts"; | ||
| 4 | |||
| 5 | test("SBDB rows to SmallBody, without rows lacking a brightness", () => { | ||
| 6 | const comets = parse([[" 24P/Schaumasse", "0.7079", "1.185", "11.50", "78.29", "58.48", "2461049.06", "14.6", "8."], ["C/2026 X1", "1.0", "0.5", "40", "10", "20", "2461100", null, null]], "comet"); | ||
| 7 | assert.deepEqual(comets, [{ name: "24P/Schaumasse", e: 0.7079, q: 1.185, i: 11.5, node: 78.29, peri: 58.48, tp: 2461049.06, brightness: { comet: { m1: 14.6, k1: 8 } } }]); | ||
| 8 | const asteroids = parse([[" 1 Ceres (A801 AA)", "0.0797", "2.545", "10.59", "80.25", "73.29", "2461599.84", "3.34", null]], "asteroid"); | ||
| 9 | assert.deepEqual(asteroids[0].brightness, { asteroid: { h: 3.34, g: 0.15 } }); | ||
| 10 | assert.equal(asteroids[0].name, "1 Ceres (A801 AA)"); | ||
| 11 | }); | ||