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 2863037e46

2863037e46da37ad387dac4e0ecb29ada3ebcc7f

parent: 93912993b4

Unsigned

cmc <hello@cleberg.net> · 2026-10-21 04:30 UTC

Sky labels: skip off-canvas labels, reuse resolved text (!74)

With the Chinese sky culture (306 figures) at fov ~45 the sky Canvas took 7.8 ms per draw while panning, mostly laying out a `Text` for each of ~145 figure labels, about 44 of them on screen. Messier labels had the same pattern.

## Change
- `SkyView.label` gets its resolved text from `LabelCache` and draws only when the label's measured frame meets the canvas (`clipBoundingRect`). The cache keys on text and colour and is emptied when dynamic type size, legibility weight or display scale change.
- `drawCulture` draws figure names through `label` and returns the names drawn.
- Messier, Moon, planet and compass labels use the same path.
- New test `cultureLabelsDrawnAreTheOnScreenOnes`: for the Chinese culture at fov 45 in three directions, the names drawn equal the names whose label frame meets the canvas, computed independently, and some labelled figures are off screen.

Rendering is unchanged: 37 `ImageRenderer` images (Chinese, Boorong and western at 5 views each, cold and warm cache, plus a sequence of Bold Text, scale 2, night style and back) are byte-identical to main.

## Measurements
Same method before and after.

**Package benchmark** (M2 Pro, release, 393×852 pt @3x, medians, two runs each, load 2.9–4.4):

| Case | main | branch |
|---|---:|---:|
| Chinese, fov 45, one renderer panned 0.25°/frame | 7.56–7.74 ms (closure 4.91–5.03) | 3.11–3.27 ms (closure 0.92–0.98) |
| Chinese, fov 45, render + read pixels | 7.62–8.22 ms | 3.00–3.12 ms |
| Chinese, fov 60, render + read pixels | 7.76–8.02 ms | 3.26–3.34 ms |
| Western, fov 50, one renderer panned | 3.53–3.56 ms (closure 1.34) | 2.74 ms (closure 0.56) |
| Western, fov 60, Messier on, render + read pixels | 3.55–3.66 ms | 2.72–2.76 ms |
| Western, fov 100, render + read pixels | 2.98–3.08 ms | 2.88–2.98 ms |
| Allocations, Chinese fov 45 | 12,150 | 2,100 |

**iPhone 18 Pro simulator** (Release build with a temporary draw/frame probe, XCUITest pans, two runs each, 1-min load 3.8–6.2):

| Pan, 5.3 s | main | branch |
|---|---:|---:|
| Chinese fov ~45: Canvas draw median (max) | 7.85 / 7.81 ms (11.2 / 11.4) | 1.56 / 1.53 ms (2.3 / 2.3) |
| Chinese fov ~45: frames over 25 ms | 22 / 15 | 2 / 2 |
| Chinese fov ~45: ms lost to long frames, longest frame | 1,244 / 1,131 ms, 661 / 407 ms | 65 / 34 ms, 47 / 34 ms |
| Western fov ~45: Canvas draw median | 2.45 / 2.37 ms | 1.10 / 1.05 ms |
| Western fov ~45: frames over 25 ms | 1 / 1 | 1 / 1 |

The test driver delivers about 28 drag updates a second in every run, so the draw rate itself does not show 60 fps; the drop in long frames does.

## Tests
- `swift test`: all pass (192)
- `npm test`: 40 pass
- UI accessibility audit: 64 issues before and 64 after, the same issues (Sky 4, Settings 2, System 7, Sun 3, News & launches 21, Library 14, Saturn 13)

Not verified: a device; Dynamic Type invalidation (it has no effect on macOS, where the pixel checks ran).

Layout: unified · split

