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 4c72d5eff7

4c72d5eff7784439a6b28123b2bbb83d45b635da

parent: 323a647574

Unsigned

cmc <hello@cleberg.net> · 2026-10-21 09:01 UTC

System 3D: shared meshes and materials, placeholder while RealityKit starts, scene detached on leaving 3D (!79)

Switching System from Map to 3D blocked the main thread for 1.5–2.0 s on the first switch and ~240 ms on later ones, with the 2D content frozen on screen until the 3D view appeared. `SolarSystem3DView.build` generated a night-shell mesh per body (~40), a sphere mesh per entity, and a translucent material per glow shell, night shell, tail cone, orbit and path. Leaving 3D kept the whole scene alive. App report (perf/app.md) finding 1.

## Changes

- One `generateSphere(radius: 1)` mesh for the Sun, its glow shells (now scaled 1.07–1.7 instead of generated at that radius), bodies, spacecraft, comet nuclei and the flare.
- `nightShell()` returns the mesh; it is built once with one material and shared by all bodies.
- Comet tail cones and their three materials are made once and shared by all comets. Spacecraft and nucleus materials are shared.
- Orbit materials are shared by colour and opacity (three in total); spacecraft paths share one material. Created only when the orbit/path entity is first created, as before.
- `SolarSystem3DView` shows `Color.black.overlay(ProgressView().tint(ink))` (as on the Sun tab) until a task sets `ready`, then creates the `RealityView`. The task sleeps 1 ms first so the placeholder is committed before RealityKit blocks the main thread.
- `SolarSceneEntities` detaches `root` in an `isolated deinit`. After leaving 3D, RealityView keeps its last `ARView` (referenced from `_RealityViewCameraModel`), and that view kept our scene: 151 `ModelEntity`, 23 `TextureAsset` still alive in a memory graph taken after switching back to Map. With the detach: 0 `ModelEntity`, 9 `TextureAsset`.

Rendering is unchanged: same meshes, materials, scales and draw order.

## Measurements

iPhone 18 Pro simulator (iOS 27), Release build, M2 Pro. A temporary probe (not committed) logged `CADisplayLink` frame intervals over 1.5× target, `phys_footprint` every 250 ms, the `RealityView` make closure duration around `build`, and when the placeholder appeared. A UI test opens System (Map), then switches to 3D and back to Map three times, 4–6 s apart, and on the first 3D visit flies to Saturn, the Sun and Jupiter for screenshots. 3 runs per side, interleaved; one run per side also recorded the screen with `simctl io recordVideo`. Load (`uptime`, 12 cores): main 3.94 → 3.69, 3.90 → 3.86, 3.25 → 3.37; branch 3.69 → 5.70, 3.88 → 3.25, 3.37 → 3.41.

| | main | branch |
|---|---:|---:|
| First switch in the process: longest main-thread frame | 1,504–2,044 ms | 1,361–1,396 ms |
| First switch: `RealityView` make closure (`build`) | 399–452 ms | 303–319 ms |
| Later switches: longest frame | 215–252 ms | 132–182 ms |
| Later switches: make closure (`build`) | 111–115 ms | 32–38 ms |
| Touch to first changed content (screen recording) | ~1.5 s (2D view frozen, only the segmented control animates) | next frame (17 ms), progress indicator animating during RealityKit start-up |
| Footprint before first 3D → after leaving 3D the third time | 44.5 → 101.0, 49.3 → 102.2, 48.9 → 101.4 MB | 45.0 → 87.5, 49.1 → 89.8, 48.2 → 90.3 MB |
| Footprint 3 s into the first 3D visit | 76–86 MB | 65–68 MB |

**Time Profiler**, one run per side (attached after launch; main thread, Running samples, within each 3D step):

| | main | branch |
|---|---:|---:|
| `build` incl., first switch | 384 ms | 308 ms |
| of which one RealityFoundation call at the start of `build` (first use in the process) | 278 ms | 270 ms |
| of which `nightShell()` | 31 ms | 1 ms |
| `build` incl., later switches | 107, 101 ms | 28, 30 ms |
| RealityKit outside `build`, first switch | 1,081 ms | 1,178 ms |

