SPB Git

Repository Public License

LunarStarfield.swift 7.9 KB 173 lines swift

1import SwiftUI23/// An optional, very light animated backdrop: a sparse field of slowly twinkling stars and a few faint orbital arcs.4///5/// Cost control, because a full-screen animated `Canvas` is expensive:6/// - it redraws at 12 frames per second, not at display rate;7/// - it renders at half resolution and is scaled up (stars are soft dots, the loss is invisible);8/// - it pauses when the view is off screen and when the window or scene is inactive9///   (`controlActiveState` on the Mac, `scenePhase` elsewhere);10/// - under Reduce Motion (and in snapshot renders) it draws one static frame and never schedules another.11public struct LunarStarfield: View {12    @Environment(\.lunarTheme) private var theme13    @Environment(\.lunarRenderMode) private var renderMode14    @Environment(\.accessibilityReduceMotion) private var reduceMotion15    #if os(macOS)16    @Environment(\.controlActiveState) private var controlActiveState17    #else18    @Environment(\.scenePhase) private var scenePhase19    #endif20    @State private var isVisible = false21    private let density: Double22    private let showsOrbits: Bool23    private let isAnimated: Bool2425    /// - Parameters:26    ///   - density: stars per 10 000 square points (default 1.1: about 140 stars in a 1440 × 900 window).27    ///   - showsOrbits: draws three faint concentric orbital arcs from the lower trailing corner.28    ///   - isAnimated: pass `false` to keep the field static regardless of system settings.29    public init(density: Double = 1.1, showsOrbits: Bool = true, isAnimated: Bool = true) {30        self.density = density31        self.showsOrbits = showsOrbits32        self.isAnimated = isAnimated33    }3435    private var isSceneActive: Bool {36        #if os(macOS)37        controlActiveState != .inactive38        #else39        scenePhase == .active40        #endif41    }4243    private var isStatic: Bool { !isAnimated || reduceMotion || renderMode == .snapshot }4445    public var body: some View {46        GeometryReader { proxy in47            if isStatic {48                canvas(size: proxy.size, time: 0, resolution: 1)49            } else {50                TimelineView(.animation(minimumInterval: 1.0 / 12.0, paused: !(isVisible && isSceneActive))) { timeline in51                    canvas(size: proxy.size, time: timeline.date.timeIntervalSinceReferenceDate, resolution: 0.5)52                }53            }54        }55        .onAppear { isVisible = true }56        .onDisappear { isVisible = false }57        .allowsHitTesting(false)58        .accessibilityHidden(true)59    }6061    private func canvas(size: CGSize, time: Double, resolution: CGFloat) -> some View {62        let star = theme.star63        let rings = theme.orbitRings64        let count = Int((size.width * size.height / 10_000 * density).rounded())65        let showsOrbits = showsOrbits66        return Canvas(opaque: false, rendersAsynchronously: resolution < 1) { context, canvasSize in67            context.scaleBy(x: resolution, y: resolution)68            let full = CGSize(width: canvasSize.width / resolution, height: canvasSize.height / resolution)69            LunarStarfieldRenderer.draw(in: &context, size: full, time: time, starCount: count, star: star,70                                        rings: showsOrbits ? rings : [])71        }72        .frame(width: size.width * resolution, height: size.height * resolution)73        .scaleEffect(1 / resolution, anchor: .topLeading)74        .frame(width: size.width, height: size.height, alignment: .topLeading)75    }76}7778enum LunarStarfieldRenderer {79    /// SplitMix64: a tiny deterministic generator so the sky is the same on every launch and in every render.80    struct Generator {81        var state: UInt6482        mutating func next() -> Double {83            state &+= 0x9E37_79B9_7F4A_7C1584            var z = state85            z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B986            z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB87            z ^= z >> 3188            return Double(z >> 11) / Double(1 << 53)89        }90    }9192    static func draw(in context: inout GraphicsContext, size: CGSize, time: Double, starCount: Int, star: LunarRGBA,93                     rings: [LunarRGBA]) {94        // Orbital arcs: large concentric circles centred beyond the lower trailing corner.95        let center = CGPoint(x: size.width * 0.86, y: size.height * 1.18)96        let base = max(size.width, size.height)97        for (index, ring) in rings.enumerated() {98            let radius = base * (0.42 + 0.17 * CGFloat(index))99            let rect = CGRect(x: center.x - radius, y: center.y - radius, width: radius * 2, height: radius * 2)100            context.stroke(Path(ellipseIn: rect), with: .color(ring.withAlpha(ring.alpha * 0.42).color),101                           lineWidth: LunarStroke.ring)102            // One satellite per ring, moving a few degrees per minute.103            let angle = -2.1 + 0.42 * Double(index) + time * 0.004 * (index.isMultiple(of: 2) ? 1 : -0.7)104            let point = CGPoint(x: center.x + radius * cos(angle), y: center.y + radius * sin(angle))105            let dot = CGRect(x: point.x - 2.2, y: point.y - 2.2, width: 4.4, height: 4.4)106            context.fill(Path(ellipseIn: dot), with: .color(ring.withAlpha(min(1, ring.alpha * 1.9)).color))107        }108109        var generator = Generator(state: 0x4F52_4958)110        for _ in 0..<max(0, starCount) {111            let x = generator.next() * size.width, y = generator.next() * size.height112            let magnitude = generator.next()113            let phase = generator.next() * 2 * .pi, speed = 0.25 + generator.next() * 0.6114            let radius = 0.45 + magnitude * magnitude * 1.15115            let twinkle = 0.62 + 0.38 * sin(time * speed + phase)116            let alpha = star.alpha * (0.25 + 0.75 * magnitude) * twinkle117            let rect = CGRect(x: x - radius, y: y - radius, width: radius * 2, height: radius * 2)118            context.fill(Path(ellipseIn: rect), with: .color(star.withAlpha(alpha).color))119        }120    }121}122123/// Thin concentric orbital rings around a centre: the skeleton of the Orbit view and of decorative headers.124public struct LunarOrbitRings: View {125    @Environment(\.lunarTheme) private var theme126    private let count: Int127    private let squash: CGFloat128    private let tilt: Angle129130    /// - Parameters:131    ///   - count: number of rings; the outermost touches the view's bounds.132    ///   - squash: height / width of each ring (`1` = circles, lower = seen at an angle).133    public init(count: Int = 3, squash: CGFloat = 1, tilt: Angle = .zero) {134        self.count = max(1, count)135        self.squash = squash136        self.tilt = tilt137    }138139    /// Radius fraction (of the outermost ring) of ring `index`, innermost first. Feature views use it to place140    /// satellites exactly on the rings.141    public static func radiusFraction(ring index: Int, of count: Int) -> CGFloat {142        let count = max(1, count)143        return 0.34 + 0.66 * CGFloat(index + 1) / CGFloat(count)144    }145146    public var body: some View {147        Canvas { context, size in148            let outer = min(size.width, size.height / max(0.01, squash)) / 2 - 1149            let center = CGPoint(x: size.width / 2, y: size.height / 2)150            context.translateBy(x: center.x, y: center.y)151            context.rotate(by: tilt)152            for index in 0..<count {153                let radius = outer * Self.radiusFraction(ring: index, of: count)154                let rect = CGRect(x: -radius, y: -radius * squash, width: radius * 2, height: radius * 2 * squash)155                let color = theme.orbitRings[min(index, theme.orbitRings.count - 1)]156                context.stroke(Path(ellipseIn: rect), with: .color(color.color), lineWidth: LunarStroke.ring)157            }158        }159        .accessibilityHidden(true)160    }161}162163#Preview("Starfield") {164    ZStack {165        LunarWindowBackground()166        LunarStarfield()167        LunarOrbitRings(count: 3).frame(width: 320, height: 320)168        LunarMarkView(size: 96)169    }170    .frame(width: 640, height: 420)171    .lunarTheme(LunarThemes.lunar.dark)172}173
Files main
Menu

Theme