Packages/MoonriseKit/Sources/SkyRenderer/SkyView.swift +49 −5
@@ -163,9 +163,11 @@ public struct SkyView: View {
163163 }
164164
165165 /// A culture's figures, named at the middle of their visible stars once zoomed in
166 /// (closer for cultures with many small figures).
167 func drawCulture(_ culture: SkyCulture, _ context: inout GraphicsContext, _ p: Projection) {
166 /// (closer for cultures with many small figures). Returns the names drawn.
167 @discardableResult
168 func drawCulture(_ culture: SkyCulture, _ context: inout GraphicsContext, _ p: Projection) -> [String] {
168169 var path = Path()
170 var labelled: [String] = []
169171 let labelBelow = culture.constellations.count > 60 ? 60.0 : 110.0
170172 for figure in culture.constellations {
171173 var points: [CGPoint] = []
@@ -181,10 +183,11 @@ public struct SkyView: View {
181183 }
182184 if fieldOfView <= labelBelow, points.count > 1 {
183185 let c = CGPoint(x: points.map(\.x).reduce(0, +) / Double(points.count), y: points.map(\.y).reduce(0, +) / Double(points.count))
184 context.draw(Text(figure.name).font(.caption2).foregroundStyle(style.muted), at: c)
186 if label(&context, figure.name, at: c, anchor: .center, color: style.muted) { labelled.append(figure.name) }
185187 }
186188 }
187189 context.stroke(path, with: .color(style.line), lineWidth: 0.6)
190 return labelled
188191 }
189192
190193 /// A constellation's IAU lines drawn bright and thick; a star or body ringed.
@@ -333,9 +336,50 @@ public struct SkyView: View {
333336 }
334337 }
335338
336 func label(_ context: inout GraphicsContext, _ text: String, at point: CGPoint, anchor: UnitPoint, color: Color? = nil) {
337 let t = Text(text).font(.caption2).foregroundStyle(color ?? style.label)
339 /// Draws a label unless it falls wholly outside the canvas; returns whether it was drawn.
340 @discardableResult
341 func label(_ context: inout GraphicsContext, _ text: String, at point: CGPoint, anchor: UnitPoint, color: Color? = nil) -> Bool {
342 let t = LabelCache.shared.resolve(text, color: color ?? style.label, in: context)
343 let size = t.measure(in: CGSize(width: CGFloat.infinity, height: .infinity))
344 let frame = CGRect(x: point.x - anchor.x * size.width, y: point.y - anchor.y * size.height, width: size.width, height: size.height)
345 guard frame.intersects(context.clipBoundingRect) else { return false }
338346 context.draw(t, at: point, anchor: anchor)
347 return true
348 }
349}
350
351/// Labels resolved once and drawn again on later frames; laying out a `Text` is most of the cost of drawing it.
352/// Resolved text depends on the environment, so the cache is emptied when the parts that change at run time do.
353@MainActor
354final class LabelCache {
355 static let shared = LabelCache()
356
357 private struct Key: Hashable {
358 var text: String
359 var color: Color
360 }
361
362 private struct TextEnvironment: Equatable {
363 var dynamicTypeSize: DynamicTypeSize
364 var legibilityWeight: LegibilityWeight?
365 var displayScale: CGFloat
366 }
367
368 private var texts: [Key: GraphicsContext.ResolvedText] = [:]
369 private var environment: TextEnvironment?
370
371 func resolve(_ text: String, color: Color, in context: GraphicsContext) -> GraphicsContext.ResolvedText {
372 let e = context.environment
373 let current = TextEnvironment(dynamicTypeSize: e.dynamicTypeSize, legibilityWeight: e.legibilityWeight, displayScale: e.displayScale)
374 if current != environment {
375 texts = [:]
376 environment = current
377 }
378 let key = Key(text: text, color: color)
379 if let t = texts[key] { return t }
380 let t = context.resolve(Text(text).font(.caption2).foregroundStyle(color))
381 texts[key] = t
382 return t
339383 }
340384}
341385
Packages/MoonriseKit/Tests/SkyRendererTests/SkyRenderTests.swift +35
@@ -89,3 +89,38 @@ let evening = Date(timeIntervalSince1970: 1_792_202_400) // 2026-10-17T02:00:00Z
8989 // The Norse Wolf's Mouth is the Hyades and includes Aldebaran (HR 1457).
9090 #expect(cultures.first { $0.id == "norse" }?.constellations.contains { $0.name == "Wolf's Mouth" && $0.lines.joined().contains(1457) } == true)
9191}
92
93/// Figure labels are drawn exactly when some of the label falls on the canvas.
94@MainActor
95@Test func cultureLabelsDrawnAreTheOnScreenOnes() throws {
96 let scene = try SkyScene(date: evening, observer: chicago)
97 let culture = try #require(Catalog.skyCultures.first { $0.id == "chinese" })
98 for (az, alt) in [(180.0, 45.0), (90, 30), (300, 70)] {
99 let view = SkyView(scene: scene, centerAzimuth: az, centerAltitude: alt, fieldOfView: 45, culture: culture)
100 var drawn: [String] = [], onScreen: [String] = [], labelled = 0
101 let canvas = Canvas { context, size in
102 let p = Projection(centerAzimuth: az, centerAltitude: alt, fieldOfView: 45, size: size)
103 drawn = view.drawCulture(culture, &context, p)
104 for figure in culture.constellations {
105 var points: [CGPoint] = []
106 for line in figure.lines {
107 for (a, b) in zip(line, line.dropFirst()) {
108 guard let ha = scene.starsByHR[a], let hb = scene.starsByHR[b], ha.altitude > -5 || hb.altitude > -5,
109 let pa = p.point(ha), let pb = p.point(hb) else { continue }
110 points += [pa, pb]
111 }
112 }
113 guard points.count > 1 else { continue }
114 labelled += 1
115 let c = CGPoint(x: points.map(\.x).reduce(0, +) / Double(points.count), y: points.map(\.y).reduce(0, +) / Double(points.count))
116 let s = context.resolve(Text(figure.name).font(.caption2)).measure(in: CGSize(width: CGFloat.infinity, height: .infinity))
117 if CGRect(x: c.x - s.width / 2, y: c.y - s.height / 2, width: s.width, height: s.height).intersects(CGRect(origin: .zero, size: size)) {
118 onScreen.append(figure.name)
119 }
120 }
121 }
122 _ = ImageRenderer(content: canvas.frame(width: 393, height: 852)).cgImage
123 #expect(!drawn.isEmpty && drawn.count < labelled, "az \(az)")
124 #expect(drawn.sorted() == onScreen.sorted(), "az \(az)")
125 }
126}