astronomy: ktlint rollout — format module and fix residue
- Commit
43ccbe290958c1c93e6612bdfe978f9dddc1e691- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 19:30 UTC (4 days ago)
- Parents
f87071c
Ran ./format astronomy over the whole module: 2,233 violations in 55 files at census (main 1,706, test 471, screenshotTest 47, androidTest 9) are down to zero, verified by ktlintCheck on every source set. Manual fixes for the 20 non-autocorrectable residues, all in main: - Renamed single-letter and PascalCase local properties to camelCase in the ephemeris engine (standard: property-naming): LunarCalculator (Lp/Mm/Ms/D2/F2 and their *Rad forms to mean-longitude / mean-anomaly / elongation / latitude-argument names), PlanetaryCalculator (Mdeg/Mrad/Erad), RiseSetCalculator (H0 to hourAngleRad), SolarCalculator (L/g/R to meanLongitudeDeg / meanAnomalyDeg / distanceAu) and TimeEngine (T to centuries, g to normalizedGmstDeg). All are function locals; no declaration or API changed. - Merged the doubled KDoc in AstronomyUiContract (standard:no-consecutive-comments) onto SkyMapUiState. - Moved the inline block comment on SkyMapScreen's disabled onPan onto its own line (standard: comment-wrapping). No file needed a standard:filename rename: every single-declaration file already matches its declaration. Fixes that expansion (or the lint it then allowed) surfaced: - detekt LongMethod: computeVisibleSky (69 lines) in AstronomyViewModel extracted its constellation-art and planet blocks into file-private visibleArt / visiblePlanets helpers beside resolveViewCenter, the same TooManyFunctions-safe shape that file already uses. - lint FileLength: SkyCanvas reached 354 lines (350 ui limit); the deep-sky drawing block moved to ui/DrawDeepSkyObjects.kt, documented in astronomy/AGENTS.md. - lint StringFormatMatches: SettingsScreen passed an Int to the %1$s fov string at both call sites; it now passes the Int as a String, with no visible change. No ktlint rule was disabled, no detekt or lint config was touched, and no baseline was added. Verified: ./gradlew :astronomy:detekt :astronomy:lint :astronomy:ktlintCheck :astronomy:compileDevKotlin green (lint and compile with the cargoBuild tasks excluded — see below); :astronomy:testDevUnitTest runs 132 tests with 1 failure. Two blockers are pre-existing and outside this module: the workspace Cargo.lock is stale for an unrelated crate (cargo check --locked reproduces it on the untouched tree), so the --locked cargo builds fail before Kotlin runs, and the failing SettingsScreenInteractionsTest slider-count assertion fails identically on a clean HEAD worktree.
Diff
astronomy/AGENTS.md
diff --git a/astronomy/AGENTS.md b/astronomy/AGENTS.mdindex 8f9a458e19..02bfc27d77 100644--- a/astronomy/AGENTS.md+++ b/astronomy/AGENTS.md@@ -42,6 +42,7 @@ _Install: ./install astronomy (dev by default)._ ### ui/ — sky map + detail + search - com/vayunmathur/astronomy/ui/SkyMapPage.kt - com/vayunmathur/astronomy/ui/SkyCanvas.kt+- com/vayunmathur/astronomy/ui/DrawDeepSkyObjects.kt - com/vayunmathur/astronomy/ui/SkyGrid.kt - com/vayunmathur/astronomy/ui/SkyArt.kt - com/vayunmathur/astronomy/ui/ObjectDetailPage.kt
astronomy/src/androidTest/java/com/vayunmathur/astronomy/ui/FullE2eTest.kt
diff --git a/astronomy/src/androidTest/java/com/vayunmathur/astronomy/ui/FullE2eTest.kt b/astronomy/src/androidTest/java/com/vayunmathur/astronomy/ui/FullE2eTest.ktindex 9548c770ea..82e9bcb84a 100644--- a/astronomy/src/androidTest/java/com/vayunmathur/astronomy/ui/FullE2eTest.kt+++ b/astronomy/src/androidTest/java/com/vayunmathur/astronomy/ui/FullE2eTest.kt@@ -8,12 +8,12 @@ import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.By import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.Until-import java.io.IOException import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Test import org.junit.runner.RunWith+import java.io.IOException /** * Full e2e test: launches the app, grants every requested permission, and@@ -37,7 +37,6 @@ import org.junit.runner.RunWith */ @RunWith(AndroidJUnit4::class) class FullE2eTest {- @Test fun launch_grantsPermissions_showsSkyMap() { val instrumentation = InstrumentationRegistry.getInstrumentation()@@ -101,11 +100,12 @@ class FullE2eTest { packageManager: PackageManager, packageName: String, ) {- val info = try {- packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)- } catch (e: PackageManager.NameNotFoundException) {- throw AssertionError("package $packageName not installed", e)- }+ val info =+ try {+ packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+ } catch (e: PackageManager.NameNotFoundException) {+ throw AssertionError("package $packageName not installed", e)+ } for (permission in info.requestedPermissions.orEmpty()) { try { uiAutomation.executeShellCommand("pm grant $packageName $permission").close()@@ -142,9 +142,10 @@ class FullE2eTest { * have no pm-grantable permission, but the shell can flip their appops. * Ignored where the appop does not exist; the gate assertion reports it. */- private val SPECIAL_ACCESS_COMMANDS = arrayOf(- "appops set %s SCHEDULE_EXACT_ALARM allow",- "appops set %s USE_FULL_SCREEN_INTENT allow",- )+ private val SPECIAL_ACCESS_COMMANDS =+ arrayOf(+ "appops set %s SCHEDULE_EXACT_ALARM allow",+ "appops set %s USE_FULL_SCREEN_INTENT allow",+ ) } }
astronomy/src/main/java/com/vayunmathur/astronomy/MainActivity.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/MainActivity.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/MainActivity.ktindex 2bf4485c16..87864633e2 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/MainActivity.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/MainActivity.kt@@ -16,17 +16,19 @@ class MainActivity : MaActivity() { @Composable override fun Content() { AppPermissionsGate(- spec = AppPermissionsSpec(- title = "Grant location permission — astronomy needs your position for horizon",- requirements = listOf(- PermissionRequirement.Runtime(- arrayOf(- Manifest.permission.ACCESS_FINE_LOCATION,- Manifest.permission.ACCESS_COARSE_LOCATION- )- )- )- )+ spec =+ AppPermissionsSpec(+ title = "Grant location permission — astronomy needs your position for horizon",+ requirements =+ listOf(+ PermissionRequirement.Runtime(+ arrayOf(+ Manifest.permission.ACCESS_FINE_LOCATION,+ Manifest.permission.ACCESS_COARSE_LOCATION,+ ),+ ),+ ),+ ), ) { Navigation(viewModel) }
astronomy/src/main/java/com/vayunmathur/astronomy/Route.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/Route.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/Route.ktindex a1d9684d7a..b45d335317 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/Route.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/Route.kt@@ -11,7 +11,9 @@ sealed interface Route : NavKey { @Serializable data object SkyMap : Route /** Detail screen for the celestial object identified by [id]. */- @Serializable data class ObjectDetail(val id: String) : Route+ @Serializable data class ObjectDetail(+ val id: String,+ ) : Route /** Search screen for catalog objects. */ @Serializable data object Search : Route@@ -20,5 +22,7 @@ sealed interface Route : NavKey { @Serializable data object Settings : Route /** Date picker for scrubbing to a historical date, starting at [initialDate]. */- @Serializable data class HistoryDatePicker(val initialDate: LocalDate) : Route+ @Serializable data class HistoryDatePicker(+ val initialDate: LocalDate,+ ) : Route }
astronomy/src/main/java/com/vayunmathur/astronomy/data/CatalogRepository.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/data/CatalogRepository.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/data/CatalogRepository.ktindex 7de83b80e1..d585f856a5 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/data/CatalogRepository.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/data/CatalogRepository.kt@@ -21,41 +21,63 @@ class CatalogRepository( /** Reads one bundled asset as text, or null when it cannot be read. Injectable for tests. */ private val assetLoader: (String) -> String? = { path -> try {- context.assets.open(path).bufferedReader().use { it.readText() }+ context.assets+ .open(path)+ .bufferedReader()+ .use { it.readText() } } catch (_: Exception) { null } }, ) {- private val json = Json { ignoreUnknownKeys = true; isLenient = true }- var stars: List<Star> = emptyList(); private set- var constellations: List<Constellation> = emptyList(); private set- var constellationArt: List<ConstellationArt> = emptyList(); private set- var deepSky: List<DeepSkyObject> = emptyList(); private set- var planets: List<OrbitalElements> = emptyList(); private set- var earth: OrbitalElements? = null; private set+ private val json =+ Json {+ ignoreUnknownKeys = true+ isLenient = true+ }+ var stars: List<Star> = emptyList()+ private set+ var constellations: List<Constellation> = emptyList()+ private set+ var constellationArt: List<ConstellationArt> = emptyList()+ private set+ var deepSky: List<DeepSkyObject> = emptyList()+ private set+ var planets: List<OrbitalElements> = emptyList()+ private set+ var earth: OrbitalElements? = null+ private set+ @Volatile private var loaded = false - suspend fun loadAll() = withContext(Dispatchers.IO) {- if (loaded) return@withContext- stars = loadStars()- constellations = loadConstellations()- constellationArt = loadConstellationArt()- deepSky = loadDeepSky()- val orbital = loadOrbital()- planets = orbital.planets- earth = planets.firstOrNull { it.id == "EARTH" }- loaded = true- }+ suspend fun loadAll() =+ withContext(Dispatchers.IO) {+ if (loaded) return@withContext+ stars = loadStars()+ constellations = loadConstellations()+ constellationArt = loadConstellationArt()+ deepSky = loadDeepSky()+ val orbital = loadOrbital()+ planets = orbital.planets+ earth = planets.firstOrNull { it.id == "EARTH" }+ loaded = true+ } private fun loadJsonAsset(path: String): String? = assetLoader(path) private fun loadStars(): List<Star> { val text = loadJsonAsset("catalog/stars.json") ?: return BuiltInCatalogs.stars- return try { json.decodeFromString<StarsCatalog>(text).stars } catch (_: Exception) {- try { json.decodeFromString<List<Star>>(text) } catch (_: Exception) { BuiltInCatalogs.stars }+ return try {+ json.decodeFromString<StarsCatalog>(text).stars+ } catch (_: Exception) {+ try {+ json.decodeFromString<List<Star>>(text)+ } catch (_: Exception) {+ BuiltInCatalogs.stars+ } } }+ private fun loadConstellations(): List<Constellation> { val text = loadJsonAsset("catalog/constellations.json") ?: return BuiltInCatalogs.constellations return try {@@ -68,18 +90,33 @@ class CatalogRepository( } } }+ private fun loadConstellationArt(): List<ConstellationArt> { val text = loadJsonAsset("catalog/constellation_art.json") ?: return emptyList()- return try { json.decodeFromString<ConstellationArtCatalog>(text).art } catch (_: Exception) {- try { json.decodeFromString<List<ConstellationArt>>(text) } catch (_: Exception) { emptyList() }+ return try {+ json.decodeFromString<ConstellationArtCatalog>(text).art+ } catch (_: Exception) {+ try {+ json.decodeFromString<List<ConstellationArt>>(text)+ } catch (_: Exception) {+ emptyList()+ } } }+ private fun loadDeepSky(): List<DeepSkyObject> { val text = loadJsonAsset("catalog/messier.json") ?: return BuiltInCatalogs.messier- return try { json.decodeFromString<DeepSkyCatalog>(text).objects } catch (_: Exception) {- try { json.decodeFromString<List<DeepSkyObject>>(text) } catch (_: Exception) { BuiltInCatalogs.messier }+ return try {+ json.decodeFromString<DeepSkyCatalog>(text).objects+ } catch (_: Exception) {+ try {+ json.decodeFromString<List<DeepSkyObject>>(text)+ } catch (_: Exception) {+ BuiltInCatalogs.messier+ } } }+ private fun loadOrbital(): OrbitalElementsCatalog { val text = loadJsonAsset("catalog/orbital_elements.json") if (text != null) {@@ -98,39 +135,390 @@ class CatalogRepository( /** Small built-in fallback catalogs used when a bundled asset is missing or unreadable. */ object BuiltInCatalogs {- val stars: List<Star> = listOf(- // RA/Dec (radians, J2000) match the bundled catalog/stars.json entries- // of the same names; the fallback is what renders when the asset- // cannot be read, so it must place the named stars on the real sky.- Star(1, 1.7677953696021995, -0.291751258517685, -1.44, 0.0, "Sirius", "Sirius", "Alpha", null, "CMa", 8.6, "A1V"),- Star(2, 1.6753053519997292, -0.9197127748902675, -0.62, 0.0, "Canopus", "Canopus", "Alpha", null, "Car", 310.0, "A9 II"),- Star(3, 3.7335290285420872, 0.33479621805862125, -0.05, 0.01, "Arcturus", "Arcturus", "Alpha", null, "Boo", 36.7, "K0 III"),- Star(4, 4.873563095509031, 0.6769031163973025, -0.05, 0.15, "Vega", "Vega", "Alpha", null, "Lyr", 25.0, "A0 Va"),- Star(5, 1.381816412648801, 0.8028163926341112, 0.03, 0.15, "Capella", "Capella", "Alpha", null, "Aur", 42.9, "G3 III"),- Star(6, 1.3724303693276385, -0.143145630755865, 0.08, 0.0, "Rigel", "Rigel", "Beta", null, "Ori", 860.0, "B8 Ia"),- Star(7, 2.004083041242831, 0.09119333187796, 0.12, 0.0, "Procyon", "Procyon", "Alpha", null, "CMi", 11.46, "F5 IV-V"),- Star(8, 1.5497291183713153, 0.12927763169419373, 0.42, 0.0, "Betelgeuse", "Betelgeuse", "Alpha", null, "Ori", 642.5,- "M1-M2 Ia-Iab"),- Star(9, 0.42635506591376426, -0.9989698692415762, 0.42, -0.21, "Achernar", "Achernar", "Alpha", null, "Eri", 139.0, "B6 Vep"),- Star(10, 3.681875660376148, -1.053708314075195, 0.50, 0.14, "Hadar", "Agena", "Beta", null, "Cen", 390.0, "B1 III"),- Star(11, 5.195772105546999, 0.15478141706831, 0.61, 0.0, "Altair", "Altair", "Alpha", null, "Aql", 16.73, "A7 V"),- Star(12, 1.2039308112027507, 0.2881416661221312, 0.76, 0.07, "Aldebaran", "Aldebaran", "Alpha", null, "Tau", 65.0, "K5 III"),- Star(13, 4.317105466000638, -0.4613254705959812, 0.77, 0.39, "Antares", "Antares", "Alpha", 21, "Sco", 550.0, "M1.5 Iab-b"),- Star(14, 3.2576512815622607, -1.1012869028642311, 0.79, 0.14, "Acrux", "Acrux", "Alpha", null, "Cru", 321.0, "B0.5 IV"),- Star(15, 3.5133172180991257, -0.194801818024575, 0.87, -0.04, "Spica", "Spica", "Alpha", 67, "Vir", 250.0, "B1 III-IV"),- Star(16, 2.0303268874812184, 0.4891494417459975, 0.97, 0.0, "Pollux", "Pollux", "Beta", 78, "Gem", 33.78, "K0 III"),- Star(17, 6.011133383906492, -0.5170055514089774, 1.06, 1.48, "Fomalhaut", "Fomalhaut", "Alpha", null, "PsA", 25.13, "A4 V"),- Star(18, 3.349817026601454, -1.0417654498397388, 1.14, 1.42, "Mimosa", "Becrux", "Beta", null, "Cru", 280.0, "B0.5 III"),- Star(19, 5.416768542177067, 0.790290982752855, 1.16, 0.09, "Deneb", "Deneb", "Alpha", 50, "Cyg", 2600.0, "A2 Ia"),- Star(20, 0.6622870748653336, 1.5579526129751475, 1.98, 0.0, "Polaris", "Polaris", "Alpha", 1, "UMi", 433.0, "F7 Ib"),- Star(21, 2.896065350203451, 1.0777588446528075, 2.9, 0.0, "Dubhe", "Dubhe", "Alpha", 50, "UMa", 123.0, "F7"),- Star(22, 0.17674488133148336, 0.9867625763100912, 2.7, 0.0, "Schedar", "Schedar", "Alpha", 18, "Cas", 228.0, "K0 IIIa"),- Star(23, 0.040025852830323276, 1.0323584043676326, 2.2, 0.0, "Caph", "Caph", "Beta", 8, "Cas", 54.0, "F2 III-IV"),- Star(24, 4.953529829382003, -0.4589643844760175, 2.1, 0.0, "Nunki", "Nunki", "Sigma", 0, "Sgr", 228.0, "B2.5 V"),- Star(25, 3.838179211777228, -1.0617531757704175, 0.4, 0.0, "Rigil Kentaurus", "Rigil Kentaurus", "Alpha", null, "Cen", 4.37, "G2 V"),- Star(26, 1.983558270234413, 0.5565554130270287, 0.77, 0.0, "Castor", "Castor", "Alpha", 66, "Gem", 52.0, "A1 V"),- Star(27, 3.349817026601454, -1.0417654498397388, 1.25, 0.0, "Beta Crucis", "Mimosa", "Beta", null, "Cru", 280.0, "B0.5 III"),- ) + generateFillerStars()+ val stars: List<Star> =+ listOf(+ // RA/Dec (radians, J2000) match the bundled catalog/stars.json entries+ // of the same names; the fallback is what renders when the asset+ // cannot be read, so it must place the named stars on the real sky.+ Star(+ 1,+ 1.7677953696021995,+ -0.291751258517685,+ -1.44,+ 0.0,+ "Sirius",+ "Sirius",+ "Alpha",+ null,+ "CMa",+ 8.6,+ "A1V",+ ),+ Star(+ 2,+ 1.6753053519997292,+ -0.9197127748902675,+ -0.62,+ 0.0,+ "Canopus",+ "Canopus",+ "Alpha",+ null,+ "Car",+ 310.0,+ "A9 II",+ ),+ Star(+ 3,+ 3.7335290285420872,+ 0.33479621805862125,+ -0.05,+ 0.01,+ "Arcturus",+ "Arcturus",+ "Alpha",+ null,+ "Boo",+ 36.7,+ "K0 III",+ ),+ Star(+ 4,+ 4.873563095509031,+ 0.6769031163973025,+ -0.05,+ 0.15,+ "Vega",+ "Vega",+ "Alpha",+ null,+ "Lyr",+ 25.0,+ "A0 Va",+ ),+ Star(+ 5,+ 1.381816412648801,+ 0.8028163926341112,+ 0.03,+ 0.15,+ "Capella",+ "Capella",+ "Alpha",+ null,+ "Aur",+ 42.9,+ "G3 III",+ ),+ Star(+ 6,+ 1.3724303693276385,+ -0.143145630755865,+ 0.08,+ 0.0,+ "Rigel",+ "Rigel",+ "Beta",+ null,+ "Ori",+ 860.0,+ "B8 Ia",+ ),+ Star(+ 7,+ 2.004083041242831,+ 0.09119333187796,+ 0.12,+ 0.0,+ "Procyon",+ "Procyon",+ "Alpha",+ null,+ "CMi",+ 11.46,+ "F5 IV-V",+ ),+ Star(+ 8,+ 1.5497291183713153,+ 0.12927763169419373,+ 0.42,+ 0.0,+ "Betelgeuse",+ "Betelgeuse",+ "Alpha",+ null,+ "Ori",+ 642.5,+ "M1-M2 Ia-Iab",+ ),+ Star(+ 9,+ 0.42635506591376426,+ -0.9989698692415762,+ 0.42,+ -0.21,+ "Achernar",+ "Achernar",+ "Alpha",+ null,+ "Eri",+ 139.0,+ "B6 Vep",+ ),+ Star(+ 10,+ 3.681875660376148,+ -1.053708314075195,+ 0.50,+ 0.14,+ "Hadar",+ "Agena",+ "Beta",+ null,+ "Cen",+ 390.0,+ "B1 III",+ ),+ Star(+ 11,+ 5.195772105546999,+ 0.15478141706831,+ 0.61,+ 0.0,+ "Altair",+ "Altair",+ "Alpha",+ null,+ "Aql",+ 16.73,+ "A7 V",+ ),+ Star(+ 12,+ 1.2039308112027507,+ 0.2881416661221312,+ 0.76,+ 0.07,+ "Aldebaran",+ "Aldebaran",+ "Alpha",+ null,+ "Tau",+ 65.0,+ "K5 III",+ ),+ Star(+ 13,+ 4.317105466000638,+ -0.4613254705959812,+ 0.77,+ 0.39,+ "Antares",+ "Antares",+ "Alpha",+ 21,+ "Sco",+ 550.0,+ "M1.5 Iab-b",+ ),+ Star(+ 14,+ 3.2576512815622607,+ -1.1012869028642311,+ 0.79,+ 0.14,+ "Acrux",+ "Acrux",+ "Alpha",+ null,+ "Cru",+ 321.0,+ "B0.5 IV",+ ),+ Star(+ 15,+ 3.5133172180991257,+ -0.194801818024575,+ 0.87,+ -0.04,+ "Spica",+ "Spica",+ "Alpha",+ 67,+ "Vir",+ 250.0,+ "B1 III-IV",+ ),+ Star(+ 16,+ 2.0303268874812184,+ 0.4891494417459975,+ 0.97,+ 0.0,+ "Pollux",+ "Pollux",+ "Beta",+ 78,+ "Gem",+ 33.78,+ "K0 III",+ ),+ Star(+ 17,+ 6.011133383906492,+ -0.5170055514089774,+ 1.06,+ 1.48,+ "Fomalhaut",+ "Fomalhaut",+ "Alpha",+ null,+ "PsA",+ 25.13,+ "A4 V",+ ),+ Star(+ 18,+ 3.349817026601454,+ -1.0417654498397388,+ 1.14,+ 1.42,+ "Mimosa",+ "Becrux",+ "Beta",+ null,+ "Cru",+ 280.0,+ "B0.5 III",+ ),+ Star(+ 19,+ 5.416768542177067,+ 0.790290982752855,+ 1.16,+ 0.09,+ "Deneb",+ "Deneb",+ "Alpha",+ 50,+ "Cyg",+ 2600.0,+ "A2 Ia",+ ),+ Star(+ 20,+ 0.6622870748653336,+ 1.5579526129751475,+ 1.98,+ 0.0,+ "Polaris",+ "Polaris",+ "Alpha",+ 1,+ "UMi",+ 433.0,+ "F7 Ib",+ ),+ Star(+ 21,+ 2.896065350203451,+ 1.0777588446528075,+ 2.9,+ 0.0,+ "Dubhe",+ "Dubhe",+ "Alpha",+ 50,+ "UMa",+ 123.0,+ "F7",+ ),+ Star(+ 22,+ 0.17674488133148336,+ 0.9867625763100912,+ 2.7,+ 0.0,+ "Schedar",+ "Schedar",+ "Alpha",+ 18,+ "Cas",+ 228.0,+ "K0 IIIa",+ ),+ Star(+ 23,+ 0.040025852830323276,+ 1.0323584043676326,+ 2.2,+ 0.0,+ "Caph",+ "Caph",+ "Beta",+ 8,+ "Cas",+ 54.0,+ "F2 III-IV",+ ),+ Star(+ 24,+ 4.953529829382003,+ -0.4589643844760175,+ 2.1,+ 0.0,+ "Nunki",+ "Nunki",+ "Sigma",+ 0,+ "Sgr",+ 228.0,+ "B2.5 V",+ ),+ Star(+ 25,+ 3.838179211777228,+ -1.0617531757704175,+ 0.4,+ 0.0,+ "Rigil Kentaurus",+ "Rigil Kentaurus",+ "Alpha",+ null,+ "Cen",+ 4.37,+ "G2 V",+ ),+ Star(+ 26,+ 1.983558270234413,+ 0.5565554130270287,+ 0.77,+ 0.0,+ "Castor",+ "Castor",+ "Alpha",+ 66,+ "Gem",+ 52.0,+ "A1 V",+ ),+ Star(+ 27,+ 3.349817026601454,+ -1.0417654498397388,+ 1.25,+ 0.0,+ "Beta Crucis",+ "Mimosa",+ "Beta",+ null,+ "Cru",+ 280.0,+ "B0.5 III",+ ),+ ) + generateFillerStars() private const val FILLER_STAR_COUNT = 4000 @@ -149,61 +537,170 @@ object BuiltInCatalogs { return list } - val constellations: List<Constellation> = listOf(- Constellation("UMa", "Ursa Major", listOf(listOf(21,22), listOf(22,23))),- Constellation("UMi", "Ursa Minor", listOf(listOf(20,21))),- Constellation("Ori", "Orion", listOf(listOf(8,6), listOf(6,1))),- Constellation("Cas", "Cassiopeia", listOf(listOf(22,23))),- Constellation("Sco", "Scorpius", listOf(listOf(13,24))),- Constellation("Cru", "Crux", listOf(listOf(14,27))),- Constellation("Lyr", "Lyra", listOf(listOf(4,19))),- Constellation("Gem", "Gemini", listOf(listOf(16,26))),- Constellation("Cen", "Centaurus", listOf(listOf(25,14))),- )+ val constellations: List<Constellation> =+ listOf(+ Constellation("UMa", "Ursa Major", listOf(listOf(21, 22), listOf(22, 23))),+ Constellation("UMi", "Ursa Minor", listOf(listOf(20, 21))),+ Constellation("Ori", "Orion", listOf(listOf(8, 6), listOf(6, 1))),+ Constellation("Cas", "Cassiopeia", listOf(listOf(22, 23))),+ Constellation("Sco", "Scorpius", listOf(listOf(13, 24))),+ Constellation("Cru", "Crux", listOf(listOf(14, 27))),+ Constellation("Lyr", "Lyra", listOf(listOf(4, 19))),+ Constellation("Gem", "Gemini", listOf(listOf(16, 26))),+ Constellation("Cen", "Centaurus", listOf(listOf(25, 14))),+ ) // RA/Dec (radians, J2000) match the bundled catalog/messier.json entries.- val messier: List<DeepSkyObject> = listOf(- DeepSkyObject("M31", "Andromeda Galaxy", 0.1864011641129944, 0.7202746930177839, 3.4, "galaxy", 178.0, "And"),- DeepSkyObject("M42", "Orion Nebula", 1.462971630935939, -0.09409244530426629, 4.0, "nebula", 65.0, "Ori"),- DeepSkyObject("M45", "Pleiades", 0.990474350506782, 0.4209158197157165, 1.6, "cluster", 110.0, "Tau"),- DeepSkyObject("M13", "Hercules Cluster", 4.3706535128442, 0.6363470452771326, 5.8, "cluster", 20.0, "Her"),- DeepSkyObject("M51", "Whirlpool Galaxy", 3.5337786084884306, 0.8237133764664799, 8.4, "galaxy", 11.0, "CVn"),- DeepSkyObject("M57", "Ring Nebula", 4.946193286981851, 0.5764647986412071, 8.8, "nebula", 1.5, "Lyr"),- )-- val orbital: List<OrbitalElements> = listOf(- OrbitalElements("SUN", "Sun", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, null, 0xFFFFD700, -26.7),- OrbitalElements(- "EARTH", "Earth", 1.0, 0.0167086, 0.0, -11.26064, 102.9372, 100.46435, 8.78779,- 0.9856091, null, 0xFF00FF00, -3.0,- ),- OrbitalElements(- "MERCURY", "Mercury", 0.38709893, 0.20563069, 7.00487, 48.33167, 29.12478, 252.33145, 174.875,- 4.09233445, 4879.0, 0xFFA9A9A9, -0.42,- ),- OrbitalElements(- "VENUS", "Venus", 0.72333199, 0.00677323, 3.39471, 76.68069, 54.88378, 181.975, 50.41053,- 1.60213034, 12104.0, 0xFFFFE0B0, -4.4,- ),- OrbitalElements(- "MARS", "Mars", 1.52366231, 0.09341233, 1.85061, 49.57854, 286.4623, 355.453, 19.41216,- 0.52402068, 6792.0, 0xFFFF4500, -0.5,- ),- OrbitalElements(- "JUPITER", "Jupiter", 5.20336301, 0.04839266, 1.30530, 100.55615, 273.8777, 34.40438, 20.0202,- 0.08308529, 139820.0, 0xFFFFDAB9, -9.4,- ),- OrbitalElements(- "SATURN", "Saturn", 9.53707032, 0.05386179, 2.48446, 113.71504, 339.3939, 49.94432, 317.020,- 0.03344414, 116460.0, 0xFFF0E68C, -8.9,- ),- OrbitalElements(- "URANUS", "Uranus", 19.19126393, 0.04725744, 0.76986, 74.22988, 96.73436, 313.23218, 142.2386,- 0.01172834, 50724.0, 0xFFADD8E6, -7.1,- ),- OrbitalElements(- "NEPTUNE", "Neptune", 30.06896348, 0.00859048, 1.76917, 131.72169, 272.8461, 304.88003, 260.31224,- 0.00598103, 49244.0, 0xFF4169E1, -6.9,- ),- )+ val messier: List<DeepSkyObject> =+ listOf(+ DeepSkyObject(+ "M31",+ "Andromeda Galaxy",+ 0.1864011641129944,+ 0.7202746930177839,+ 3.4,+ "galaxy",+ 178.0,+ "And",+ ),+ DeepSkyObject("M42", "Orion Nebula", 1.462971630935939, -0.09409244530426629, 4.0, "nebula", 65.0, "Ori"),+ DeepSkyObject("M45", "Pleiades", 0.990474350506782, 0.4209158197157165, 1.6, "cluster", 110.0, "Tau"),+ DeepSkyObject("M13", "Hercules Cluster", 4.3706535128442, 0.6363470452771326, 5.8, "cluster", 20.0, "Her"),+ DeepSkyObject(+ "M51",+ "Whirlpool Galaxy",+ 3.5337786084884306,+ 0.8237133764664799,+ 8.4,+ "galaxy",+ 11.0,+ "CVn",+ ),+ DeepSkyObject("M57", "Ring Nebula", 4.946193286981851, 0.5764647986412071, 8.8, "nebula", 1.5, "Lyr"),+ )++ val orbital: List<OrbitalElements> =+ listOf(+ OrbitalElements("SUN", "Sun", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, null, 0xFFFFD700, -26.7),+ OrbitalElements(+ "EARTH",+ "Earth",+ 1.0,+ 0.0167086,+ 0.0,+ -11.26064,+ 102.9372,+ 100.46435,+ 8.78779,+ 0.9856091,+ null,+ 0xFF00FF00,+ -3.0,+ ),+ OrbitalElements(+ "MERCURY",+ "Mercury",+ 0.38709893,+ 0.20563069,+ 7.00487,+ 48.33167,+ 29.12478,+ 252.33145,+ 174.875,+ 4.09233445,+ 4879.0,+ 0xFFA9A9A9,+ -0.42,+ ),+ OrbitalElements(+ "VENUS",+ "Venus",+ 0.72333199,+ 0.00677323,+ 3.39471,+ 76.68069,+ 54.88378,+ 181.975,+ 50.41053,+ 1.60213034,+ 12104.0,+ 0xFFFFE0B0,+ -4.4,+ ),+ OrbitalElements(+ "MARS",+ "Mars",+ 1.52366231,+ 0.09341233,+ 1.85061,+ 49.57854,+ 286.4623,+ 355.453,+ 19.41216,+ 0.52402068,+ 6792.0,+ 0xFFFF4500,+ -0.5,+ ),+ OrbitalElements(+ "JUPITER",+ "Jupiter",+ 5.20336301,+ 0.04839266,+ 1.30530,+ 100.55615,+ 273.8777,+ 34.40438,+ 20.0202,+ 0.08308529,+ 139820.0,+ 0xFFFFDAB9,+ -9.4,+ ),+ OrbitalElements(+ "SATURN",+ "Saturn",+ 9.53707032,+ 0.05386179,+ 2.48446,+ 113.71504,+ 339.3939,+ 49.94432,+ 317.020,+ 0.03344414,+ 116460.0,+ 0xFFF0E68C,+ -8.9,+ ),+ OrbitalElements(+ "URANUS",+ "Uranus",+ 19.19126393,+ 0.04725744,+ 0.76986,+ 74.22988,+ 96.73436,+ 313.23218,+ 142.2386,+ 0.01172834,+ 50724.0,+ 0xFFADD8E6,+ -7.1,+ ),+ OrbitalElements(+ "NEPTUNE",+ "Neptune",+ 30.06896348,+ 0.00859048,+ 1.76917,+ 131.72169,+ 272.8461,+ 304.88003,+ 260.31224,+ 0.00598103,+ 49244.0,+ 0xFF4169E1,+ -6.9,+ ),+ ) }
astronomy/src/main/java/com/vayunmathur/astronomy/data/model/Models.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/data/model/Models.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/data/model/Models.ktindex e26eeeb981..237aaf64fa 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/data/model/Models.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/data/model/Models.kt@@ -18,7 +18,7 @@ data class Star( val flamsteed: Int? = null, val constellation: String? = null, val distanceLy: Double? = null,- val spectralClass: String? = null+ val spectralClass: String? = null, ) /** A constellation identified by abbreviation, with stick-figure lines joining star ids. */@@ -26,7 +26,7 @@ data class Star( data class Constellation( val abbr: String, val name: String,- val lines: List<List<Int>>+ val lines: List<List<Int>>, ) /** One alignment point tying a figure-image pixel to the catalog star it must overlay. */@@ -34,7 +34,7 @@ data class Constellation( data class ArtAnchor( val x: Int, // pixel x in the figure image val y: Int, // pixel y in the figure image- val hip: Int // star (catalog id) this pixel should align to+ val hip: Int, // star (catalog id) this pixel should align to ) /** A constellation figure image and its three anchors defining its sky placement. */@@ -42,7 +42,7 @@ data class ArtAnchor( data class ConstellationArt( val abbr: String, val image: String, // asset filename under constellation_art/- val anchors: List<ArtAnchor> // exactly 3, defines the affine placement+ val anchors: List<ArtAnchor>, // exactly 3, defines the affine placement ) /** A deep-sky catalog entry (galaxy, nebula, or cluster) at J2000 coordinates. */@@ -55,7 +55,7 @@ data class DeepSkyObject( val mag: Double, val type: String, val sizeArcmin: Double? = null,- val constellation: String? = null+ val constellation: String? = null, ) /** Keplerian orbital elements for a solar-system body, used to compute its position. */@@ -73,31 +73,43 @@ data class OrbitalElements( val nDegPerDay: Double, val diameterKm: Double? = null, val colorArgb: Long? = null,- val magBase: Double? = null+ val magBase: Double? = null, ) /** Serialized wrapper for the bundled star catalog. */ @Serializable-data class StarsCatalog(val stars: List<Star>)+data class StarsCatalog(+ val stars: List<Star>,+) /** Serialized wrapper for the bundled constellation catalog. */ @Serializable-data class ConstellationsCatalog(val constellations: List<Constellation>)+data class ConstellationsCatalog(+ val constellations: List<Constellation>,+) /** Serialized wrapper for the bundled constellation-art catalog. */ @Serializable-data class ConstellationArtCatalog(val art: List<ConstellationArt>)+data class ConstellationArtCatalog(+ val art: List<ConstellationArt>,+) /** Serialized wrapper for the bundled deep-sky catalog. */ @Serializable-data class DeepSkyCatalog(val objects: List<DeepSkyObject>)+data class DeepSkyCatalog(+ val objects: List<DeepSkyObject>,+) /** Serialized wrapper for the bundled orbital-elements catalog. */ @Serializable-data class OrbitalElementsCatalog(val planets: List<OrbitalElements>)+data class OrbitalElementsCatalog(+ val planets: List<OrbitalElements>,+) /** Solar-system bodies shown as planets, each with its display-name string resource. */-enum class PlanetId(@StringRes val displayNameRes: Int) {+enum class PlanetId(+ @StringRes val displayNameRes: Int,+) { SUN(R.string.planet_sun), MOON(R.string.planet_moon), MERCURY(R.string.planet_mercury),@@ -106,5 +118,5 @@ enum class PlanetId(@StringRes val displayNameRes: Int) { JUPITER(R.string.planet_jupiter), SATURN(R.string.planet_saturn), URANUS(R.string.planet_uranus),- NEPTUNE(R.string.planet_neptune)+ NEPTUNE(R.string.planet_neptune), }
astronomy/src/main/java/com/vayunmathur/astronomy/domain/AstronomyNative.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/AstronomyNative.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/AstronomyNative.ktindex 710905e12a..f89e00523c 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/AstronomyNative.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/AstronomyNative.kt@@ -23,7 +23,11 @@ object AstronomyNative { * Batch RaDec -> AltAz. [radec] is interleaved `[ra0,dec0,ra1,dec1,...]` in * radians; returns interleaved `[az0,alt0,az1,alt1,...]` in radians. */- external fun batchRaDecToAltAz(radec: DoubleArray, lstRad: Double, latRad: Double): DoubleArray+ external fun batchRaDecToAltAz(+ radec: DoubleArray,+ lstRad: Double,+ latRad: Double,+ ): DoubleArray /** * Batch stereographic projection. [altaz] is interleaved `[az0,alt0,...]`;
astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/CoordinateTransforms.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/CoordinateTransforms.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/CoordinateTransforms.ktindex 2b528a2241..c24297e014 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/CoordinateTransforms.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/CoordinateTransforms.kt@@ -9,25 +9,37 @@ import kotlin.math.sin import kotlin.math.tan /** Equatorial coordinates: right ascension and declination in radians (J2000). */-data class RaDec(val raRad: Double, val decRad: Double) {+data class RaDec(+ val raRad: Double,+ val decRad: Double,+) { val raDeg get() = raRad.toDeg() val decDeg get() = decRad.toDeg() val raHours get() = raDeg / 15.0 } /** Horizontal coordinates: azimuth and altitude in radians for an observer. */-data class AltAz(val azRad: Double, val altRad: Double) {+data class AltAz(+ val azRad: Double,+ val altRad: Double,+) { val azDeg get() = azRad.toDeg() val altDeg get() = altRad.toDeg() } /** Ecliptic longitude and latitude in radians. */-data class Ecliptic(val lonRad: Double, val latRad: Double)+data class Ecliptic(+ val lonRad: Double,+ val latRad: Double,+) /** Conversions between equatorial, horizontal, and ecliptic coordinates. */ object CoordinateTransforms {-- fun raDecToAltAz(raDec: RaDec, lstRad: Double, latRad: Double): AltAz {+ fun raDecToAltAz(+ raDec: RaDec,+ lstRad: Double,+ latRad: Double,+ ): AltAz { val ha = (lstRad - raDec.raRad).normalizePi() val sinDec = sin(raDec.decRad) val cosDec = cos(raDec.decRad)@@ -42,16 +54,22 @@ object CoordinateTransforms { // This form tends to the continuous pole limit (HA + 180deg at the // north pole); at the zenith both arguments vanish and atan2 gives // 0, as before.- val az = atan2(- -cosDec * sin(ha),- sinDec * cos(latRad) - cosDec * cos(ha) * sin(latRad),- ).normalize2Pi()+ val az =+ atan2(+ -cosDec * sin(ha),+ sinDec * cos(latRad) - cosDec * cos(ha) * sin(latRad),+ ).normalize2Pi() return AltAz(az, alt) } - fun altAzToRaDec(altAz: AltAz, lstRad: Double, latRad: Double): RaDec {- val sinDec = sin(altAz.altRad) * sin(latRad) +- cos(altAz.altRad) * cos(latRad) * cos(altAz.azRad)+ fun altAzToRaDec(+ altAz: AltAz,+ lstRad: Double,+ latRad: Double,+ ): RaDec {+ val sinDec =+ sin(altAz.altRad) * sin(latRad) ++ cos(altAz.altRad) * cos(latRad) * cos(altAz.azRad) val dec = asin(sinDec.coerceIn(-1.0, 1.0)) // Inverts raDecToAltAz exactly: from sinH = -sinAz*cosAlt/cosDec and // cosH = (sinAlt*cosLat - cosAlt*cosAz*sinLat)/cosDec, multiply both@@ -60,44 +78,62 @@ object CoordinateTransforms { // ~0 at the geographic poles, where atan2 then returns a rounding- // noise hour angle; this form keeps the pole limit (HA = Az - 180deg // at the north pole).- val ha = atan2(- -sin(altAz.azRad) * cos(altAz.altRad),- sin(altAz.altRad) * cos(latRad) - cos(altAz.altRad) * cos(altAz.azRad) * sin(latRad),- )+ val ha =+ atan2(+ -sin(altAz.azRad) * cos(altAz.altRad),+ sin(altAz.altRad) * cos(latRad) - cos(altAz.altRad) * cos(altAz.azRad) * sin(latRad),+ ) val ra = (lstRad - ha).normalize2Pi() return RaDec(ra, dec) } - fun raDecToEcliptic(raDec: RaDec, obliquityRad: Double): Ecliptic {- val sinElat = sin(raDec.decRad) * cos(obliquityRad) -- cos(raDec.decRad) * sin(obliquityRad) * sin(raDec.raRad)+ fun raDecToEcliptic(+ raDec: RaDec,+ obliquityRad: Double,+ ): Ecliptic {+ val sinElat =+ sin(raDec.decRad) * cos(obliquityRad) -+ cos(raDec.decRad) * sin(obliquityRad) * sin(raDec.raRad) val eLat = asin(sinElat.coerceIn(-1.0, 1.0))- val eLon = atan2(- sin(raDec.raRad) * cos(obliquityRad) + tan(raDec.decRad) * sin(obliquityRad),- cos(raDec.raRad),- ).normalize2Pi()+ val eLon =+ atan2(+ sin(raDec.raRad) * cos(obliquityRad) + tan(raDec.decRad) * sin(obliquityRad),+ cos(raDec.raRad),+ ).normalize2Pi() return Ecliptic(eLon, eLat) } - fun eclipticToRaDec(ecliptic: Ecliptic, obliquityRad: Double): RaDec {- val sinDec = sin(ecliptic.latRad) * cos(obliquityRad) +- cos(ecliptic.latRad) * sin(obliquityRad) * sin(ecliptic.lonRad)+ fun eclipticToRaDec(+ ecliptic: Ecliptic,+ obliquityRad: Double,+ ): RaDec {+ val sinDec =+ sin(ecliptic.latRad) * cos(obliquityRad) ++ cos(ecliptic.latRad) * sin(obliquityRad) * sin(ecliptic.lonRad) val dec = asin(sinDec.coerceIn(-1.0, 1.0))- val ra = atan2(- sin(ecliptic.lonRad) * cos(obliquityRad) - tan(ecliptic.latRad) * sin(obliquityRad),- cos(ecliptic.lonRad),- ).normalize2Pi()+ val ra =+ atan2(+ sin(ecliptic.lonRad) * cos(obliquityRad) - tan(ecliptic.latRad) * sin(obliquityRad),+ cos(ecliptic.lonRad),+ ).normalize2Pi() return RaDec(ra, dec) } - fun angularDistanceRad(a: RaDec, b: RaDec): Double {+ fun angularDistanceRad(+ a: RaDec,+ b: RaDec,+ ): Double { val sd = sin(a.decRad) * sin(b.decRad) + cos(a.decRad) * cos(b.decRad) * cos(a.raRad - b.raRad) return acos(sd.coerceIn(-1.0, 1.0)) } // Native batch transform: marshal to an interleaved [ra,dec,...] DoubleArray, // transform in Rust, rebuild the List<AltAz>.- fun batchRaDecToAltAz(radecs: List<RaDec>, lstRad: Double, latRad: Double): List<AltAz> {+ fun batchRaDecToAltAz(+ radecs: List<RaDec>,+ lstRad: Double,+ latRad: Double,+ ): List<AltAz> { if (radecs.isEmpty()) return emptyList() // Same guard projectAll has: where the Rust library did not load // (an ABI the APK does not ship, e.g. x86_64), transform in Kotlin
astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/LunarCalculator.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/LunarCalculator.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/LunarCalculator.ktindex 97cfacc5c5..52a1321922 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/LunarCalculator.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/LunarCalculator.kt@@ -13,53 +13,54 @@ object LunarCalculator { val illumination: Double, val ageDays: Double, val eclipticLonRad: Double,- val eclipticLatRad: Double+ val eclipticLatRad: Double, ) fun calc(jd: Double): MoonResult { val d = jd - TimeEngine.J2000+ fun norm(v: Double): Double = ((v % 360.0) + 360.0) % 360.0- val Lp = norm(218.316 + 13.176396 * d)- val Mm = norm(134.963 + 13.064993 * d)- val Ms = norm(357.529 + 0.98560028 * d)- val D2 = norm(297.850 + 12.190749 * d)- val F2 = norm(93.272 + 13.229350 * d)+ val meanLongitudeDeg = norm(218.316 + 13.176396 * d)+ val moonMeanAnomalyDeg = norm(134.963 + 13.064993 * d)+ val sunMeanAnomalyDeg = norm(357.529 + 0.98560028 * d)+ val meanElongationDeg = norm(297.850 + 12.190749 * d)+ val latitudeArgumentDeg = norm(93.272 + 13.229350 * d) - val LpRad = Lp.toRad()- val MmRad = Mm.toRad()- val MsRad = Ms.toRad()- val D2Rad = D2.toRad()- val F2Rad = F2.toRad()+ val meanLongitudeRad = meanLongitudeDeg.toRad()+ val moonMeanAnomalyRad = moonMeanAnomalyDeg.toRad()+ val sunMeanAnomalyRad = sunMeanAnomalyDeg.toRad()+ val meanElongationRad = meanElongationDeg.toRad()+ val latitudeArgumentRad = latitudeArgumentDeg.toRad() var sigmaL = 0.0- sigmaL += 6288774 * sin(MmRad)- sigmaL += 1274027 * sin(2 * D2Rad - MmRad)- sigmaL += 658314 * sin(2 * D2Rad)- sigmaL += 213618 * sin(2 * MmRad)- sigmaL += -185116 * sin(MsRad)- sigmaL += -114332 * sin(2 * F2Rad)- sigmaL += 58793 * sin(2 * D2Rad - 2 * MmRad)- sigmaL += 57066 * sin(2 * D2Rad - MsRad - MmRad)- sigmaL += 53322 * sin(2 * D2Rad + MmRad)- sigmaL += 45728 * sin(2 * D2Rad - MsRad)- sigmaL += -40923 * sin(MmRad - MsRad)- sigmaL += -34720 * sin(D2Rad)- sigmaL += -30383 * sin(MsRad + MmRad)+ sigmaL += 6288774 * sin(moonMeanAnomalyRad)+ sigmaL += 1274027 * sin(2 * meanElongationRad - moonMeanAnomalyRad)+ sigmaL += 658314 * sin(2 * meanElongationRad)+ sigmaL += 213618 * sin(2 * moonMeanAnomalyRad)+ sigmaL += -185116 * sin(sunMeanAnomalyRad)+ sigmaL += -114332 * sin(2 * latitudeArgumentRad)+ sigmaL += 58793 * sin(2 * meanElongationRad - 2 * moonMeanAnomalyRad)+ sigmaL += 57066 * sin(2 * meanElongationRad - sunMeanAnomalyRad - moonMeanAnomalyRad)+ sigmaL += 53322 * sin(2 * meanElongationRad + moonMeanAnomalyRad)+ sigmaL += 45728 * sin(2 * meanElongationRad - sunMeanAnomalyRad)+ sigmaL += -40923 * sin(moonMeanAnomalyRad - sunMeanAnomalyRad)+ sigmaL += -34720 * sin(meanElongationRad)+ sigmaL += -30383 * sin(sunMeanAnomalyRad + moonMeanAnomalyRad) var sigmaB = 0.0- sigmaB += 5128122 * sin(F2Rad)- sigmaB += 280602 * sin(MmRad + F2Rad)- sigmaB += 277693 * sin(MmRad - F2Rad)- sigmaB += 173237 * sin(2 * D2Rad - F2Rad)- sigmaB += 55413 * sin(2 * D2Rad - MmRad + F2Rad)+ sigmaB += 5128122 * sin(latitudeArgumentRad)+ sigmaB += 280602 * sin(moonMeanAnomalyRad + latitudeArgumentRad)+ sigmaB += 277693 * sin(moonMeanAnomalyRad - latitudeArgumentRad)+ sigmaB += 173237 * sin(2 * meanElongationRad - latitudeArgumentRad)+ sigmaB += 55413 * sin(2 * meanElongationRad - moonMeanAnomalyRad + latitudeArgumentRad) var sigmaR = 0.0- sigmaR += -20905355 * cos(MmRad)- sigmaR += -3699111 * cos(2 * D2Rad - MmRad)- sigmaR += -2955968 * cos(2 * D2Rad)- sigmaR += -569925 * cos(2 * MmRad)+ sigmaR += -20905355 * cos(moonMeanAnomalyRad)+ sigmaR += -3699111 * cos(2 * meanElongationRad - moonMeanAnomalyRad)+ sigmaR += -2955968 * cos(2 * meanElongationRad)+ sigmaR += -569925 * cos(2 * moonMeanAnomalyRad) - val lonDeg = Lp + sigmaL / 1000000.0+ val lonDeg = meanLongitudeDeg + sigmaL / 1000000.0 val latDeg = sigmaB / 1000000.0 // sigmaR coefficients are metres (the largest term, -20905355, is // -20905.355 km expressed in metres), so they add to the metre@@ -74,20 +75,21 @@ object LunarCalculator { val raDec = CoordinateTransforms.eclipticToRaDec(Ecliptic(lonRad, latRad), obliq) val sun = SolarCalculator.calc(jd) val elongation = (lonRad - sun.eclipticLonRad).normalizePi()- val phase = (((D2 / 360.0) % 1.0) + 1.0) % 1.0+ val phase = (((meanElongationDeg / 360.0) % 1.0) + 1.0) % 1.0 val illumination = (1 - cos(elongation)) / 2.0 val age = phase * 29.53058867- return MoonResult(raDec, distMeters / 1000.0, phase, illumination.coerceIn(0.0,1.0), age, lonRad, latRad)+ return MoonResult(raDec, distMeters / 1000.0, phase, illumination.coerceIn(0.0, 1.0), age, lonRad, latRad) } - fun phaseName(phase: Double): String = when {- phase < 0.03 || phase > 0.97 -> "New Moon"- phase < 0.22 -> "Waxing Crescent"- phase < 0.28 -> "First Quarter"- phase < 0.47 -> "Waxing Gibbous"- phase < 0.53 -> "Full Moon"- phase < 0.72 -> "Waning Gibbous"- phase < 0.78 -> "Last Quarter"- else -> "Waning Crescent"- }+ fun phaseName(phase: Double): String =+ when {+ phase < 0.03 || phase > 0.97 -> "New Moon"+ phase < 0.22 -> "Waxing Crescent"+ phase < 0.28 -> "First Quarter"+ phase < 0.47 -> "Waxing Gibbous"+ phase < 0.53 -> "Full Moon"+ phase < 0.72 -> "Waning Gibbous"+ phase < 0.78 -> "Last Quarter"+ else -> "Waning Crescent"+ } }
astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/PlanetaryCalculator.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/PlanetaryCalculator.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/PlanetaryCalculator.ktindex 2e1004d6e9..5e55493de3 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/PlanetaryCalculator.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/PlanetaryCalculator.kt@@ -18,14 +18,18 @@ object PlanetaryCalculator { val raDec: RaDec, val distanceAu: Double, val heliocentricDistAu: Double,- val magnitude: Double?+ val magnitude: Double?, ) - fun solveKepler(meanAnomalyRad: Double, e: Double): Double {+ fun solveKepler(+ meanAnomalyRad: Double,+ e: Double,+ ): Double { var eccentricAnomaly = meanAnomalyRad repeat(20) {- val delta = (- eccentricAnomaly - e * sin(eccentricAnomaly) - meanAnomalyRad+ val delta =+ (+ eccentricAnomaly - e * sin(eccentricAnomaly) - meanAnomalyRad ) / (1 - e * cos(eccentricAnomaly)) eccentricAnomaly -= delta if (abs(delta) < 1e-12) return@repeat@@ -33,24 +37,30 @@ object PlanetaryCalculator { return eccentricAnomaly } - fun heliocentricEcliptic(elements: OrbitalElements, jd: Double): Triple<Double, Double, Double> {+ fun heliocentricEcliptic(+ elements: OrbitalElements,+ jd: Double,+ ): Triple<Double, Double, Double> { val d = TimeEngine.daysSinceJ2000(jd)- var Mdeg = elements.m0Deg + elements.nDegPerDay * d- Mdeg %= 360.0- if (Mdeg < 0) Mdeg += 360.0- val Mrad = Mdeg.toRad()- val Erad = solveKepler(Mrad, elements.e)- val xv = elements.a * (cos(Erad) - elements.e)- val yv = elements.a * sqrt(1 - elements.e * elements.e) * sin(Erad)+ var meanAnomalyDeg = elements.m0Deg + elements.nDegPerDay * d+ meanAnomalyDeg %= 360.0+ if (meanAnomalyDeg < 0) meanAnomalyDeg += 360.0+ val meanAnomalyRad = meanAnomalyDeg.toRad()+ val eccentricAnomalyRad = solveKepler(meanAnomalyRad, elements.e)+ val xv = elements.a * (cos(eccentricAnomalyRad) - elements.e)+ val yv = elements.a * sqrt(1 - elements.e * elements.e) * sin(eccentricAnomalyRad) val v = atan2(yv, xv) val r = sqrt(xv * xv + yv * yv) val wRad = elements.wDeg.toRad() val omegaRad = elements.omegaDeg.toRad() val iRad = elements.iDeg.toRad() val u = v + wRad- val cosU = cos(u); val sinU = sin(u)- val cosO = cos(omegaRad); val sinO = sin(omegaRad)- val cosI = cos(iRad); val sinI = sin(iRad)+ val cosU = cos(u)+ val sinU = sin(u)+ val cosO = cos(omegaRad)+ val sinO = sin(omegaRad)+ val cosI = cos(iRad)+ val sinI = sin(iRad) val x = r * (cosO * cosU - sinO * sinU * cosI) val y = r * (sinO * cosU + cosO * sinU * cosI) val z = r * (sinU * sinI)@@ -63,26 +73,35 @@ object PlanetaryCalculator { z: Double, obliqRad: Double, ): Triple<Double, Double, Double> {- val cosEps = cos(obliqRad); val sinEps = sin(obliqRad)+ val cosEps = cos(obliqRad)+ val sinEps = sin(obliqRad) return Triple(x, y * cosEps - z * sinEps, y * sinEps + z * cosEps) } - fun geocentricRaDec(planetElements: OrbitalElements, earthElements: OrbitalElements, jd: Double): PlanetResult {+ fun geocentricRaDec(+ planetElements: OrbitalElements,+ earthElements: OrbitalElements,+ jd: Double,+ ): PlanetResult { val obliq = TimeEngine.meanObliquityRad(jd) var (xp, yp, zp) = heliocentricEcliptic(planetElements, jd) var (xe, ye, ze) = heliocentricEcliptic(earthElements, jd)- var dx = xp - xe; var dy = yp - ye; var dz = zp - ze- var dist = sqrt(dx*dx + dy*dy + dz*dz)+ var dx = xp - xe+ var dy = yp - ye+ var dz = zp - ze+ var dist = sqrt(dx * dx + dy * dy + dz * dz) val lightDaysPerAu = 0.0057755183 val jdCorr = jd - dist * lightDaysPerAu val (xp2, yp2, zp2) = heliocentricEcliptic(planetElements, jdCorr) val (xe2, ye2, ze2) = heliocentricEcliptic(earthElements, jdCorr)- dx = xp2 - xe2; dy = yp2 - ye2; dz = zp2 - ze2- dist = sqrt(dx*dx + dy*dy + dz*dz)- val rHelio = sqrt(xp2*xp2 + yp2*yp2 + zp2*zp2)+ dx = xp2 - xe2+ dy = yp2 - ye2+ dz = zp2 - ze2+ dist = sqrt(dx * dx + dy * dy + dz * dz)+ val rHelio = sqrt(xp2 * xp2 + yp2 * yp2 + zp2 * zp2) val (xeq, yeq, zeq) = eclipticToEquatorial(dx, dy, dz, obliq) val ra = atan2(yeq, xeq).normalize2Pi()- val dec = atan2(zeq, sqrt(xeq*xeq + yeq*yeq))+ val dec = atan2(zeq, sqrt(xeq * xeq + yeq * yeq)) val mag = estimateMagnitude(planetElements, rHelio, dist, xp2, yp2, zp2, xe2, ye2, ze2) return PlanetResult(planetElements.id, planetElements.name, RaDec(ra, dec), dist, rHelio, mag) }@@ -99,13 +118,14 @@ object PlanetaryCalculator { ze: Double, ): Double? { val base = elem.magBase ?: return null- val sunPlanet = sqrt(xp*xp + yp*yp + zp*zp)+ val sunPlanet = sqrt(xp * xp + yp * yp + zp * zp) val earthPlanet = delta- val sunEarth = sqrt(xe*xe + ye*ye + ze*ze)+ val sunEarth = sqrt(xe * xe + ye * ye + ze * ze) if (sunPlanet == 0.0 || earthPlanet == 0.0) return base- val cosPhase = (- (sunPlanet * sunPlanet + earthPlanet * earthPlanet - sunEarth * sunEarth) /- (2 * sunPlanet * earthPlanet)+ val cosPhase =+ (+ (sunPlanet * sunPlanet + earthPlanet * earthPlanet - sunEarth * sunEarth) /+ (2 * sunPlanet * earthPlanet) ).coerceIn(-1.0, 1.0) val phaseDeg = acos(cosPhase).toDeg() return base + 5.0 * log10(r * delta) + 0.01 * phaseDeg@@ -117,7 +137,8 @@ object PlanetaryCalculator { jd: Double, ): List<PlanetResult> { if (earth == null) return emptyList()- return planets.filter { it.id != "EARTH" && it.id != "SUN" && it.id != "MOON_SKIP" }+ return planets+ .filter { it.id != "EARTH" && it.id != "SUN" && it.id != "MOON_SKIP" } .map { geocentricRaDec(it, earth, jd) } } }
astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/RiseSetCalculator.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/RiseSetCalculator.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/RiseSetCalculator.ktindex 3927be2653..69aa56c96e 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/RiseSetCalculator.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/RiseSetCalculator.kt@@ -13,7 +13,7 @@ object RiseSetCalculator { val transitJd: Double?, val setJd: Double?, val isCircumpolar: Boolean = false,- val isNeverUp: Boolean = false+ val isNeverUp: Boolean = false, ) const val H0_SUN_DEG = -0.833@@ -29,6 +29,7 @@ object RiseSetCalculator { val h0Rad = h0Deg.toRad() val jdNoon = jd0 + 0.5 val raDecNoon = getRaDec(jdNoon)+ fun cosH0(decRad: Double): Double { val sinH0 = sin(h0Rad) return (sinH0 - sin(latRad) * sin(decRad)) / (cos(latRad) * cos(decRad))@@ -39,29 +40,42 @@ object RiseSetCalculator { val transit = findTransit(jd0, lonRad, getRaDec) return RiseTransitSet(null, transit, null, true, false) }- val H0 = acos(cosH.coerceIn(-1.0, 1.0))+ val hourAngleRad = acos(cosH.coerceIn(-1.0, 1.0)) val siderealDay = 1.00273790935 val transitJd = findTransit(jd0, lonRad, getRaDec) ?: jdNoon+ fun altAt(jd: Double): Double { val lst = TimeEngine.lstRad(jd, lonRad) val rd = getRaDec(jd) return CoordinateTransforms.raDecToAltAz(rd, lst, latRad).altRad }- val riseGuess = transitJd - H0.toDeg() / 360.0 / siderealDay- val setGuess = transitJd + H0.toDeg() / 360.0 / siderealDay+ val riseGuess = transitJd - hourAngleRad.toDeg() / 360.0 / siderealDay+ val setGuess = transitJd + hourAngleRad.toDeg() / 360.0 / siderealDay val riseJd = findCrossing(riseGuess - 0.1, riseGuess + 0.1, h0Rad, ::altAt, true) val setJd = findCrossing(setGuess - 0.1, setGuess + 0.1, h0Rad, ::altAt, false) return RiseTransitSet(riseJd, transitJd, setJd) } - private fun findTransit(jd0: Double, lonRad: Double, getRaDec: (Double) -> RaDec): Double? {- var bestT = 0.5; var bestHa = Double.MAX_VALUE+ private fun findTransit(+ jd0: Double,+ lonRad: Double,+ getRaDec: (Double) -> RaDec,+ ): Double? {+ var bestT = 0.5+ var bestHa = Double.MAX_VALUE for (i in 0..24) {- val t = i / 24.0; val jd = jd0 + t- val lst = TimeEngine.lstRad(jd, lonRad); val ra = getRaDec(jd).raRad; val ha = (lst - ra).normalizePi()- if (abs(ha) < abs(bestHa)) { bestHa = ha; bestT = t }+ val t = i / 24.0+ val jd = jd0 + t+ val lst = TimeEngine.lstRad(jd, lonRad)+ val ra = getRaDec(jd).raRad+ val ha = (lst - ra).normalizePi()+ if (abs(ha) < abs(bestHa)) {+ bestHa = ha+ bestT = t+ } }- var lo = (bestT - 0.1).coerceAtLeast(0.0); var hi = (bestT + 0.1).coerceAtMost(1.0)+ var lo = (bestT - 0.1).coerceAtLeast(0.0)+ var hi = (bestT + 0.1).coerceAtMost(1.0) repeat(20) { val mid = (lo + hi) / 2 val jdMid = jd0 + mid@@ -80,34 +94,65 @@ object RiseSetCalculator { altAt: (Double) -> Double, rising: Boolean, ): Double? {- var lo = jdLo; var hi = jdHi- var fLo = altAt(lo) - h0Rad; var fHi = altAt(hi) - h0Rad+ var lo = jdLo+ var hi = jdHi+ var fLo = altAt(lo) - h0Rad+ var fHi = altAt(hi) - h0Rad if (fLo * fHi > 0) {- val steps = 20; var prevJd = lo; var prevF = fLo+ val steps = 20+ var prevJd = lo+ var prevF = fLo for (k in 1..steps) {- val jd = lo + (hi - lo) * k / steps; val f = altAt(jd) - h0Rad- if (prevF * f <= 0) { lo = prevJd; hi = jd; fLo = prevF; fHi = f; break }- prevJd = jd; prevF = f+ val jd = lo + (hi - lo) * k / steps+ val f = altAt(jd) - h0Rad+ if (prevF * f <= 0) {+ lo = prevJd+ hi = jd+ fLo = prevF+ fHi = f+ break+ }+ prevJd = jd+ prevF = f } if (fLo * fHi > 0) return null } repeat(30) {- val mid = (lo + hi) / 2; val fMid = altAt(mid) - h0Rad- if (fLo * fMid <= 0) { hi = mid; fHi = fMid } else { lo = mid; fLo = fMid }+ val mid = (lo + hi) / 2+ val fMid = altAt(mid) - h0Rad+ if (fLo * fMid <= 0) {+ hi = mid+ fHi = fMid+ } else {+ lo = mid+ fLo = fMid+ } } val result = (lo + hi) / 2- val eps = 0.0001; val before = altAt(result - eps); val after = altAt(result + eps)+ val eps = 0.0001+ val before = altAt(result - eps)+ val after = altAt(result + eps) val isRising = after > before if (isRising != rising) return null return result } - fun sunRiseSet(jd0: Double, latRad: Double, lonRad: Double): RiseTransitSet =- calc(jd0, latRad, lonRad, { jd -> SolarCalculator.calc(jd).raDec }, H0_SUN_DEG)+ fun sunRiseSet(+ jd0: Double,+ latRad: Double,+ lonRad: Double,+ ): RiseTransitSet = calc(jd0, latRad, lonRad, { jd -> SolarCalculator.calc(jd).raDec }, H0_SUN_DEG) - fun starRiseSet(jd0: Double, latRad: Double, lonRad: Double, raDec: RaDec): RiseTransitSet =- calc(jd0, latRad, lonRad, { raDec }, H0_STAR_DEG)+ fun starRiseSet(+ jd0: Double,+ latRad: Double,+ lonRad: Double,+ raDec: RaDec,+ ): RiseTransitSet = calc(jd0, latRad, lonRad, { raDec }, H0_STAR_DEG) - fun moonRiseSet(jd0: Double, latRad: Double, lonRad: Double): RiseTransitSet =- calc(jd0, latRad, lonRad, { jd -> LunarCalculator.calc(jd).raDec }, H0_STAR_DEG)+ fun moonRiseSet(+ jd0: Double,+ latRad: Double,+ lonRad: Double,+ ): RiseTransitSet = calc(jd0, latRad, lonRad, { jd -> LunarCalculator.calc(jd).raDec }, H0_STAR_DEG) }
astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/SolarCalculator.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/SolarCalculator.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/SolarCalculator.ktindex 5f500565bf..af9d4b3994 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/SolarCalculator.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/SolarCalculator.kt@@ -19,12 +19,12 @@ object SolarCalculator { fun calc(jd: Double): SolarResult { val n = jd - TimeEngine.J2000- var L = (280.460 + 0.9856474 * n) % 360.0- if (L < 0) L += 360.0- var g = (357.528 + 0.9856003 * n) % 360.0- if (g < 0) g += 360.0- val gRad = g.toRad()- val lambdaDeg = L + 1.915 * sin(gRad) + 0.020 * sin(2 * gRad)+ var meanLongitudeDeg = (280.460 + 0.9856474 * n) % 360.0+ if (meanLongitudeDeg < 0) meanLongitudeDeg += 360.0+ var meanAnomalyDeg = (357.528 + 0.9856003 * n) % 360.0+ if (meanAnomalyDeg < 0) meanAnomalyDeg += 360.0+ val gRad = meanAnomalyDeg.toRad()+ val lambdaDeg = meanLongitudeDeg + 1.915 * sin(gRad) + 0.020 * sin(2 * gRad) val lambdaRad = lambdaDeg.toRad().normalize2Pi() val epsRad = TimeEngine.meanObliquityRad(jd) val sinDec = sin(epsRad) * sin(lambdaRad)@@ -32,18 +32,20 @@ object SolarCalculator { val y = cos(epsRad) * sin(lambdaRad) val x = cos(lambdaRad) var ra = atan2(y, x).normalize2Pi()- val R = 1.00014 - 0.01671 * cos(gRad) - 0.00014 * cos(2 * gRad)- var eot = (L.toRad() - ra).normalizePi()+ val distanceAu = 1.00014 - 0.01671 * cos(gRad) - 0.00014 * cos(2 * gRad)+ var eot = (meanLongitudeDeg.toRad() - ra).normalizePi() var eotMin = eot * 720.0 / PI if (eotMin < -20 && eotMin > -720) { // keep near zero crossing } if (eotMin > 720) eotMin -= 1440.0 if (eotMin < -720) eotMin += 1440.0- return SolarResult(RaDec(ra, dec), R, dec, lambdaRad, eotMin)+ return SolarResult(RaDec(ra, dec), distanceAu, dec, lambdaRad, eotMin) } - fun solarAltAz(jd: Double, lstRad: Double, latRad: Double): AltAz {- return CoordinateTransforms.raDecToAltAz(calc(jd).raDec, lstRad, latRad)- }+ fun solarAltAz(+ jd: Double,+ lstRad: Double,+ latRad: Double,+ ): AltAz = CoordinateTransforms.raDecToAltAz(calc(jd).raDec, lstRad, latRad) }
astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/TimeEngine.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/TimeEngine.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/TimeEngine.ktindex 6afb922fc7..6b7e28758b 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/TimeEngine.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/TimeEngine.kt@@ -9,8 +9,7 @@ object TimeEngine { const val J2000 = 2451545.0 @OptIn(ExperimentalTime::class)- fun instantToJulianDate(instant: Instant): Double =- 2440587.5 + instant.toEpochMilliseconds() / 86400000.0+ fun instantToJulianDate(instant: Instant): Double = 2440587.5 + instant.toEpochMilliseconds() / 86400000.0 @OptIn(ExperimentalTime::class) fun julianDateToInstant(jd: Double): Instant {@@ -19,18 +18,23 @@ object TimeEngine { } fun centuriesSinceJ2000(jd: Double): Double = (jd - J2000) / 36525.0+ fun daysSinceJ2000(jd: Double): Double = jd - J2000 fun gmstRad(jd: Double): Double {- val T = centuriesSinceJ2000(jd)- val gmstDeg = 280.46061837 + 360.98564736629 * (jd - J2000) +- 0.000387933 * T * T - T * T * T / 38710000.0- var g = gmstDeg % 360.0- if (g < 0) g += 360.0- return g * PI / 180.0+ val centuries = centuriesSinceJ2000(jd)+ val gmstDeg =+ 280.46061837 + 360.98564736629 * (jd - J2000) ++ 0.000387933 * centuries * centuries - centuries * centuries * centuries / 38710000.0+ var normalizedGmstDeg = gmstDeg % 360.0+ if (normalizedGmstDeg < 0) normalizedGmstDeg += 360.0+ return normalizedGmstDeg * PI / 180.0 } - fun lstRad(jd: Double, lonRad: Double): Double {+ fun lstRad(+ jd: Double,+ lonRad: Double,+ ): Double { var lst = gmstRad(jd) + lonRad lst %= (2.0 * PI) if (lst < 0) lst += 2.0 * PI@@ -38,9 +42,11 @@ object TimeEngine { } fun meanObliquityRad(jd: Double): Double {- val T = centuriesSinceJ2000(jd)- val eps0Deg = 23.0 + 26.0 / 60.0 + 21.448 / 3600.0 -- (46.8150 * T + 0.00059 * T * T - 0.001813 * T * T * T) / 3600.0+ val centuries = centuriesSinceJ2000(jd)+ val eps0Deg =+ 23.0 + 26.0 / 60.0 + 21.448 / 3600.0 -+ (46.8150 * centuries + 0.00059 * centuries * centuries - 0.001813 * centuries * centuries * centuries) /+ 3600.0 return eps0Deg * PI / 180.0 } @@ -48,14 +54,21 @@ object TimeEngine { } fun Double.toRad() = this * Math.PI / 180.0+ fun Double.toDeg() = this * 180.0 / Math.PI+ fun Double.normalize2Pi(): Double { var v = this % (2.0 * Math.PI)- if (v < 0) { v += 2.0 * Math.PI }+ if (v < 0) {+ v += 2.0 * Math.PI+ } return v }+ fun Double.normalizePi(): Double { var v = (this + Math.PI) % (2.0 * Math.PI)- if (v < 0) { v += 2.0 * Math.PI }+ if (v < 0) {+ v += 2.0 * Math.PI+ } return v - Math.PI }
astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/SkyProjection.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/SkyProjection.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/SkyProjection.ktindex d0b427c20a..1bc2d34633 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/SkyProjection.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/SkyProjection.kt@@ -6,6 +6,8 @@ import com.vayunmathur.astronomy.domain.engine.AltAz /** Maps horizontal coordinates to screen points and back for one sky view. */ interface SkyProjection { fun project(altAz: AltAz): Offset?+ fun unproject(screen: Offset): AltAz?+ fun isVisible(altAz: AltAz): Boolean }
astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/StereographicProjection.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/StereographicProjection.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/StereographicProjection.ktindex 1cd0e0a6e3..3a5cb4e1fe 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/StereographicProjection.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/StereographicProjection.kt@@ -19,7 +19,10 @@ import kotlin.math.tan * (`Float.NaN` from native == culled == null), positionally aligned with the * input. Intended for the largest list (stars) on the render hot path. */-fun projectAll(viewState: ViewState, altAzList: List<AltAz>): List<Offset?> {+fun projectAll(+ viewState: ViewState,+ altAzList: List<AltAz>,+): List<Offset?> { if (altAzList.isEmpty()) return emptyList() if (!AstronomyNative.available) { // Layoutlib (Compose previews, and so the store-listing screenshots) has no .so.@@ -32,42 +35,49 @@ fun projectAll(viewState: ViewState, altAzList: List<AltAz>): List<Offset?> { input[2 * i] = altAzList[i].azRad input[2 * i + 1] = altAzList[i].altRad }- val out = AstronomyNative.batchProject(- input,- viewState.centerAzRad,- viewState.centerAltRad,- viewState.fovDegDouble,- viewState.screenW.toDouble(),- viewState.screenH.toDouble(),- viewState.rotationRad,- )+ val out =+ AstronomyNative.batchProject(+ input,+ viewState.centerAzRad,+ viewState.centerAltRad,+ viewState.fovDegDouble,+ viewState.screenW.toDouble(),+ viewState.screenH.toDouble(),+ viewState.rotationRad,+ ) return List(altAzList.size) { i ->- val x = out[2 * i]; val y = out[2 * i + 1]+ val x = out[2 * i]+ val y = out[2 * i + 1] if (x.isNaN() || y.isNaN()) null else Offset(x, y) } } /** Stereographic projection of the sky onto the screen for a single view state. */-class StereographicProjection(private val viewState: ViewState) : SkyProjection {+class StereographicProjection(+ private val viewState: ViewState,+) : SkyProjection { private val sinCenterAlt = sin(viewState.centerAltRad) private val cosCenterAlt = cos(viewState.centerAltRad) private val centerAz = viewState.centerAzRad private val fovRad = viewState.fovRad.coerceIn(Math.toRadians(1.0), Math.toRadians(150.0))- private val scale: Double = run {- val rhoEdge = 2.0 * tan(fovRad / 2.0 / 2.0)- if (rhoEdge < 1e-9) 1.0 else (viewState.screenW * 0.5) / rhoEdge- }+ private val scale: Double =+ run {+ val rhoEdge = 2.0 * tan(fovRad / 2.0 / 2.0)+ if (rhoEdge < 1e-9) 1.0 else (viewState.screenW * 0.5) / rhoEdge+ }+ // Cull to the disk that circumscribes the whole screen rectangle so the sky // fills the entire viewport (no circular cutout / vignette). Since // rho(theta) = 2*tan(theta/2)*scale, invert at the screen-corner radius to // get the limiting angular distance that still reaches the corners.- private val halfFov = run {- val w = viewState.screenW.toDouble()- val h = viewState.screenH.toDouble()- val cornerRho = 0.5 * sqrt(w * w + h * h)- val thetaCorner = 2.0 * atan((cornerRho / scale) / 2.0)- (thetaCorner + Math.toRadians(2.0)).coerceIn(Math.toRadians(1.0), Math.toRadians(179.0))- }+ private val halfFov =+ run {+ val w = viewState.screenW.toDouble()+ val h = viewState.screenH.toDouble()+ val cornerRho = 0.5 * sqrt(w * w + h * h)+ val thetaCorner = 2.0 * atan((cornerRho / scale) / 2.0)+ (thetaCorner + Math.toRadians(2.0)).coerceIn(Math.toRadians(1.0), Math.toRadians(179.0))+ } // Full sphere: always include below-horizon for grid + user request to keep below-horizon objects visible override fun isVisible(altAz: AltAz): Boolean {@@ -90,42 +100,61 @@ class StereographicProjection(private val viewState: ViewState) : SkyProjection return projectCore(altAz, theta) } - private fun projectCore(altAz: AltAz, theta: Double): Offset {+ private fun projectCore(+ altAz: AltAz,+ theta: Double,+ ): Offset { if (theta < 1e-9) return Offset(viewState.screenW / 2, viewState.screenH / 2) val rho = 2.0 * tan(theta / 2.0) * scale- val sinAlt = sin(altAz.altRad); val cosAlt = cos(altAz.altRad)- val dAz = (altAz.azRad - centerAz).let { ((it + PI) % (2*PI)) - PI }- val sinDaz = sin(dAz); val cosDaz = cos(dAz)+ val sinAlt = sin(altAz.altRad)+ val cosAlt = cos(altAz.altRad)+ val dAz = (altAz.azRad - centerAz).let { ((it + PI) % (2 * PI)) - PI }+ val sinDaz = sin(dAz)+ val cosDaz = cos(dAz) val phi = atan2(sinDaz * cosAlt, cosCenterAlt * sinAlt - sinCenterAlt * cosAlt * cosDaz) // Forward-facing window view: +x = increasing azimuth (right), higher altitude // than center (phi≈0) maps to -y (up on screen). This is the exact inverse of // `unproject`'s atan2(x, -y).- val x = rho * sin(phi); val y = -rho * cos(phi)- val cosR = cos(viewState.rotationRad); val sinR = sin(viewState.rotationRad)- val xr = x * cosR - y * sinR; val yr = x * sinR + y * cosR+ val x = rho * sin(phi)+ val y = -rho * cos(phi)+ val cosR = cos(viewState.rotationRad)+ val sinR = sin(viewState.rotationRad)+ val xr = x * cosR - y * sinR+ val yr = x * sinR + y * cosR return Offset((viewState.screenW / 2 + xr).toFloat(), (viewState.screenH / 2 + yr).toFloat()) } override fun unproject(screen: Offset): AltAz? {- val cx = viewState.screenW / 2; val cy = viewState.screenH / 2- var x = (screen.x - cx).toDouble(); var y = (screen.y - cy).toDouble()- val cosR = cos(-viewState.rotationRad); val sinR = sin(-viewState.rotationRad)- val xr = x * cosR - y * sinR; val yr = x * sinR + y * cosR; x = xr; y = yr- val rho = sqrt(x*x + y*y); if (rho < 1e-12) return AltAz(centerAz, viewState.centerAltRad)- val rhoNorm = rho / scale; val theta = 2 * atan(rhoNorm / 2.0)+ val cx = viewState.screenW / 2+ val cy = viewState.screenH / 2+ var x = (screen.x - cx).toDouble()+ var y = (screen.y - cy).toDouble()+ val cosR = cos(-viewState.rotationRad)+ val sinR = sin(-viewState.rotationRad)+ val xr = x * cosR - y * sinR+ val yr = x * sinR + y * cosR+ x = xr+ y = yr+ val rho = sqrt(x * x + y * y)+ if (rho < 1e-12) return AltAz(centerAz, viewState.centerAltRad)+ val rhoNorm = rho / scale+ val theta = 2 * atan(rhoNorm / 2.0) val phi = atan2(x, -y) val sinAlt = sinCenterAlt * cos(theta) + cosCenterAlt * sin(theta) * cos(phi) val alt = asin(sinAlt.coerceIn(-1.0, 1.0)) val sinDaz = sin(theta) * sin(phi) val cosDaz = cosCenterAlt * cos(theta) - sinCenterAlt * sin(theta) * cos(phi) val dAz = atan2(sinDaz, cosDaz)- var az = centerAz + dAz; az %= (2*PI); if (az < 0) az += 2*PI+ var az = centerAz + dAz+ az %= (2 * PI)+ if (az < 0) az += 2 * PI return AltAz(az, alt) } private fun angularDist(altAz: AltAz): Double {- val sinAlt = sin(altAz.altRad); val cosAlt = cos(altAz.altRad)- val dAz = (altAz.azRad - centerAz).let { ((it + 3*PI) % (2*PI)) - PI }+ val sinAlt = sin(altAz.altRad)+ val cosAlt = cos(altAz.altRad)+ val dAz = (altAz.azRad - centerAz).let { ((it + 3 * PI) % (2 * PI)) - PI } val cosTheta = sinCenterAlt * sinAlt + cosCenterAlt * cosAlt * cos(dAz) return acos(cosTheta.coerceIn(-1.0, 1.0)) }
astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/ViewState.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/ViewState.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/ViewState.ktindex 99f0a9a9b5..18984db51f 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/ViewState.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/ViewState.kt@@ -7,7 +7,7 @@ data class ViewState( val fovDeg: Float, // Float to align with slider/gesture Float domain val screenW: Float, val screenH: Float,- val rotationRad: Double = 0.0+ val rotationRad: Double = 0.0, ) { val fovRad get() = Math.toRadians(fovDeg.toDouble()) val fovDegDouble get() = fovDeg.toDouble()
astronomy/src/main/java/com/vayunmathur/astronomy/platform/AstronomyPrefs.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/platform/AstronomyPrefs.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/platform/AstronomyPrefs.ktindex f45a548e22..e6ffc1412b 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/platform/AstronomyPrefs.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/platform/AstronomyPrefs.kt@@ -30,9 +30,10 @@ internal class AstronomyPrefs( val latDeg = ds.getDouble("astro_lat") val lonDeg = ds.getDouble("astro_lon") return AstronomyPrefsSnapshot(- constellationMode = runCatching {- ConstellationMode.valueOf(ds.getString("astro_const_mode") ?: "LINES")- }.getOrDefault(ConstellationMode.LINES),+ constellationMode =+ runCatching {+ ConstellationMode.valueOf(ds.getString("astro_const_mode") ?: "LINES")+ }.getOrDefault(ConstellationMode.LINES), showGrid = ds.getBoolean("astro_show_grid", true), showDeepSky = ds.getBoolean("astro_show_deep", true), showPlanets = ds.getBoolean("astro_show_planets", true),@@ -45,15 +46,24 @@ internal class AstronomyPrefs( ) } - fun saveBool(key: String, v: Boolean) {+ fun saveBool(+ key: String,+ v: Boolean,+ ) { scope.launch { ds.setBoolean(key, v) } } - fun saveDouble(key: String, v: Double) {+ fun saveDouble(+ key: String,+ v: Double,+ ) { scope.launch { ds.setDouble(key, v) } } - fun saveString(key: String, v: String) {+ fun saveString(+ key: String,+ v: String,+ ) { scope.launch { ds.setString(key, v) } }
astronomy/src/main/java/com/vayunmathur/astronomy/platform/AstronomyUiContract.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/platform/AstronomyUiContract.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/platform/AstronomyUiContract.ktindex c9ac86cabc..396d7881be 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/platform/AstronomyUiContract.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/platform/AstronomyUiContract.kt@@ -16,9 +16,7 @@ import kotlin.time.Instant * * Every actions method has a no-op default body, so [SkyMapActions.Noop] and friends are * the whole implementation a preview needs.- */--/**+ * * Everything the sky map draws. The projection inputs ([centerAzRad], [centerAltRad], * [rotationRad]) are already resolved from the device sensors by the binder, and * [visibleSky] is already computed for [simTime] — so nothing here reads the clock or the@@ -50,8 +48,13 @@ data class SkyMapUiState( @OptIn(ExperimentalTime::class) interface SkyMapActions { fun setFov(v: Float) {}+ fun selectObject(id: String) {}- fun setTime(instant: Instant, live: Boolean = false) {}++ fun setTime(+ instant: Instant,+ live: Boolean = false,+ ) {} /** Holds the shared no-op [SkyMapActions] instance for previews. */ companion object {@@ -65,6 +68,7 @@ interface SkyMapActions { */ interface SearchActions { fun search(query: String): List<SearchResult> = emptyList()+ fun selectObject(id: String) {} /** Holds the shared no-op [SearchActions] instance for previews. */@@ -93,14 +97,26 @@ data class SettingsUiState( /** Settings callbacks. Parameter names match the ViewModel setters they bind to. */ interface SettingsActions { fun setShowConstellations(mode: ConstellationMode) {}+ fun setShowGrid(v: Boolean) {}+ fun setShowDeepSky(v: Boolean) {}+ fun setShowPlanets(v: Boolean) {}+ fun setShowBelowHorizon(v: Boolean) {}+ fun setNightMode(v: Boolean) {}+ fun setMagLimit(v: Float) {}+ fun setFov(v: Float) {}- fun setManualLocation(latDeg: Double, lonDeg: Double) {}++ fun setManualLocation(+ latDeg: Double,+ lonDeg: Double,+ ) {}+ fun refreshLocation() {} /** Holds the shared no-op [SettingsActions] instance for previews. */
astronomy/src/main/java/com/vayunmathur/astronomy/platform/AstronomyViewModel.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/platform/AstronomyViewModel.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/platform/AstronomyViewModel.ktindex f84fe19caf..6618dabd10 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/platform/AstronomyViewModel.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/platform/AstronomyViewModel.kt@@ -3,9 +3,9 @@ package com.vayunmathur.astronomy.platform import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope+import com.vayunmathur.astronomy.R import com.vayunmathur.astronomy.data.CatalogRepository import com.vayunmathur.astronomy.data.model.PlanetId-import com.vayunmathur.astronomy.R import com.vayunmathur.astronomy.domain.engine.AltAz import com.vayunmathur.astronomy.domain.engine.CoordinateTransforms import com.vayunmathur.astronomy.domain.engine.LunarCalculator@@ -15,8 +15,8 @@ import com.vayunmathur.astronomy.domain.engine.RiseSetCalculator import com.vayunmathur.astronomy.domain.engine.SolarCalculator import com.vayunmathur.astronomy.domain.engine.TimeEngine import com.vayunmathur.astronomy.domain.engine.toRad-import com.vayunmathur.library.sensor.DeviceOrientation import com.vayunmathur.astronomy.platform.sensor.LocationProvider+import com.vayunmathur.library.sensor.DeviceOrientation import com.vayunmathur.library.sensor.OrientationManager import com.vayunmathur.library.util.DataStoreUtils import kotlinx.coroutines.Dispatchers@@ -50,10 +50,17 @@ sealed interface CenterOption { data object DevicePointing : CenterOption /** Center is fixed at an explicit azimuth and altitude. */- data class Manual(val azRad: Double, val altRad: Double) : CenterOption+ data class Manual(+ val azRad: Double,+ val altRad: Double,+ ) : CenterOption /** Center is locked to a selected object at an explicit azimuth and altitude. */- data class TargetObject(val objectId: String, val azRad: Double, val altRad: Double) : CenterOption+ data class TargetObject(+ val objectId: String,+ val azRad: Double,+ val altRad: Double,+ ) : CenterOption } /** A catalog star placed in the sky for the current time and observer. */@@ -72,8 +79,13 @@ data class VisiblePlanet( val mag: Double?, val distanceAu: Double, )+ /** The Sun placed in the sky for the current time and observer. */-data class VisibleSun(val altAz: AltAz, val raDec: RaDec, val distanceAu: Double)+data class VisibleSun(+ val altAz: AltAz,+ val raDec: RaDec,+ val distanceAu: Double,+) /** The Moon placed in the sky, with its phase and illumination. */ data class VisibleMoon(@@ -83,6 +95,7 @@ data class VisibleMoon( val illumination: Double, val ageDays: Double, )+ /** A deep-sky object placed in the sky for the current time and observer. */ data class VisibleDeepSky( val obj: com.vayunmathur.astronomy.data.model.DeepSkyObject,@@ -94,9 +107,18 @@ data class VisibleDeepSky( enum class ConstellationMode { OFF, LINES, LINES_AND_ART } /** One anchor of a constellation figure: the image pixel and where it currently sits on the sky. */-data class VisibleArtAnchor(val srcX: Float, val srcY: Float, val altAz: AltAz)+data class VisibleArtAnchor(+ val srcX: Float,+ val srcY: Float,+ val altAz: AltAz,+)+ /** A constellation figure placed in the sky via its resolved anchors. */-data class VisibleArt(val abbr: String, val image: String, val anchors: List<VisibleArtAnchor>)+data class VisibleArt(+ val abbr: String,+ val image: String,+ val anchors: List<VisibleArtAnchor>,+) /** The fully computed sky at one instant for one observer. */ @OptIn(ExperimentalTime::class)@@ -111,21 +133,39 @@ data class VisibleSky( val observer: ObserverLocation? = null, val time: Instant = Clock.System.now(), val constellations: List<ConstellationLine> = emptyList(),- val art: List<VisibleArt> = emptyList()+ val art: List<VisibleArt> = emptyList(), ) /** A constellation's stick-figure segments as star-id polylines for drawing. */-data class ConstellationLine(val abbr: String, val name: String, val segments: List<List<Int>>)+data class ConstellationLine(+ val abbr: String,+ val name: String,+ val segments: List<List<Int>>,+) /** One sampled point of an object's path: Julian date with horizontal and equatorial positions. */-data class TrajectoryPoint(val jd: Double, val altAz: AltAz, val raDec: RaDec)+data class TrajectoryPoint(+ val jd: Double,+ val altAz: AltAz,+ val raDec: RaDec,+) /** One search hit: stable id, display title and subtitle, and optional equatorial position. */-data class SearchResult(val id: String, val title: String, val subtitle: String, val raDec: Pair<Double, Double>?)+data class SearchResult(+ val id: String,+ val title: String,+ val subtitle: String,+ val raDec: Pair<Double, Double>?,+) /** ViewModel owning the computed sky, observer, time, and settings state for the screens. */ @OptIn(ExperimentalTime::class)-class AstronomyViewModel(app: Application) : AndroidViewModel(app), SkyMapActions, SearchActions, SettingsActions {+class AstronomyViewModel(+ app: Application,+) : AndroidViewModel(app),+ SkyMapActions,+ SearchActions,+ SettingsActions { private companion object { const val MIN_FOV_DEG = 10f const val MAX_FOV_DEG = 120f@@ -139,6 +179,7 @@ class AstronomyViewModel(app: Application) : AndroidViewModel(app), SkyMapAction const val TRAJECTORY_STEP_DAYS = 0.25 / 24.0 const val SEARCH_RESULT_LIMIT = 20 }+ private val context = getApplication<Application>() val catalog = CatalogRepository(context) private var starIndex: Map<Int, com.vayunmathur.astronomy.data.model.Star> = emptyMap()@@ -206,54 +247,48 @@ class AstronomyViewModel(app: Application) : AndroidViewModel(app), SkyMapAction private var tickerJob: Job? = null private var locationJob: Job? = null - private fun computeVisibleSky(time: Instant, obs: ObserverLocation): VisibleSky {+ private fun computeVisibleSky(+ time: Instant,+ obs: ObserverLocation,+ ): VisibleSky { val jd = TimeEngine.instantToJulianDate(time) val lst = TimeEngine.lstRad(jd, obs.lonRad) val magLim = _magLimit.value.toDouble() val visibleStars = catalog.stars.filter { it.mag <= magLim } val starRaDecs = visibleStars.map { RaDec(it.ra, it.dec) } val starAltAz = CoordinateTransforms.batchRaDecToAltAz(starRaDecs, lst, obs.latRad)- val stars = visibleStars.mapIndexed { i, s ->- VisibleStar(s, starAltAz[i], starRaDecs[i])- }-- val constLines = catalog.constellations.map { c ->- ConstellationLine(c.abbr, c.name, c.lines)- }+ val stars =+ visibleStars.mapIndexed { i, s ->+ VisibleStar(s, starAltAz[i], starRaDecs[i])+ } - val art = catalog.constellationArt.mapNotNull { a ->- val resolved = a.anchors.map { an -> an to starIndex[an.hip] }- if (resolved.any { it.second == null }) return@mapNotNull null- VisibleArt(a.abbr, a.image, resolved.map { (an, st) ->- val raDec = RaDec(st!!.ra, st.dec)- val altAz = CoordinateTransforms.raDecToAltAz(raDec, lst, obs.latRad)- VisibleArtAnchor(an.x.toFloat(), an.y.toFloat(), altAz)- })- }+ val constLines =+ catalog.constellations.map { c ->+ ConstellationLine(c.abbr, c.name, c.lines)+ } - val deep = catalog.deepSky.map { obj ->- val rd = RaDec(obj.ra, obj.dec)- val aa = CoordinateTransforms.raDecToAltAz(rd, lst, obs.latRad)- VisibleDeepSky(obj, aa, rd)- }+ val art = visibleArt(catalog, starIndex, lst, obs) - val sun = SolarCalculator.calc(jd).let { solar ->- val aa = CoordinateTransforms.raDecToAltAz(solar.raDec, lst, obs.latRad)- VisibleSun(aa, solar.raDec, solar.distanceAu)- }+ val deep =+ catalog.deepSky.map { obj ->+ val rd = RaDec(obj.ra, obj.dec)+ val aa = CoordinateTransforms.raDecToAltAz(rd, lst, obs.latRad)+ VisibleDeepSky(obj, aa, rd)+ } - val moon = LunarCalculator.calc(jd).let { lunar ->- val aa = CoordinateTransforms.raDecToAltAz(lunar.raDec, lst, obs.latRad)- VisibleMoon(aa, lunar.raDec, lunar.phase, lunar.illumination, lunar.ageDays)- }+ val sun =+ SolarCalculator.calc(jd).let { solar ->+ val aa = CoordinateTransforms.raDecToAltAz(solar.raDec, lst, obs.latRad)+ VisibleSun(aa, solar.raDec, solar.distanceAu)+ } - val earthElem = catalog.earth- val planets = if (earthElem != null) {- PlanetaryCalculator.calcAll(catalog.planets, earthElem, jd).map { pr ->- val aa = CoordinateTransforms.raDecToAltAz(pr.raDec, lst, obs.latRad)- VisiblePlanet(pr.id, pr.name, aa, pr.raDec, pr.magnitude, pr.distanceAu)+ val moon =+ LunarCalculator.calc(jd).let { lunar ->+ val aa = CoordinateTransforms.raDecToAltAz(lunar.raDec, lst, obs.latRad)+ VisibleMoon(aa, lunar.raDec, lunar.phase, lunar.illumination, lunar.ageDays) }- } else emptyList()++ val planets = visiblePlanets(catalog, jd, lst, obs) return VisibleSky( stars = stars,@@ -266,12 +301,12 @@ class AstronomyViewModel(app: Application) : AndroidViewModel(app), SkyMapAction observer = obs, time = time, constellations = constLines,- art = art+ art = art, ) } - fun getRaDecProvider(objectId: String): (Double) -> RaDec {- return when {+ fun getRaDecProvider(objectId: String): (Double) -> RaDec =+ when { objectId == "SUN" -> { jd -> SolarCalculator.calc(jd).raDec } objectId == "MOON" -> { jd -> LunarCalculator.calc(jd).raDec } objectId.startsWith("PLANET_") -> {@@ -307,7 +342,6 @@ class AstronomyViewModel(app: Application) : AndroidViewModel(app), SkyMapAction provider } }- } override fun selectObject(id: String) { _selectedObjectId.value = id@@ -381,22 +415,27 @@ class AstronomyViewModel(app: Application) : AndroidViewModel(app), SkyMapAction _constellationMode.value = mode prefs.saveString("astro_const_mode", mode.name) }+ override fun setShowGrid(v: Boolean) { _showGrid.value = v prefs.saveBool("astro_show_grid", v) }+ override fun setShowDeepSky(v: Boolean) { _showDeepSky.value = v prefs.saveBool("astro_show_deep", v) }+ override fun setShowPlanets(v: Boolean) { _showPlanets.value = v prefs.saveBool("astro_show_planets", v) }+ override fun setNightMode(v: Boolean) { _nightMode.value = v prefs.saveBool("astro_night_mode", v) }+ fun setDevicePointing(v: Boolean) { _devicePointingEnabled.value = v prefs.saveBool("astro_device_pointing", v)@@ -408,6 +447,7 @@ class AstronomyViewModel(app: Application) : AndroidViewModel(app), SkyMapAction _viewCenter.value = CenterOption.Manual(0.0, 45.0.toRad()) } }+ override fun setShowBelowHorizon(v: Boolean) { _showBelowHorizon.value = v prefs.saveBool("astro_show_below", v)@@ -417,11 +457,16 @@ class AstronomyViewModel(app: Application) : AndroidViewModel(app), SkyMapAction _magLimit.value = v prefs.saveDouble("astro_mag_limit", v.toDouble()) }+ override fun setFov(v: Float) { _fovDeg.value = v.coerceIn(MIN_FOV_DEG, MAX_FOV_DEG) prefs.saveDouble("astro_fov", v.toDouble()) }- override fun setManualLocation(latDeg: Double, lonDeg: Double) {++ override fun setManualLocation(+ latDeg: Double,+ lonDeg: Double,+ ) { // The settings form only checked that the text parsed as a // Double, so e.g. latitude 999 was applied and persisted; the // alt-az formulas then silently produced a sky for a latitude@@ -439,45 +484,59 @@ class AstronomyViewModel(app: Application) : AndroidViewModel(app), SkyMapAction private fun startTicker() { tickerJob?.cancel()- tickerJob = viewModelScope.launch {- while (true) {- if (_isLive.value) { _simTime.value = Clock.System.now() }- delay(TICKER_DELAY_MS)+ tickerJob =+ viewModelScope.launch {+ while (true) {+ if (_isLive.value) {+ _simTime.value = Clock.System.now()+ }+ delay(TICKER_DELAY_MS)+ } }- } } override fun refreshLocation() { locationJob?.cancel()- locationJob = viewModelScope.launch {- if (!LocationProvider.hasPermission(context)) return@launch- val loc = withContext(Dispatchers.IO) {- try {- kotlinx.coroutines.withTimeoutOrNull(LOCATION_TIMEOUT_MS) {- LocationProvider.currentLocation(context)+ locationJob =+ viewModelScope.launch {+ if (!LocationProvider.hasPermission(context)) return@launch+ val loc =+ withContext(Dispatchers.IO) {+ try {+ kotlinx.coroutines.withTimeoutOrNull(LOCATION_TIMEOUT_MS) {+ LocationProvider.currentLocation(context)+ }+ } catch (_: Exception) {+ null+ } }- } catch (_: Exception) {- null- }+ loc?.let {+ val latDeg = it.latitude+ val lonDeg = it.longitude+ _observer.value = ObserverLocation(latDeg.toRad(), lonDeg.toRad(), latDeg, lonDeg, it.altitude)+ prefs.saveDouble("astro_lat", latDeg)+ prefs.saveDouble("astro_lon", lonDeg)+ orientationMgr.updateLocation(latDeg, lonDeg, it.altitude.toFloat())+ updateTrajectoryForSelected()+ updateRiseSetForSelected()+ } ?: run { _observer.value?.let { obs -> orientationMgr.updateLocation(obs.latDeg, obs.lonDeg) } } }- loc?.let {- val latDeg = it.latitude; val lonDeg = it.longitude- _observer.value = ObserverLocation(latDeg.toRad(), lonDeg.toRad(), latDeg, lonDeg, it.altitude)- prefs.saveDouble("astro_lat", latDeg); prefs.saveDouble("astro_lon", lonDeg)- orientationMgr.updateLocation(latDeg, lonDeg, it.altitude.toFloat())- updateTrajectoryForSelected()- updateRiseSetForSelected()- } ?: run { _observer.value?.let { obs -> orientationMgr.updateLocation(obs.latDeg, obs.lonDeg) } }- } } - override fun setTime(instant: Instant, live: Boolean) {+ override fun setTime(+ instant: Instant,+ live: Boolean,+ ) { _simTime.value = instant _isLive.value = live updateTrajectoryForSelected() updateRiseSetForSelected() }- fun setLiveNow() { _simTime.value = Clock.System.now(); _isLive.value = true }++ fun setLiveNow() {+ _simTime.value = Clock.System.now()+ _isLive.value = true+ } // No still mode per request: always tracks phone. Pan disabled in device mode (only zoom allowed) @@ -513,7 +572,8 @@ class AstronomyViewModel(app: Application) : AndroidViewModel(app), SkyMapAction if (query.isBlank()) return emptyList() val q = query.lowercase() val results = mutableListOf<SearchResult>()- catalog.stars.filter { matchesQuery(it.name, q) || matchesQuery(it.properName, q) }+ catalog.stars+ .filter { matchesQuery(it.name, q) || matchesQuery(it.properName, q) } .take(SEARCH_RESULT_LIMIT) .forEach { results.add(@@ -532,21 +592,25 @@ class AstronomyViewModel(app: Application) : AndroidViewModel(app), SkyMapAction ), ) }- PlanetId.entries.map { it to context.getString(it.displayNameRes) }+ PlanetId.entries+ .map { it to context.getString(it.displayNameRes) } .filter { (_, name) -> name.lowercase().contains(q) } .forEach { (planet, name) ->- val pid = when (planet) {- PlanetId.SUN, PlanetId.MOON -> planet.name- else -> "PLANET_${planet.name}"- }+ val pid =+ when (planet) {+ PlanetId.SUN, PlanetId.MOON -> planet.name+ else -> "PLANET_${planet.name}"+ } results.add(SearchResult(pid, name, context.getString(R.string.search_result_planet), null)) }- catalog.deepSky.filter { it.id.lowercase().contains(q) || it.name.lowercase().contains(q) }+ catalog.deepSky+ .filter { it.id.lowercase().contains(q) || it.name.lowercase().contains(q) } .take(SEARCH_RESULT_LIMIT) .forEach { results.add(SearchResult(it.id, "${it.id} ${it.name}", it.type, it.ra to it.dec)) }- catalog.constellations.filter { it.abbr.lowercase().contains(q) || it.name.lowercase().contains(q) }+ catalog.constellations+ .filter { it.abbr.lowercase().contains(q) || it.name.lowercase().contains(q) } .forEach { results.add( SearchResult(@@ -560,10 +624,49 @@ class AstronomyViewModel(app: Application) : AndroidViewModel(app), SkyMapAction return results } - private fun matchesQuery(value: String?, q: String): Boolean =- value?.lowercase()?.contains(q) == true+ private fun matchesQuery(+ value: String?,+ q: String,+ ): Boolean = value?.lowercase()?.contains(q) == true - override fun onCleared() { orientationMgr.stop(); tickerJob?.cancel(); locationJob?.cancel() }+ override fun onCleared() {+ orientationMgr.stop()+ tickerJob?.cancel()+ locationJob?.cancel()+ }+}++private fun visibleArt(+ catalog: CatalogRepository,+ starIndex: Map<Int, com.vayunmathur.astronomy.data.model.Star>,+ lst: Double,+ obs: ObserverLocation,+): List<VisibleArt> =+ catalog.constellationArt.mapNotNull { a ->+ val resolved = a.anchors.map { an -> an to starIndex[an.hip] }+ if (resolved.any { it.second == null }) return@mapNotNull null+ VisibleArt(+ a.abbr,+ a.image,+ resolved.map { (an, st) ->+ val raDec = RaDec(st!!.ra, st.dec)+ val altAz = CoordinateTransforms.raDecToAltAz(raDec, lst, obs.latRad)+ VisibleArtAnchor(an.x.toFloat(), an.y.toFloat(), altAz)+ },+ )+ }++private fun visiblePlanets(+ catalog: CatalogRepository,+ jd: Double,+ lst: Double,+ obs: ObserverLocation,+): List<VisiblePlanet> {+ val earthElem = catalog.earth ?: return emptyList()+ return PlanetaryCalculator.calcAll(catalog.planets, earthElem, jd).map { pr ->+ val aa = CoordinateTransforms.raDecToAltAz(pr.raDec, lst, obs.latRad)+ VisiblePlanet(pr.id, pr.name, aa, pr.raDec, pr.magnitude, pr.distanceAu)+ } } /** Resolves the sky-map view center from explicit state (extracted for TooManyFunctions). */@@ -573,8 +676,11 @@ internal fun resolveViewCenter( ): Pair<Double, Double> = when (viewCenter) { is CenterOption.DevicePointing -> {- if (orient != null) Pair(orient.pointingAzRad, orient.pointingAltRad)- else Pair(0.0, 45.0.toRad())+ if (orient != null) {+ Pair(orient.pointingAzRad, orient.pointingAltRad)+ } else {+ Pair(0.0, 45.0.toRad())+ } } is CenterOption.Manual -> Pair(viewCenter.azRad, viewCenter.altRad) is CenterOption.TargetObject -> Pair(viewCenter.azRad, viewCenter.altRad)
astronomy/src/main/java/com/vayunmathur/astronomy/platform/sensor/LocationProvider.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/platform/sensor/LocationProvider.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/platform/sensor/LocationProvider.ktindex b7c8e19ca0..6db45a493f 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/platform/sensor/LocationProvider.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/platform/sensor/LocationProvider.kt@@ -22,34 +22,40 @@ object LocationProvider { suspend fun currentLocation(context: Context): Location? { if (!hasPermission(context)) return null val lm = context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager ?: return null- val providers = listOf(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER)- .filter { lm.isProviderEnabled(it) }+ val providers =+ listOf(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER)+ .filter { lm.isProviderEnabled(it) } if (providers.isEmpty()) return null- providers.mapNotNull { runCatching { lm.getLastKnownLocation(it) }.getOrNull() }+ providers+ .mapNotNull { runCatching { lm.getLastKnownLocation(it) }.getOrNull() } .maxByOrNull { it.time } ?.let { return it } return suspendCancellableCoroutine { cont -> val listeners = mutableListOf<android.location.LocationListener>() var resumed = false providers.forEach { provider ->- val listener = object : android.location.LocationListener {- override fun onLocationChanged(location: Location) {- if (!resumed) {- resumed = true- listeners.forEach { runCatching { lm.removeUpdates(it) } }- cont.resume(location)+ val listener =+ object : android.location.LocationListener {+ override fun onLocationChanged(location: Location) {+ if (!resumed) {+ resumed = true+ listeners.forEach { runCatching { lm.removeUpdates(it) } }+ cont.resume(location)+ }+ }++ override fun onProviderDisabled(provider: String) {}++ override fun onProviderEnabled(provider: String) {}++ @Deprecated("Deprecated")+ override fun onStatusChanged(+ provider: String?,+ status: Int,+ extras: android.os.Bundle?,+ ) { } }- override fun onProviderDisabled(provider: String) {}- override fun onProviderEnabled(provider: String) {}- @Deprecated("Deprecated")- override fun onStatusChanged(- provider: String?,- status: Int,- extras: android.os.Bundle?,- ) {- }- } listeners += listener runCatching { lm.requestLocationUpdates(provider, 0L, 0f, listener, android.os.Looper.getMainLooper()) } }
astronomy/src/main/java/com/vayunmathur/astronomy/ui/DrawDeepSkyObjects.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/DrawDeepSkyObjects.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/DrawDeepSkyObjects.ktnew file mode 100644index 0000000000..a23708d94e--- /dev/null+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/DrawDeepSkyObjects.kt@@ -0,0 +1,37 @@+package com.vayunmathur.astronomy.ui++import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.text.TextMeasurer+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.drawText+import androidx.compose.ui.unit.sp+import com.vayunmathur.astronomy.platform.VisibleDeepSky++/** Draws the projected deep-sky objects, labelled when bright enough to name at a glance. */+internal fun DrawScope.drawDeepSkyObjects(+ projectedDeep: List<Pair<VisibleDeepSky, Offset>>,+ textMeasurer: TextMeasurer,+) {+ projectedDeep.forEach { (vd, off) ->+ val color =+ when (vd.obj.type) {+ "galaxy" -> Color(0xFF90CAF9)+ "nebula" -> Color(0xFFCE93D8)+ "cluster" -> Color(0xFFFFCC80)+ else -> Color.White+ }+ drawCircle(color.copy(alpha = 0.8f), 6f, off)+ drawCircle(color, 6f, off, style = Stroke(1.5f))+ if (vd.obj.mag < 6) {+ drawText(+ textMeasurer,+ vd.obj.id,+ topLeft = off + Offset(8f, -8f),+ style = TextStyle(color, fontSize = 10.sp),+ )+ }+ }+}
astronomy/src/main/java/com/vayunmathur/astronomy/ui/ObjectDetailPage.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/ObjectDetailPage.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/ObjectDetailPage.ktindex 4bd2c2e4c9..49da89233a 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/ObjectDetailPage.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/ObjectDetailPage.kt@@ -15,13 +15,13 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.astronomy.R import com.vayunmathur.astronomy.Route import com.vayunmathur.astronomy.domain.engine.TimeEngine import com.vayunmathur.astronomy.domain.engine.toDeg import com.vayunmathur.astronomy.platform.AstronomyViewModel-import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.DesktopMaxWidthContainer import com.vayunmathur.library.ui.MaterialTheme@@ -31,11 +31,15 @@ import com.vayunmathur.library.ui.TopAppBarOverlay import com.vayunmathur.library.util.NavBackStack import kotlinx.datetime.toLocalDateTime import kotlin.time.ExperimentalTime-import androidx.compose.ui.res.stringResource+import com.vayunmathur.library.ui.R as UiR @OptIn(ExperimentalTime::class) @Composable-fun ObjectDetailPage(backStack: NavBackStack<Route>, viewModel: AstronomyViewModel, objectId: String) {+fun ObjectDetailPage(+ backStack: NavBackStack<Route>,+ viewModel: AstronomyViewModel,+ objectId: String,+) { val visibleSky by viewModel.visibleSky.collectAsState() val riseSet by viewModel.riseSet.collectAsState() val trajectory by viewModel.trajectory.collectAsState()@@ -45,7 +49,14 @@ fun ObjectDetailPage(backStack: NavBackStack<Route>, viewModel: AstronomyViewMod // Dialog detail: already correct metadata, just letterbox the column on // expanded windows so it keeps a readable measure on desktop. DesktopMaxWidthContainer {- Column(Modifier.fillMaxSize().statusBarsPadding().verticalScroll(rememberScrollState()).padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {+ Column(+ Modifier+ .fillMaxSize()+ .statusBarsPadding()+ .verticalScroll(rememberScrollState())+ .padding(16.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp),+ ) { if (detail == null) { Text(stringResource(R.string.object_not_found, objectId)) return@Column@@ -56,7 +67,7 @@ fun ObjectDetailPage(backStack: NavBackStack<Route>, viewModel: AstronomyViewMod Card(Modifier.fillMaxWidth()) { Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { Text(stringResource(R.string.ra_dec, detail.raDeg.format(2), detail.decDeg.format(2)))- Text(stringResource(R.string.ra_h_h, (detail.raDeg/15.0).format(2)))+ Text(stringResource(R.string.ra_h_h, (detail.raDeg / 15.0).format(2))) detail.altAz?.let { Text(stringResource(R.string.alt_az, it.first.format(1), it.second.format(1))) } detail.mag?.let { Text(stringResource(R.string.mag, it.format(1))) } detail.extra?.let { Text(it) }@@ -67,10 +78,13 @@ fun ObjectDetailPage(backStack: NavBackStack<Route>, viewModel: AstronomyViewMod Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { Text(stringResource(R.string.rise_transit_set), style = MaterialTheme.typography.titleSmall) val rs = riseSet- if (rs == null) Text(stringResource(R.string.calculating))- else if (rs.isNeverUp) Text(stringResource(R.string.never_rises_at_this_location))- else if (rs.isCircumpolar) Text(stringResource(R.string.circumpolar_never_sets))- else {+ if (rs == null) {+ Text(stringResource(R.string.calculating))+ } else if (rs.isNeverUp) {+ Text(stringResource(R.string.never_rises_at_this_location))+ } else if (rs.isCircumpolar) {+ Text(stringResource(R.string.circumpolar_never_sets))+ } else { Text(stringResource(R.string.rise_1, rs.riseJd?.let { jdToLocal(it) } ?: "—")) Text(stringResource(R.string.transit_1, rs.transitJd?.let { jdToLocal(it) } ?: "—")) Text(stringResource(R.string.set_1, rs.setJd?.let { jdToLocal(it) } ?: "—"))@@ -84,7 +98,10 @@ fun ObjectDetailPage(backStack: NavBackStack<Route>, viewModel: AstronomyViewMod } if (trajectory.isNotEmpty()) {- Text(stringResource(R.string.trajectory_24h_15m_steps_yellow_line_on), style = MaterialTheme.typography.labelSmall)+ Text(+ stringResource(R.string.trajectory_24h_15m_steps_yellow_line_on),+ style = MaterialTheme.typography.labelSmall,+ ) } } @@ -103,7 +120,7 @@ private data class DetailInfo( val altAz: Pair<Double, Double>?, val mag: Double?, val raDec: Pair<Double, Double>?,- val extra: String?+ val extra: String?, ) @OptIn(ExperimentalTime::class)@@ -116,15 +133,26 @@ private fun resolveDetail( id == "SUN" -> { val s = sky.sun ?: return null DetailInfo(- "Sun", "Star", s.raDec.raDeg, s.raDec.decDeg, s.altAz.altDeg to s.altAz.azDeg,- -26.7, s.raDec.raRad to s.raDec.decRad, "Distance ${s.distanceAu.format(3)} AU",+ "Sun",+ "Star",+ s.raDec.raDeg,+ s.raDec.decDeg,+ s.altAz.altDeg to s.altAz.azDeg,+ -26.7,+ s.raDec.raRad to s.raDec.decRad,+ "Distance ${s.distanceAu.format(3)} AU", ) } id == "MOON" -> { val m = sky.moon ?: return null DetailInfo(- "Moon", com.vayunmathur.astronomy.domain.engine.LunarCalculator.phaseName(m.phase),- m.raDec.raDeg, m.raDec.decDeg, m.altAz.altDeg to m.altAz.azDeg, null,+ "Moon",+ com.vayunmathur.astronomy.domain.engine.LunarCalculator+ .phaseName(m.phase),+ m.raDec.raDeg,+ m.raDec.decDeg,+ m.altAz.altDeg to m.altAz.azDeg,+ null, m.raDec.raRad to m.raDec.decRad, "Illum ${(m.illumination * 100).format(0)}% Age ${m.ageDays.format(1)}d", )@@ -133,8 +161,14 @@ private fun resolveDetail( val pid = id.removePrefix("PLANET_") val p = sky.planets.firstOrNull { it.id == pid } ?: return null DetailInfo(- p.name, "Planet", p.raDec.raDeg, p.raDec.decDeg, p.altAz.altDeg to p.altAz.azDeg,- p.mag, p.raDec.raRad to p.raDec.decRad, "Dist ${p.distanceAu.format(3)} AU",+ p.name,+ "Planet",+ p.raDec.raDeg,+ p.raDec.decDeg,+ p.altAz.altDeg to p.altAz.azDeg,+ p.mag,+ p.raDec.raRad to p.raDec.decRad,+ "Dist ${p.distanceAu.format(3)} AU", ) } id.startsWith("STAR_") -> resolveStarDetail(id, sky, vm)@@ -142,8 +176,13 @@ private fun resolveDetail( val obj = vm.catalog.deepSky.firstOrNull { it.id == id } ?: return null val v = sky.deepSky.firstOrNull { it.obj.id == id } DetailInfo(- "${obj.id} ${obj.name}", obj.type, obj.ra.toDeg(), obj.dec.toDeg(),- v?.let { it.altAz.altDeg to it.altAz.azDeg }, obj.mag, obj.ra to obj.dec,+ "${obj.id} ${obj.name}",+ obj.type,+ obj.ra.toDeg(),+ obj.dec.toDeg(),+ v?.let { it.altAz.altDeg to it.altAz.azDeg },+ obj.mag,+ obj.ra to obj.dec, "Size ${obj.sizeArcmin?.format(0) ?: "?"} arcmin", ) }@@ -158,14 +197,19 @@ private fun resolveStarDetail( ): DetailInfo? { val sid = id.removePrefix("STAR_").toIntOrNull() ?: return null val catalogStar = vm.catalog.stars.firstOrNull { it.id == sid }- val s = sky.stars.firstOrNull { it.star.id == sid }- ?: catalogStar?.let { projectCatalogStar(it, sky) }- ?: return null+ val s =+ sky.stars.firstOrNull { it.star.id == sid }+ ?: catalogStar?.let { projectCatalogStar(it, sky) }+ ?: return null return DetailInfo( s.star.properName ?: s.star.name ?: "Star ${s.star.id}", s.star.constellation ?: s.star.spectralClass ?: "",- s.star.ra.toDeg(), s.star.dec.toDeg(), s.altAz.altDeg to s.altAz.azDeg, s.star.mag,- s.star.ra to s.star.dec, "BV ${s.star.bv.format(2)}",+ s.star.ra.toDeg(),+ s.star.dec.toDeg(),+ s.altAz.altDeg to s.altAz.azDeg,+ s.star.mag,+ s.star.ra to s.star.dec,+ "BV ${s.star.bv.format(2)}", ) } @@ -175,14 +219,20 @@ private fun projectCatalogStar( sky: com.vayunmathur.astronomy.platform.VisibleSky, ): com.vayunmathur.astronomy.platform.VisibleStar? { val obs = sky.observer ?: return null- val lst = com.vayunmathur.astronomy.domain.engine.TimeEngine.lstRad(sky.jd, obs.lonRad)- val raDec = com.vayunmathur.astronomy.domain.engine.RaDec(star.ra, star.dec)- val aa = com.vayunmathur.astronomy.domain.engine.CoordinateTransforms.raDecToAltAz(- raDec,- lst,- obs.latRad,- )- return com.vayunmathur.astronomy.platform.VisibleStar(star, aa, raDec)+ val lst =+ com.vayunmathur.astronomy.domain.engine.TimeEngine+ .lstRad(sky.jd, obs.lonRad)+ val raDec =+ com.vayunmathur.astronomy.domain.engine+ .RaDec(star.ra, star.dec)+ val aa =+ com.vayunmathur.astronomy.domain.engine.CoordinateTransforms.raDecToAltAz(+ raDec,+ lst,+ obs.latRad,+ )+ return com.vayunmathur.astronomy.platform+ .VisibleStar(star, aa, raDec) } @OptIn(ExperimentalTime::class)@@ -195,9 +245,15 @@ private fun jdToLocal(jd: Double): String = formatJdInZone(jd, kotlinx.datetime. * to users in every other zone, hours away from the real local event. */ @OptIn(ExperimentalTime::class)-internal fun formatJdInZone(jd: Double, timeZone: kotlinx.datetime.TimeZone): String =- TimeEngine.julianDateToInstant(jd)+internal fun formatJdInZone(+ jd: Double,+ timeZone: kotlinx.datetime.TimeZone,+): String =+ TimeEngine+ .julianDateToInstant(jd) .toLocalDateTime(timeZone)- .toString().take(16).replace('T', ' ')+ .toString()+ .take(16)+ .replace('T', ' ') private fun Double.format(d: Int): String = "%.${d}f".format(this)
astronomy/src/main/java/com/vayunmathur/astronomy/ui/SearchPage.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SearchPage.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SearchPage.ktindex 3acee22400..464be0de9d 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SearchPage.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SearchPage.kt@@ -1,41 +1,17 @@ package com.vayunmathur.astronomy.ui -import androidx.compose.foundation.clickable-import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.Spacer-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.height-import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.layout.statusBarsPadding-import androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.lazy.items import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember import androidx.compose.runtime.setValue-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.unit.dp-import com.vayunmathur.astronomy.R import com.vayunmathur.astronomy.Route import com.vayunmathur.astronomy.platform.AstronomyViewModel-import com.vayunmathur.astronomy.platform.SearchActions-import com.vayunmathur.library.ui.DesktopMaxWidthContainer-import com.vayunmathur.library.ui.HorizontalDivider-import com.vayunmathur.library.ui.IconChevronRight-import com.vayunmathur.library.ui.ListItem-import com.vayunmathur.library.ui.OutlinedTextField-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TopAppBarOverlay import com.vayunmathur.library.util.NavBackStack-import androidx.compose.ui.res.stringResource /** Binds [AstronomyViewModel] to the stateless [SearchScreen]. */ @Composable-fun SearchPage(backStack: NavBackStack<Route>, viewModel: AstronomyViewModel) {+fun SearchPage(+ backStack: NavBackStack<Route>,+ viewModel: AstronomyViewModel,+) { SearchScreen(backStack = backStack, actions = viewModel) }-
astronomy/src/main/java/com/vayunmathur/astronomy/ui/SearchScreen.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SearchScreen.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SearchScreen.ktindex 0b83c8991c..66b37e6603 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SearchScreen.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SearchScreen.kt@@ -19,10 +19,10 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.astronomy.R import com.vayunmathur.astronomy.Route-import com.vayunmathur.astronomy.platform.AstronomyViewModel import com.vayunmathur.astronomy.platform.SearchActions import com.vayunmathur.library.ui.DesktopMaxWidthContainer import com.vayunmathur.library.ui.HorizontalDivider@@ -32,7 +32,6 @@ import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TopAppBarOverlay import com.vayunmathur.library.util.NavBackStack-import androidx.compose.ui.res.stringResource /** * The catalog search screen, with no dependency on the ViewModel so it can be rendered@@ -55,8 +54,21 @@ fun SearchScreen( // Letterbox the single results column on expanded windows; the sky map // itself stays full-bleed by design. DesktopMaxWidthContainer {- Column(Modifier.fillMaxSize().statusBarsPadding().padding(top = 56.dp).padding(12.dp)) {- OutlinedTextField(value = query, onValueChange = { query = it; results = actions.search(it) }, label = { Text(stringResource(R.string.search_stars_planets_messier)) }, modifier = Modifier.fillMaxWidth())+ Column(+ Modifier+ .fillMaxSize()+ .statusBarsPadding()+ .padding(top = 56.dp)+ .padding(12.dp),+ ) {+ OutlinedTextField(value = query, onValueChange = {+ query = it+ results = actions.search(it)+ }, label = {+ Text(+ stringResource(R.string.search_stars_planets_messier),+ )+ }, modifier = Modifier.fillMaxWidth()) Spacer(Modifier.height(8.dp)) LazyColumn(verticalArrangement = Arrangement.spacedBy(4.dp)) { items(results) { r ->@@ -64,15 +76,16 @@ fun SearchScreen( headlineContent = { Text(r.title) }, supportingContent = { Text(r.subtitle) }, trailingContent = { IconChevronRight() },- modifier = Modifier.clickable {- if (!r.id.startsWith("CONST_")) {- actions.selectObject(r.id)- // Drop the search page from the stack so back from the- // detail page returns straight to the sky map.- backStack.pop()- backStack.add(Route.ObjectDetail(r.id))- }- }+ modifier =+ Modifier.clickable {+ if (!r.id.startsWith("CONST_")) {+ actions.selectObject(r.id)+ // Drop the search page from the stack so back from the+ // detail page returns straight to the sky map.+ backStack.pop()+ backStack.add(Route.ObjectDetail(r.id))+ }+ }, ) HorizontalDivider() }
astronomy/src/main/java/com/vayunmathur/astronomy/ui/SettingsPage.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SettingsPage.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SettingsPage.ktindex 363b22f1ba..94b6a9f0d1 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SettingsPage.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SettingsPage.kt@@ -1,45 +1,20 @@ package com.vayunmathur.astronomy.ui -import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.rememberScrollState-import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember import androidx.compose.runtime.setValue-import androidx.compose.ui.Modifier-import androidx.compose.foundation.text.KeyboardOptions-import androidx.compose.ui.text.input.KeyboardType-import androidx.compose.ui.unit.dp-import com.vayunmathur.astronomy.R import com.vayunmathur.astronomy.Route import com.vayunmathur.astronomy.platform.AstronomyViewModel-import com.vayunmathur.astronomy.platform.ConstellationMode-import com.vayunmathur.astronomy.platform.SettingsActions import com.vayunmathur.astronomy.platform.SettingsUiState-import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.Button-import com.vayunmathur.library.ui.DesktopMaxWidthContainer-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.OutlinedTextField-import com.vayunmathur.library.ui.SettingsDivider-import com.vayunmathur.library.ui.SettingsSection-import com.vayunmathur.library.ui.SettingsSelectRow-import com.vayunmathur.library.ui.SettingsSwitchRow-import com.vayunmathur.library.ui.Slider-import com.vayunmathur.library.ui.Text import com.vayunmathur.library.util.NavBackStack-import androidx.compose.ui.res.stringResource /** Binds [AstronomyViewModel] to the stateless [SettingsScreen]. */ @Composable-fun SettingsPage(backStack: NavBackStack<Route>, viewModel: AstronomyViewModel) {+fun SettingsPage(+ backStack: NavBackStack<Route>,+ viewModel: AstronomyViewModel,+) { val showConst by viewModel.constellationMode.collectAsState() val showGrid by viewModel.showGrid.collectAsState() val showDeep by viewModel.showDeepSky.collectAsState()@@ -53,23 +28,22 @@ fun SettingsPage(backStack: NavBackStack<Route>, viewModel: AstronomyViewModel) SettingsScreen( backStack = backStack,- state = SettingsUiState(- constellationMode = showConst,- showGrid = showGrid,- showDeepSky = showDeep,- showPlanets = showPlanets,- showBelowHorizon = showBelow,- nightMode = nightMode,- magLimit = magLimit,- fovDeg = fov,- latDeg = observer?.latDeg,- lonDeg = observer?.lonDeg,- starCount = catalog.stars.size,- constellationCount = catalog.constellations.size,- deepSkyCount = catalog.deepSky.size,- ),+ state =+ SettingsUiState(+ constellationMode = showConst,+ showGrid = showGrid,+ showDeepSky = showDeep,+ showPlanets = showPlanets,+ showBelowHorizon = showBelow,+ nightMode = nightMode,+ magLimit = magLimit,+ fovDeg = fov,+ latDeg = observer?.latDeg,+ lonDeg = observer?.lonDeg,+ starCount = catalog.stars.size,+ constellationCount = catalog.constellations.size,+ deepSkyCount = catalog.deepSky.size,+ ), actions = viewModel, ) }--
astronomy/src/main/jav
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SettingsScreen.kt b/astronomy/src/main/javDiff truncated.