**RealityKit's remaining share** (simulator; needs a device to judge): on the first switch, about 1.0 s of `ARView`/renderer start-up before the make closure runs, plus the ~270 ms first-use call inside `build`, out of a ~1.37 s hang; app code in `build` is ~40 ms. On later switches the hang is 132–182 ms, of which `build` is 32–38 ms. The placeholder stays on screen and animates during the hang, but touches are not handled until it ends.

**Memory after leaving 3D.** Our scene is freed (above), but the footprint stays ~40 MB above the pre-3D level. Memory graphs before 3D and after leaving it show the live heap at 28 → 57 MB; the growth is RealityKit allocations (material definitions, shader function constants, Metal library data, per-frame allocator) and the retained `ARView`. It does not grow with repeated switches. App code has no handle on these.

**Appearance.** Screenshots of the overview and of Saturn, the Sun and Jupiter after the fly-to compared with SSIM (status bar cropped): main vs branch falls in the same range as run-to-run on one side (overview 0.99963–0.999999, Sun 0.99979–0.99998, Saturn and Jupiter 0.990–0.998, where moons and the camera flight differ between runs). Glow, night side, Saturn's rings and tails look the same side by side.

## Tests

- `swift test` (Packages/MoonriseKit): 195 tests passed.
- `npm test` (server): 55 passed.
- `xcodebuild test` (Moonrise, iPhone 18 Pro simulator): passed. Accessibility audit 64 issues on both main and branch: Sky 4, Settings 2, System 7, Sun 3, News & launches 21, Library 14, Library page: Saturn 13. The audit visits System in Map mode, so the 3D view and its placeholder are not audited.
- MoonriseVision does not compile `SolarSystem3D.swift`; `xcodebuild build -scheme MoonriseVision -destination 'generic/platform=visionOS Simulator'` succeeded. No visionOS simulator runtime is installed, so it was not run.

## Not verified

- A device. The RealityKit start-up and first-use costs are simulator numbers.
- Whether `ARView` is also kept outside UI tests: the memory graphs were taken under XCUITest, where the accessibility element cache also references it.
- Switching tabs away from System and back keeps the 3D scene, as before; only leaving 3D releases it.

Layout: unified · split

App/Sources/SolarSystem3D.swift +68 −34
@@ -186,6 +186,10 @@ final class SolarSceneEntities {
186 var debrisBuilt: (SolarScale, Float, String)? 186 var debrisBuilt: (SolarScale, Float, String)?
187 let flare = ModelEntity() 187 let flare = ModelEntity()
188 let aurora = Entity() 188 let aurora = Entity()
189
190 /// RealityView's ARView can outlive the 3D view; detach the scene so its meshes, materials and
191 /// textures are freed when 3D is left.
192 isolated deinit { root.removeFromParent() }
189} 193}
190 194
191struct SolarSystem3DView: View { 195struct SolarSystem3DView: View {
@@ -205,6 +209,7 @@ struct SolarSystem3DView: View {
205 @State private var flight: Task<Void, Never>? 209 @State private var flight: Task<Void, Never>?
206 @State private var pulse = false 210 @State private var pulse = false
207 @State private var viewSize = CGSize(width: 400, height: 600) 211 @State private var viewSize = CGSize(width: 400, height: 600)
212 @State private var ready = false
208 @AppStorage("solar.moons") private var showMoons = true 213 @AppStorage("solar.moons") private var showMoons = true
209 @AppStorage("solar.dwarfs") private var showDwarfs = true 214 @AppStorage("solar.dwarfs") private var showDwarfs = true
210 @AppStorage("solar.craft") private var showCraft = true 215 @AppStorage("solar.craft") private var showCraft = true
@@ -224,16 +229,20 @@ struct SolarSystem3DView: View {
224 var body: some View { 229 var body: some View {
225 GeometryReader { geo in 230 GeometryReader { geo in
226 ZStack { 231 ZStack {
227 RealityView { content in 232 if ready {
228 content.camera = .virtual 233 RealityView { content in
229 build(content) 234 content.camera = .virtual
230 } update: { _ in 235 build(content)
231 place() 236 } update: { _ in
232 } 237 place()
233 .gesture(dragGesture.simultaneously(with: pinchGesture)) 238 }
234 .onTapGesture(coordinateSpace: .local) { tap($0, size: geo.size) } 239 .gesture(dragGesture.simultaneously(with: pinchGesture))
240 .onTapGesture(coordinateSpace: .local) { tap($0, size: geo.size) }
235 241
236 labels(size: geo.size).allowsHitTesting(false) 242 labels(size: geo.size).allowsHitTesting(false)
243 } else {
244 Color.black.overlay(ProgressView().tint(ink))
245 }
237 246
238 VStack(spacing: 8) { 247 VStack(spacing: 8) {
239 if let s = selected { card(s) } 248 if let s = selected { card(s) }
@@ -256,6 +265,11 @@ struct SolarSystem3DView: View {
256 .accessibilityElement(children: .contain) 265 .accessibilityElement(children: .contain)
257 .accessibilityLabel("3D solar system. Drag to turn, pinch to zoom, tap a body to learn about it.") 266 .accessibilityLabel("3D solar system. Drag to turn, pinch to zoom, tap a body to learn about it.")
258 .onChange(of: scale) { resetView() } 267 .onChange(of: scale) { resetView() }
268 .task {
269 // RealityKit's start-up blocks the main thread; let the placeholder reach the screen first.
270 try? await Task.sleep(for: .milliseconds(1))
271 ready = true
272 }
259 .task { await loadWeather() } 273 .task { await loadWeather() }
260 .task { 274 .task {
261 while !Task.isCancelled { 275 while !Task.isCancelled {
@@ -369,8 +383,10 @@ struct SolarSystem3DView: View {
369 e.camera.camera.fieldOfViewInDegrees = SolarCamera.fovDegrees 383 e.camera.camera.fieldOfViewInDegrees = SolarCamera.fovDegrees
370 e.root.addChild(e.camera) 384 e.root.addChild(e.camera)
371 385
386 // One unit sphere for every round body; entities are scaled to size.
387 let sphere = MeshResource.generateSphere(radius: 1)
372 let sunMaterial = UnlitMaterial(color: UIColor(red: 1, green: 0.86, blue: 0.5, alpha: 1)) 388 let sunMaterial = UnlitMaterial(color: UIColor(red: 1, green: 0.86, blue: 0.5, alpha: 1))
373 e.sun.model = ModelComponent(mesh: .generateSphere(radius: 1), materials: [sunMaterial]) 389 e.sun.model = ModelComponent(mesh: sphere, materials: [sunMaterial])
374 e.root.addChild(e.sun) 390 e.root.addChild(e.sun)
375 // Glow: nested translucent shells, fainter outward. 391 // Glow: nested translucent shells, fainter outward.
376 for i in 1...10 { 392 for i in 1...10 {
@@ -378,7 +394,9 @@ struct SolarSystem3DView: View {
378 let a = CGFloat(0.09 * pow(0.78, Double(i - 1))) 394 let a = CGFloat(0.09 * pow(0.78, Double(i - 1)))
379 var g = UnlitMaterial(color: UIColor(red: 1, green: 0.72, blue: 0.32, alpha: a)) 395 var g = UnlitMaterial(color: UIColor(red: 1, green: 0.72, blue: 0.32, alpha: a))
380 g.blending = .transparent(opacity: .init(floatLiteral: Float(a))) 396 g.blending = .transparent(opacity: .init(floatLiteral: Float(a)))
381 e.sun.addChild(ModelEntity(mesh: .generateSphere(radius: r), materials: [g])) 397 let shell = ModelEntity(mesh: sphere, materials: [g])
398 shell.scale = .init(repeating: r)
399 e.sun.addChild(shell)
382 } 400 }
383 401
384 // Planets, dwarf planets and moons: textured where there is a map, with a night side. 402 // Planets, dwarf planets and moons: textured where there is a map, with a night side.
@@ -386,36 +404,45 @@ struct SolarSystem3DView: View {
386 if let pluto = SolarPlanet.pluto { spheres.append(("pluto", pluto.color, pluto.tiltDeg)) } 404 if let pluto = SolarPlanet.pluto { spheres.append(("pluto", pluto.color, pluto.tiltDeg)) }
387 spheres += KeplerOrbit.dwarfPlanets.map { ($0.id, Library.page(id: $0.id)?.drawing?.color ?? "#999999", 0) } 405 spheres += KeplerOrbit.dwarfPlanets.map { ($0.id, Library.page(id: $0.id)?.drawing?.color ?? "#999999", 0) }
388 spheres += SolarMoon.all.map { ($0.id, $0.color, 0) } 406 spheres += SolarMoon.all.map { ($0.id, $0.color, 0) }
407 let nightMesh = Self.nightShell()
408 var nightMaterial = UnlitMaterial(color: .black)
409 nightMaterial.blending = .transparent(opacity: .init(floatLiteral: 0.88))
410 nightMaterial.faceCulling = .none
389 for s in spheres { 411 for s in spheres {
390 let body = ModelEntity() 412 let body = ModelEntity()
391 // Plain colour first; the map, if there is one, is swapped in once it has loaded. 413 // Plain colour first; the map, if there is one, is swapped in once it has loaded.
392 let m = UnlitMaterial(color: UIColor(Color(hex: s.color) ?? .gray)) 414 let m = UnlitMaterial(color: UIColor(Color(hex: s.color) ?? .gray))
393 body.model = ModelComponent(mesh: .generateSphere(radius: 1), materials: [m]) 415 body.model = ModelComponent(mesh: sphere, materials: [m])
394 body.orientation = simd_quatf(angle: Float(s.tilt * .pi / 180), axis: [1, 0, 0]) 416 body.orientation = simd_quatf(angle: Float(s.tilt * .pi / 180), axis: [1, 0, 0])
395 if s.id == "saturn" { body.addChild(Self.annulus(inner: 1.24, outer: 2.27, color: UIColor(red: 0.85, green: 0.78, blue: 0.62, alpha: 0.7))) } 417 if s.id == "saturn" { body.addChild(Self.annulus(inner: 1.24, outer: 2.27, color: UIColor(red: 0.85, green: 0.78, blue: 0.62, alpha: 0.7))) }
396 e.bodies[s.id] = body 418 e.bodies[s.id] = body
397 e.root.addChild(body) 419 e.root.addChild(body)
398 let night = Self.nightShell() 420 let night = ModelEntity(mesh: nightMesh, materials: [nightMaterial])
399 e.nights[s.id] = night 421 e.nights[s.id] = night
400 e.root.addChild(night) 422 e.root.addChild(night)
401 } 423 }
402 424
403 // Spacecraft and comet nuclei: dots sized each frame to stay visible. 425 // Spacecraft and comet nuclei: dots sized each frame to stay visible.
426 let craftMaterial = UnlitMaterial(color: Self.craftColor)
404 for craft in Spacecraft.all { 427 for craft in Spacecraft.all {
405 let dot = ModelEntity(mesh: .generateSphere(radius: 1), materials: [UnlitMaterial(color: Self.craftColor)]) 428 let dot = ModelEntity(mesh: sphere, materials: [craftMaterial])
406 e.bodies["craft:\(craft.name)"] = dot 429 e.bodies["craft:\(craft.name)"] = dot
407 e.root.addChild(dot) 430 e.root.addChild(dot)
408 } 431 }
432 let nucleusMaterial = UnlitMaterial(color: UIColor(white: 0.92, alpha: 1))
433 // A soft tail: nested cones, wider and fainter outward.
434 let tailParts = ([(0.025, 0.3), (0.06, 0.14), (0.11, 0.06)] as [(Float, Float)]).map { radius, alpha in
435 var t = UnlitMaterial(color: UIColor(red: 0.7, green: 0.88, blue: 1, alpha: 1))
436 t.blending = .transparent(opacity: .init(floatLiteral: alpha))
437 return (mesh: MeshResource.generateCone(height: 1, radius: radius), material: t)
438 }
409 for c in KeplerOrbit.comets { 439 for c in KeplerOrbit.comets {
410 let nucleus = ModelEntity(mesh: .generateSphere(radius: 1), materials: [UnlitMaterial(color: UIColor(white: 0.92, alpha: 1))]) 440 let nucleus = ModelEntity(mesh: sphere, materials: [nucleusMaterial])
411 e.bodies["comet:\(c.id)"] = nucleus 441 e.bodies["comet:\(c.id)"] = nucleus
412 e.root.addChild(nucleus) 442 e.root.addChild(nucleus)
413 // A soft tail: nested cones, wider and fainter outward.
414 let tail = ModelEntity() 443 let tail = ModelEntity()
415 for (radius, alpha) in [(0.025, 0.3), (0.06, 0.14), (0.11, 0.06)] as [(Float, Float)] { 444 for part in tailParts {
416 var t = UnlitMaterial(color: UIColor(red: 0.7, green: 0.88, blue: 1, alpha: 1)) 445 tail.addChild(ModelEntity(mesh: part.mesh, materials: [part.material]))
417 t.blending = .transparent(opacity: .init(floatLiteral: alpha))
418 tail.addChild(ModelEntity(mesh: .generateCone(height: 1, radius: radius), materials: [t]))
419 } 446 }
420 e.tails[c.id] = tail 447 e.tails[c.id] = tail
421 e.root.addChild(tail) 448 e.root.addChild(tail)
@@ -429,7 +456,7 @@ struct SolarSystem3DView: View {
429 456
430 var flareMaterial = UnlitMaterial(color: UIColor(red: 1, green: 1, blue: 0.85, alpha: 0.9)) 457 var flareMaterial = UnlitMaterial(color: UIColor(red: 1, green: 1, blue: 0.85, alpha: 0.9))
431 flareMaterial.blending = .transparent(opacity: .init(floatLiteral: 0.9)) 458 flareMaterial.blending = .transparent(opacity: .init(floatLiteral: 0.9))
432 e.flare.model = ModelComponent(mesh: .generateSphere(radius: 1), materials: [flareMaterial]) 459 e.flare.model = ModelComponent(mesh: sphere, materials: [flareMaterial])
433 e.root.addChild(e.flare) 460 e.root.addChild(e.flare)
434 for y: Float in [0.86, -0.86] { 461 for y: Float in [0.86, -0.86] {
435 for (inner, outer, alpha) in [(0.36, 0.66, 0.22), (0.45, 0.56, 0.5)] as [(Float, Float, CGFloat)] { 462 for (inner, outer, alpha) in [(0.36, 0.66, 0.22), (0.45, 0.56, 0.5)] as [(Float, Float, CGFloat)] {
@@ -535,13 +562,19 @@ struct SolarSystem3DView: View {
535 if let (s, w) = e.orbitsBuilt, s == scale, w / width < 1.6, width / w < 1.6 { return } 562 if let (s, w) = e.orbitsBuilt, s == scale, w / width < 1.6, width / w < 1.6 { return }
536 e.orbitsBuilt = (scale, width) 563 e.orbitsBuilt = (scale, width)
537 let map = mapping 564 let map = mapping
565 // Orbits of the same colour and opacity share a material, made when the first of them is created.
566 var materials: [String: UnlitMaterial] = [:]
538 func set(_ id: String, _ points: [SIMD3<Float>], color: UIColor, opacity: Float) { 567 func set(_ id: String, _ points: [SIMD3<Float>], color: UIColor, opacity: Float) {
539 let mesh = Self.ribbon(points, width: width, closed: true) 568 let mesh = Self.ribbon(points, width: width, closed: true)
540 if let existing = e.orbits[id] { existing.model?.mesh = mesh; return } 569 if let existing = e.orbits[id] { existing.model?.mesh = mesh; return }
541 var m = UnlitMaterial(color: color) 570 let key = "\(color) \(opacity)"
542 m.blending = .transparent(opacity: .init(floatLiteral: opacity)) 571 if materials[key] == nil {
543 m.faceCulling = .none 572 var m = UnlitMaterial(color: color)
544 let orbit = ModelEntity(mesh: mesh, materials: [m]) 573 m.blending = .transparent(opacity: .init(floatLiteral: opacity))
574 m.faceCulling = .none
575 materials[key] = m
576 }
577 let orbit = ModelEntity(mesh: mesh, materials: [materials[key]!])
545 e.orbits[id] = orbit 578 e.orbits[id] = orbit
546 e.root.addChild(orbit) 579 e.root.addChild(orbit)
547 } 580 }
@@ -567,6 +600,7 @@ struct SolarSystem3DView: View {
567 e.pathsBuilt = (scale, width, bucket) 600 e.pathsBuilt = (scale, width, bucket)
568 let map = mapping 601 let map = mapping
569 let day = date.timeIntervalSince1970 / 86_400 602 let day = date.timeIntervalSince1970 / 86_400
603 var material: UnlitMaterial?
570 for craft in Spacecraft.all { 604 for craft in Spacecraft.all {
571 var pts = craft.points.filter { $0[0] <= day }.map { map.point(SIMD3($0[1], $0[2], $0[3])) } 605 var pts = craft.points.filter { $0[0] <= day }.map { map.point(SIMD3($0[1], $0[2], $0[3])) }
572 if let now = craft.position3(at: date) { pts.append(map.point(now)) } 606 if let now = craft.position3(at: date) { pts.append(map.point(now)) }
@@ -574,10 +608,13 @@ struct SolarSystem3DView: View {
574 if let existing = e.paths[craft.name] { 608 if let existing = e.paths[craft.name] {
575 existing.model?.mesh = mesh 609 existing.model?.mesh = mesh
576 } else { 610 } else {
577 var m = UnlitMaterial(color: Self.craftColor) 611 if material == nil {
578 m.blending = .transparent(opacity: .init(floatLiteral: 0.4)) 612 var m = UnlitMaterial(color: Self.craftColor)
579 m.faceCulling = .none 613 m.blending = .transparent(opacity: .init(floatLiteral: 0.4))
580 let path = ModelEntity(mesh: mesh, materials: [m]) 614 m.faceCulling = .none
615 material = m
616 }
617 let path = ModelEntity(mesh: mesh, materials: [material!])
581 e.paths[craft.name] = path 618 e.paths[craft.name] = path
582 e.root.addChild(path) 619 e.root.addChild(path)
583 } 620 }
@@ -666,7 +703,7 @@ struct SolarSystem3DView: View {
666 } 703 }
667 704
668 /// The half of a unit sphere below y = 0, drawn dark and mostly opaque over a body's night side. 705 /// The half of a unit sphere below y = 0, drawn dark and mostly opaque over a body's night side.
669 private static func nightShell() -> ModelEntity { 706 private static func nightShell() -> MeshResource {
670 let rings = 24, segments = 64 707 let rings = 24, segments = 64
671 var positions: [SIMD3<Float>] = [] 708 var positions: [SIMD3<Float>] = []
672 var indices: [UInt32] = [] 709 var indices: [UInt32] = []
@@ -686,10 +723,7 @@ struct SolarSystem3DView: View {
686 var d = MeshDescriptor(name: "night") 723 var d = MeshDescriptor(name: "night")
687 d.positions = MeshBuffer(positions) 724 d.positions = MeshBuffer(positions)
688 d.primitives = .triangles(indices) 725 d.primitives = .triangles(indices)
689 var m = UnlitMaterial(color: .black) 726 return (try? MeshResource.generate(from: [d])) ?? .generateBox(size: 0.001)
690 m.blending = .transparent(opacity: .init(floatLiteral: 0.88))
691 m.faceCulling = .none
692 return ModelEntity(mesh: (try? MeshResource.generate(from: [d])) ?? .generateBox(size: 0.001), materials: [m])
693 } 727 }
694 728
695 // MARK: Labels, taps and the card 729 // MARK: Labels, taps and the card