astronomy: pinch-to-zoom and pan the sky view
- Commit
5ff3d8ebbf56c8bbe82a5a7e0f9db79bbc481594- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-05 14:13 UTC (18 hours ago)
- Parents
485171d
The sky map rendered through the stereographic projection at a field of view owned by the ViewModel (default 70 degrees, changed only by the Settings slider), and the center always followed the phone pointing direction. SkyCanvas already had separate drag and transform gesture handlers, but the screen wired pan to a no-op and the pinch handler zoomed about the screen center, discarding the pinch centroid, so exploring a patch of sky by hand was impossible. Now one detectTransformGestures handler drives both gestures through the projection: pinch scales the field of view about the fingers' centroid (the sky point under the centroid stays under it, refined through project/unproject in the new domain/projection/ViewTransform.kt), and drag pans so content follows the finger, covering proportionally less sky at narrower fields of view. Field-of-view limits are one shared definition on ViewState (10-120 degrees, reconciling the gesture clamp, the Settings slider range and the ViewModel clamp): at 10 degrees the ~9,100-star magnitude-6 catalog still leaves a dozen or more stars in a typical field, and past 120 degrees stereographic edge distortion grows steeply with no more sky to reveal. The Settings FOV slider is unchanged in behaviour and now reads the same limits. Tap hit-testing already ran against the projected positions for the current view, so picking uses the zoomed projection unchanged; a new tap guard keeps the release that ends a drag or pinch from also selecting whatever sits under the lifting finger. Manual control arbitrates with the sensors through the existing CenterOption model: the first pan or pinch switches DevicePointing to Manual at the resolved center (capturing the current device orientation as an anchor), so the compass cannot fight the gesture. While manual, each orientation sample is compared with the anchor as a full pointing-frame rotation (pointing direction plus roll about it, in platform/ManualViewArbitration.kt); a rotation of 45 degrees or more re-engages DevicePointing and drops the panned center, while smaller rotations leave the manual view alone. The zoomed field of view is kept across re-engagement. Gestures that take manual control are exactly drag-pan and pinch (including a pinch about the screen center); taps and the Settings slider do not. In Manual the view rotation resolves to zero as before, so a rolled phone sees the sky upright itself on the first gesture. Tests first: ViewTransformTest covers centroid-fixed zoom in and out, clamping at both limits, pan invariants and picking separation at high zoom; ManualViewArbitrationTest covers the 45-degree threshold (pointing, azimuth wrap-around, pure roll, combined rotations, missing samples); AstronomyViewModelTest covers the manual takeover and FOV clamping through setView. Verified: ./gradlew :astronomy:lint :astronomy:lintVitalRelease :astronomy:testDevUnitTest (plus ktlint main/test checks) with --max-workers=128. All green except the one pre-existing SettingsScreenInteractionsTest failure, proven identical on the 18988e3b9 baseline in a clean worktree. Screenshot previews are unchanged (the sample sky still renders at 70 degrees), so no metadata captures were regenerated.
Diff
astronomy/AGENTS.md
diff --git a/astronomy/AGENTS.md b/astronomy/AGENTS.mdindex f209e30554..19472a01dd 100644--- a/astronomy/AGENTS.md+++ b/astronomy/AGENTS.md@@ -12,7 +12,7 @@ _Install: ./install astronomy (dev by default)._ ## Overview **Purpose:** Offline AR night-sky viewer — sensor-tracked sky map, camera passthrough, time scrubber, bundled star/planet catalogs, rise/set search. 100% offline.-**Key features:** `ui/SkyCanvas` + grid/art layers over `domain/projection/` (stereographic) fed by `domain/engine/` calculators (solar/lunar/planetary/rise-set/time) with a Rust core (`domain/AstronomyNative`); catalogs in `data/` validated at build time by `scripts/` generators.+**Key features:** `ui/SkyCanvas` + grid/art layers over `domain/projection/` (stereographic) fed by `domain/engine/` calculators (solar/lunar/planetary/rise-set/time) with a Rust core (`domain/AstronomyNative`); catalogs in `data/` validated at build time by `scripts/` generators. The sky view pinches to zoom about the fingers and drags to pan (`domain/projection/ViewTransform.kt`, FOV clamped to `ViewState` 10-120 degrees, shared with the Settings slider): the first gesture takes manual control from the sensors, and a phone rotation of 45 degrees or more from the takeover orientation (`platform/ManualViewArbitration.kt`) hands the center back to the sensors (the zoomed FOV is kept). **Entry points:** `Route` → `MainActivity.kt` → `Navigation.kt` → `ui/SkyMapPage.kt` → `platform/AstronomyViewModel.kt` → `domain/engine/TimeEngine.kt`. Assistant entry: `intents/TonightIntent` (OpenAssistant `astronomy_get_tonight`) returns one capped tonight summary (Sun/Moon times, Moon phase, brightest visible planets) computed by the domain calculators; DTOs in `library/intents/astronomy/`, signature-permission gated. **Gotchas:** Catalog data is generated (`scripts/` DB generators) — never hand-edit; sensor + location drive the sky, test with movement, not static. @@ -35,11 +35,13 @@ _Install: ./install astronomy (dev by default)._ - com/vayunmathur/astronomy/domain/projection/SkyProjection.kt - com/vayunmathur/astronomy/domain/projection/StereographicProjection.kt - com/vayunmathur/astronomy/domain/projection/ViewState.kt+- com/vayunmathur/astronomy/domain/projection/ViewTransform.kt — pinch-zoom-about-centroid and pan transforms over `ViewState` ### intents/ — assistant IPC - com/vayunmathur/astronomy/intents/TonightIntent.kt — validated `TonightQuery` → capped `AstronomyTonightData` summary; explicit location pair or saved observer fallback - com/vayunmathur/astronomy/intents/TonightSummary.kt — location validation + pure tonight-summary builder over the domain calculators ### platform/ — ViewModel + location - com/vayunmathur/astronomy/platform/AstronomyViewModel.kt+- com/vayunmathur/astronomy/platform/ManualViewArbitration.kt — manual-vs-sensor view arbitration (45-degree re-engagement) - com/vayunmathur/astronomy/platform/AstronomyUiContract.kt - com/vayunmathur/astronomy/platform/sensor/LocationProvider.kt ### ui/ — sky map + detail + search
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 18984db51f..fe085e463c 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@@ -11,4 +11,23 @@ data class ViewState( ) { val fovRad get() = Math.toRadians(fovDeg.toDouble()) val fovDegDouble get() = fovDeg.toDouble()++ companion object {+ /**+ * Field-of-view limits shared by the pinch gesture, the settings+ * slider and the ViewModel, so every zoom path clamps identically.+ * At the 10-degree floor the roughly 9,100-star magnitude-6 catalog+ * still leaves a dozen or more stars in a typical field (below that,+ * fields empty out and stereographic scale magnifies sensor noise);+ * past 120 degrees the stereographic edge distortion grows steeply+ * and the view approaches the whole hemisphere, so there is no more+ * sky to reveal.+ */+ const val MIN_FOV_DEG = 10f+ const val MAX_FOV_DEG = 120f+ const val DEFAULT_FOV_DEG = 70f++ /** Clamps [fovDeg] to the shared field-of-view limits. */+ fun clampFov(fovDeg: Float): Float = fovDeg.coerceIn(MIN_FOV_DEG, MAX_FOV_DEG)+ } }
astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/ViewTransform.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/ViewTransform.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/ViewTransform.ktnew file mode 100644index 0000000000..d6a489c5d4--- /dev/null+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/ViewTransform.kt@@ -0,0 +1,79 @@+package com.vayunmathur.astronomy.domain.projection++import androidx.compose.ui.geometry.Offset+import com.vayunmathur.astronomy.domain.engine.AltAz+import kotlin.math.abs++/**+ * Returns this view zoomed by [zoomFactor] (above 1 zooms in) about the+ * screen [centroid], so the sky point under the centroid stays under it.+ *+ * The sky point at the centroid is unprojected under the current view, the+ * field of view is scaled and clamped, and the center is then refined until+ * that same sky point reprojects onto the centroid under the new field of+ * view: each pass moves the center, through the candidate projection, by+ * half the remaining screen error (a full step overshoots at wide fields of+ * view, where the projection stretches fastest). A zoom already clamped at+ * a field-of-view limit leaves the view untouched, so pinching against the+ * limit never drifts the center.+ */+fun ViewState.zoomedAbout(+ centroid: Offset,+ zoomFactor: Float,+): ViewState {+ if (!zoomFactor.isFinite() || zoomFactor <= 0f) return this+ val newFov = ViewState.clampFov(fovDeg / zoomFactor)+ if (newFov == fovDeg) return this+ val skyAtCentroid = StereographicProjection(this).unproject(centroid) ?: return copy(fovDeg = newFov)+ var candidate = copy(fovDeg = newFov)+ var best = candidate+ var bestError = Float.POSITIVE_INFINITY+ repeat(ZOOM_REFINE_PASSES) {+ val projection = StereographicProjection(candidate)+ val landed = projection.project(skyAtCentroid)+ if (landed == null) {+ // The centroid's sky point fell outside the candidate's cull+ // disk (a large zoom step from a screen corner): center on it+ // and refine from there, where it is visible by construction.+ candidate = candidate.copy(centerAzRad = skyAtCentroid.azRad, centerAltRad = skyAtCentroid.altRad)+ return@repeat+ }+ val errorX = landed.x - centroid.x+ val errorY = landed.y - centroid.y+ val error = abs(errorX) + abs(errorY)+ if (error < bestError) {+ bestError = error+ best = candidate+ }+ if (abs(errorX) < ZOOM_TOLERANCE_PX && abs(errorY) < ZOOM_TOLERANCE_PX) return candidate+ val newCenter =+ projection.unproject(+ Offset(+ screenW / 2 + errorX * ZOOM_STEP_FRACTION,+ screenH / 2 + errorY * ZOOM_STEP_FRACTION,+ ),+ ) ?: return best+ candidate = candidate.copy(centerAzRad = newCenter.azRad, centerAltRad = newCenter.altRad)+ }+ return best+}++/**+ * Returns this view panned by the screen-space [drag] offset, so the sky+ * moves with the finger: the new center is the sky point that sat at the+ * screen center minus the drag, which is the point that then sits at the+ * center — content follows the finger. Because the conversion goes through+ * the projection, the same pixel drag covers proportionally less sky at a+ * narrower (zoomed-in) field of view.+ */+fun ViewState.pannedBy(drag: Offset): ViewState {+ if (drag == Offset.Zero) return this+ val newCenter: AltAz =+ StereographicProjection(this).unproject(Offset(screenW / 2 - drag.x, screenH / 2 - drag.y))+ ?: return this+ return copy(centerAzRad = newCenter.azRad, centerAltRad = newCenter.altRad)+}++private const val ZOOM_REFINE_PASSES = 24+private const val ZOOM_STEP_FRACTION = 0.5f+private const val ZOOM_TOLERANCE_PX = 0.5f
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 396d7881be..c7a02ffdff 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/platform/AstronomyUiContract.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/platform/AstronomyUiContract.kt@@ -49,6 +49,13 @@ data class SkyMapUiState( interface SkyMapActions { fun setFov(v: Float) {} + /** Applies a pan/pinch gesture's absolute center and field of view. */+ fun setView(+ centerAzRad: Double,+ centerAltRad: Double,+ fovDeg: Float,+ ) {}+ fun selectObject(id: String) {} fun setTime(
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 6618dabd10..2b6b55267c 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/platform/AstronomyViewModel.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/platform/AstronomyViewModel.kt@@ -15,6 +15,7 @@ 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.astronomy.domain.projection.ViewState import com.vayunmathur.astronomy.platform.sensor.LocationProvider import com.vayunmathur.library.sensor.DeviceOrientation import com.vayunmathur.library.sensor.OrientationManager@@ -167,8 +168,6 @@ class AstronomyViewModel( SearchActions, SettingsActions { private companion object {- const val MIN_FOV_DEG = 10f- const val MAX_FOV_DEG = 120f const val MIN_LAT_DEG = -90.0 const val MAX_LAT_DEG = 90.0 const val MIN_LON_DEG = -180.0@@ -358,6 +357,7 @@ class AstronomyViewModel( fun enableAr(enabled: Boolean) { _isArMode.value = enabled if (enabled) {+ manualAnchorOrientation = null _viewCenter.value = CenterOption.DevicePointing _devicePointingEnabled.value = true }@@ -376,7 +376,19 @@ class AstronomyViewModel( updateRiseSetForSelected() } viewModelScope.launch {- orientationMgr.orientation.collect { _deviceOrientation.value = it }+ orientationMgr.orientation.collect {+ _deviceOrientation.value = it+ // While the user is exploring manually the sensors must not+ // fight the pan, but a deliberate large turn of the phone+ // means "look here now": drop the manual center and follow+ // the phone again. Small rotations leave the manual view be.+ if (_viewCenter.value is CenterOption.Manual &&+ shouldReengageTracking(manualAnchorOrientation, it)+ ) {+ manualAnchorOrientation = null+ _viewCenter.value = CenterOption.DevicePointing+ }+ } } orientationMgr.start() _viewCenter.value = CenterOption.DevicePointing@@ -437,6 +449,7 @@ class AstronomyViewModel( } fun setDevicePointing(v: Boolean) {+ manualAnchorOrientation = null _devicePointingEnabled.value = v prefs.saveBool("astro_device_pointing", v) if (v) {@@ -459,8 +472,40 @@ class AstronomyViewModel( } override fun setFov(v: Float) {- _fovDeg.value = v.coerceIn(MIN_FOV_DEG, MAX_FOV_DEG)- prefs.saveDouble("astro_fov", v.toDouble())+ _fovDeg.value = ViewState.clampFov(v)+ prefs.saveDouble("astro_fov", _fovDeg.value.toDouble())+ }++ // The device orientation captured when the user took manual control of+ // the view by panning or pinching; null while the sensors (or an+ // explicit non-gesture mode change) own the view. A phone rotation of+ // REENGAGE_ROTATION_DEG or more from this sample hands the view back to+ // the sensors, however far the user had panned.+ private var manualAnchorOrientation: DeviceOrientation? = null++ /**+ * Applies a manual pan/pinch result from the sky canvas: the absolute+ * view center and field of view the gesture computed through the+ * projection. The first gesture while the phone is tracking takes+ * manual control (the current orientation becomes the re-engagement+ * anchor and the sensors stop driving the center); later gestures just+ * move the manual view. The field of view itself is kept when tracking+ * later re-engages — only the panned center is dropped.+ */+ override fun setView(+ centerAzRad: Double,+ centerAltRad: Double,+ fovDeg: Float,+ ) {+ if (_viewCenter.value is CenterOption.DevicePointing) {+ manualAnchorOrientation = _deviceOrientation.value+ }+ _viewCenter.value =+ CenterOption.Manual(+ centerAzRad,+ centerAltRad.coerceIn(-Math.PI / 2, Math.PI / 2),+ )+ setFov(fovDeg) } override fun setManualLocation(
astronomy/src/main/java/com/vayunmathur/astronomy/platform/ManualViewArbitration.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/platform/ManualViewArbitration.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/platform/ManualViewArbitration.ktnew file mode 100644index 0000000000..f4260f32f3--- /dev/null+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/platform/ManualViewArbitration.kt@@ -0,0 +1,109 @@+package com.vayunmathur.astronomy.platform++import com.vayunmathur.library.sensor.DeviceOrientation+import kotlin.math.acos+import kotlin.math.cos+import kotlin.math.sin++/**+ * How far the phone must rotate, in degrees, from the orientation at which+ * the user took manual control of the sky view before orientation tracking+ * re-engages and the manual pan is dropped.+ */+const val REENGAGE_ROTATION_DEG = 45.0++/**+ * True when the phone has rotated at least [REENGAGE_ROTATION_DEG] from+ * [anchor] (the orientation when manual control took over) to [current], so+ * sensor tracking should drive the view again. A missing sample on either+ * side never re-engages.+ */+fun shouldReengageTracking(+ anchor: DeviceOrientation?,+ current: DeviceOrientation?,+): Boolean {+ if (anchor == null || current == null) return false+ // The epsilon only absorbs floating-point noise in the acos at the+ // boundary; a rotation of exactly 45 degrees re-engages.+ return orientationRotationDeg(anchor, current) >= REENGAGE_ROTATION_DEG - ROTATION_EPSILON_DEG+}++/**+ * The rotation angle, in degrees, between two device orientations as the+ * code represents them: the angle between the two pointing frames, where a+ * frame is the pointing direction (azimuth/altitude of the phone's back)+ * plus the device-up direction implied by the view rotation about that+ * pointing axis. Pure pointing changes, pure rolls about the viewing axis,+ * and any composition of the two all contribute to the one angle.+ */+fun orientationRotationDeg(+ from: DeviceOrientation,+ to: DeviceOrientation,+): Double {+ val (f1, u1) = orientationFrame(from)+ val (f2, u2) = orientationFrame(to)+ val r1 = cross(f1, u1)+ val r2 = cross(f2, u2)+ val trace = dot(f1, f2) + dot(u1, u2) + dot(r1, r2)+ val cosAngle = ((trace - 1.0) / 2.0).coerceIn(-1.0, 1.0)+ return Math.toDegrees(acos(cosAngle))+}++/** A minimal 3D vector for the frame math above, in east/north/up axes. */+private data class Vec3(+ val x: Double,+ val y: Double,+ val z: Double,+)++/** The pointing direction and device-up direction of one orientation sample. */+private fun orientationFrame(orientation: DeviceOrientation): Pair<Vec3, Vec3> {+ val az = orientation.pointingAzRad+ val alt = orientation.pointingAltRad+ // Pointing (the phone's back) in east/north/up: azimuth runs from north+ // toward east, altitude above the horizon.+ val forward =+ Vec3(+ x = cos(alt) * sin(az),+ y = cos(alt) * cos(az),+ z = sin(alt),+ )+ // Celestial up (the zenith) projected into the plane facing the viewer,+ // which is the direction of increasing altitude; it stays well defined+ // even at the zenith/nadir, where the unprojected zenith would vanish.+ val celestialUp =+ Vec3(+ x = -sin(alt) * sin(az),+ y = -sin(alt) * cos(az),+ z = cos(alt),+ )+ // Device up is celestial up rotated about the pointing axis by the roll+ // the orientation carries: viewRotationDeg is the negative of that roll+ // (see OrientationManager.viewRotationFromDeviceToWorld).+ val roll = -orientation.viewRotationRad+ val across = cross(forward, celestialUp)+ val up =+ Vec3(+ x = celestialUp.x * cos(roll) + across.x * sin(roll),+ y = celestialUp.y * cos(roll) + across.y * sin(roll),+ z = celestialUp.z * cos(roll) + across.z * sin(roll),+ )+ return forward to up+}++private fun cross(+ a: Vec3,+ b: Vec3,+): Vec3 =+ Vec3(+ x = a.y * b.z - a.z * b.y,+ y = a.z * b.x - a.x * b.z,+ z = a.x * b.y - a.y * b.x,+ )++private fun dot(+ a: Vec3,+ b: Vec3,+): Double = a.x * b.x + a.y * b.y + a.z * b.z++private const val ROTATION_EPSILON_DEG = 1e-6
astronomy/src/main/java/com/vayunmathur/astronomy/ui/SettingsScreen.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SettingsScreen.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SettingsScreen.ktindex 518c537f7b..2faea94342 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SettingsScreen.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SettingsScreen.kt@@ -19,6 +19,7 @@ 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.domain.projection.ViewState import com.vayunmathur.astronomy.platform.ConstellationMode import com.vayunmathur.astronomy.platform.SettingsActions import com.vayunmathur.astronomy.platform.SettingsUiState@@ -148,7 +149,7 @@ fun SettingsScreen( Slider( value = state.fovDeg, onValueChange = { actions.setFov(it) },- valueRange = 10f..120f,+ valueRange = ViewState.MIN_FOV_DEG..ViewState.MAX_FOV_DEG, valueFormatter = { context.getString(R.string.fov, it.toInt().toString()) }, ) }
astronomy/src/main/java/com/vayunmathur/astronomy/ui/SkyCanvas.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SkyCanvas.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SkyCanvas.ktindex ff9f57537e..15d5bf7888 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SkyCanvas.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SkyCanvas.kt@@ -1,7 +1,6 @@ package com.vayunmathur.astronomy.ui import androidx.compose.foundation.Canvas-import androidx.compose.foundation.gestures.detectDragGestures import androidx.compose.foundation.gestures.detectTransformGestures import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable@@ -21,7 +20,9 @@ import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.unit.sp import com.vayunmathur.astronomy.domain.projection.StereographicProjection import com.vayunmathur.astronomy.domain.projection.ViewState+import com.vayunmathur.astronomy.domain.projection.pannedBy import com.vayunmathur.astronomy.domain.projection.projectAll+import com.vayunmathur.astronomy.domain.projection.zoomedAbout import com.vayunmathur.astronomy.platform.TrajectoryPoint import com.vayunmathur.astronomy.platform.VisibleSky import kotlin.math.sqrt@@ -39,8 +40,8 @@ fun SkyCanvas( transparentBackground: Boolean = false, trajectory: List<TrajectoryPoint> = emptyList(), selectedId: String? = null,- onPan: (azDeg: Double, altDeg: Double) -> Unit,- onZoom: (Float) -> Unit,+ /** Reports the absolute view a pan/pinch gesture computed through the projection. */+ onViewChange: (ViewState) -> Unit, onTap: (Offset) -> Unit, onObjectTap: (String) -> Unit, onObjectOpen: (String) -> Unit = onObjectTap,@@ -48,8 +49,7 @@ fun SkyCanvas( val textMeasurer = rememberTextMeasurer() val projection = remember(viewState) { StereographicProjection(viewState) } - // Constellation-art bitmaps, decoded from assets on demand and cached.- val context = LocalContext.current+ val context = LocalContext.current // constellation-art bitmaps are decoded from assets on demand and cached val artCache = remember { mutableMapOf<String, android.graphics.Bitmap?>() } val artPaint = remember {@@ -70,13 +70,14 @@ fun SkyCanvas( }.getOrNull() } - // Kept fresh so the pointer handler (keyed on projection/geometry, not these)- // always sees the latest selection + callbacks.+ // Kept fresh so the pointer handlers always see the latest selection + callbacks. val currentSelectedId by rememberUpdatedState(selectedId) val currentShowPlanets by rememberUpdatedState(showPlanets) val currentOnObjectTap by rememberUpdatedState(onObjectTap) val currentOnObjectOpen by rememberUpdatedState(onObjectOpen) val currentOnTap by rememberUpdatedState(onTap)+ val currentViewState by rememberUpdatedState(viewState)+ val currentOnViewChange by rememberUpdatedState(onViewChange) val projectedStars = remember(visibleSky.stars, projection) {@@ -106,19 +107,15 @@ fun SkyCanvas( modifier = modifier .fillMaxSize()- .pointerInput(viewState) {- detectDragGestures { change, dragAmount ->- change.consume()- val w = size.width.toFloat()- val h = size.height.toFloat()- // viewState.fovDeg is Float- val azDelta = (-dragAmount.x / w * viewState.fovDeg).toDouble()- val altDelta = (dragAmount.y / h * viewState.fovDeg).toDouble() // revert: natural- onPan(azDelta, altDelta)- }- }.pointerInput(viewState) {- detectTransformGestures { _, _, zoom, _ ->- onZoom((viewState.fovDeg / zoom).coerceIn(10f, 120f))+ .pointerInput(Unit) {+ // One transform handler for pan and pinch (never both a drag and a pinch): pinch+ // zooms about the centroid, pan moves the zoomed view, both through the projection.+ detectTransformGestures { centroid, pan, zoom, _ ->+ val start = currentViewState+ var transformed = start+ if (zoom != 1f) transformed = transformed.zoomedAbout(centroid, zoom)+ if (pan != Offset.Zero) transformed = transformed.pannedBy(pan)+ if (transformed != start) currentOnViewChange(transformed) } }.pointerInput( visibleSky,@@ -130,18 +127,35 @@ fun SkyCanvas( moonProj, ) { awaitPointerEventScope {+ // A tap is a single finger that stays put: a drag/pinch release selects nothing.+ var downPos: Offset? = null+ var multiTouch = false while (true) { val event = awaitPointerEvent()+ if (event.changes.any { it.pressed }) {+ if (event.changes.count { it.pressed } > 1) multiTouch = true+ if (downPos == null) {+ downPos = event.changes.firstOrNull { it.pressed }?.position+ }+ } val change = event.changes.firstOrNull() ?: continue if (!change.pressed && change.previousPressed) { val pos = change.position+ val startPos = downPos+ val movedPx =+ startPos?.let {+ sqrt((pos.x - it.x) * (pos.x - it.x) + (pos.y - it.y) * (pos.y - it.y))+ } ?: Float.POSITIVE_INFINITY+ val wasTap = !multiTouch && movedPx < TAP_SLOP_PX+ downPos = null+ multiTouch = false+ if (!wasTap) continue fun dist( a: Offset, b: Offset, ): Float {- val dx =- a.x - b.x+ val dx = a.x - b.x val dy = a.y - b.y return sqrt(dx * dx + dy * dy) }@@ -329,3 +343,6 @@ fun SkyCanvas( if (viewState.centerAltRad < Math.toRadians(60.0)) drawCardinalLabels(projection, textMeasurer) } }++/** A release further than this from its touch-down is a drag/pinch ending, not a tap. */+private const val TAP_SLOP_PX = 24f
astronomy/src/main/java/com/vayunmathur/astronomy/ui/SkyMapScreen.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SkyMapScreen.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SkyMapScreen.ktindex 8888a4114b..7e8a0eb285 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SkyMapScreen.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/SkyMapScreen.kt@@ -79,9 +79,9 @@ fun SkyMapScreen( transparentBackground = cameraOn, trajectory = state.trajectory, selectedId = state.selectedObjectId,- // Pan is disabled: the sky always tracks the phone.- onPan = { _, _ -> },- onZoom = { actions.setFov(it) },+ // Pan/pinch explores manually: the gesture's absolute view+ // takes manual control until the phone turns well away.+ onViewChange = { actions.setView(it.centerAzRad, it.centerAltRad, it.fovDeg) }, onTap = { _ -> }, onObjectTap = { id -> actions.selectObject(id) }, onObjectOpen = { id ->
astronomy/src/test/java/com/vayunmathur/astronomy/domain/projection/ViewTransformTest.kt
diff --git a/astronomy/src/test/java/com/vayunmathur/astronomy/domain/projection/ViewTransformTest.kt b/astronomy/src/test/java/com/vayunmathur/astronomy/domain/projection/ViewTransformTest.ktnew file mode 100644index 0000000000..702a72080b--- /dev/null+++ b/astronomy/src/test/java/com/vayunmathur/astronomy/domain/projection/ViewTransformTest.kt@@ -0,0 +1,144 @@+package com.vayunmathur.astronomy.domain.projection++import androidx.compose.ui.geometry.Offset+import com.vayunmathur.astronomy.domain.engine.AltAz+import com.vayunmathur.astronomy.domain.engine.toRad+import kotlin.math.abs+import kotlin.math.hypot+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * Pinch-zoom / pan math over [ViewState]: zooming about the pinch centroid+ * keeps the sky point under the fingers fixed, the FOV clamps to the shared+ * limits, pan moves less sky at a narrower FOV, and nearby objects separate+ * enough at high zoom for tap picking to tell them apart.+ */+class ViewTransformTest {+ private val base = ViewState(30.0.toRad(), 40.0.toRad(), 70f, 1080f, 1920f)++ @Test+ fun zoom_about_centroid_keeps_centroid_sky_point_fixed() {+ val centroid = Offset(800f, 600f)+ val skyAtCentroid = StereographicProjection(base).unproject(centroid)+ assertNotNull(skyAtCentroid)++ val zoomed = base.zoomedAbout(centroid, zoomFactor = 2f)++ assertEquals(35f, zoomed.fovDeg, 0.01f)+ val reprojected = StereographicProjection(zoomed).project(skyAtCentroid)+ assertNotNull(reprojected)+ assertTrue(abs(reprojected.x - centroid.x) < 1f, "x drifted: ${reprojected.x} vs ${centroid.x}")+ assertTrue(abs(reprojected.y - centroid.y) < 1f, "y drifted: ${reprojected.y} vs ${centroid.y}")+ }++ @Test+ fun zoom_about_screen_center_keeps_view_center_fixed() {+ val center = Offset(base.screenW / 2, base.screenH / 2)+ val zoomed = base.zoomedAbout(center, zoomFactor = 2f)+ assertEquals(base.centerAzRad, zoomed.centerAzRad, 1e-9)+ assertEquals(base.centerAltRad, zoomed.centerAltRad, 1e-9)+ assertEquals(35f, zoomed.fovDeg, 0.01f)+ }++ @Test+ fun zoom_out_about_centroid_keeps_centroid_sky_point_fixed() {+ val centroid = Offset(250f, 1400f)+ val skyAtCentroid = StereographicProjection(base).unproject(centroid)+ assertNotNull(skyAtCentroid)++ val zoomed = base.zoomedAbout(centroid, zoomFactor = 0.5f)++ assertEquals(120f, zoomed.fovDeg, 0.01f)+ val reprojected = StereographicProjection(zoomed).project(skyAtCentroid)+ assertNotNull(reprojected)+ assertTrue(abs(reprojected.x - centroid.x) < 1f, "x drifted: ${reprojected.x} vs ${centroid.x}")+ assertTrue(abs(reprojected.y - centroid.y) < 1f, "y drifted: ${reprojected.y} vs ${centroid.y}")+ }++ @Test+ fun zoom_clamps_to_shared_fov_limits() {+ val centroid = Offset(800f, 600f)+ assertEquals(ViewState.MAX_FOV_DEG, base.zoomedAbout(centroid, 0.01f).fovDeg)+ assertEquals(ViewState.MIN_FOV_DEG, base.zoomedAbout(centroid, 100f).fovDeg)+ // Already at a limit: zooming further that way changes nothing at all.+ val atMin = base.copy(fovDeg = ViewState.MIN_FOV_DEG)+ assertEquals(atMin, atMin.zoomedAbout(centroid, 4f))+ val atMax = base.copy(fovDeg = ViewState.MAX_FOV_DEG)+ assertEquals(atMax, atMax.zoomedAbout(centroid, 0.25f))+ }++ @Test+ fun pan_moves_center_sky_point_by_the_drag_amount() {+ val drag = Offset(120f, -80f)+ val centerSky = AltAz(base.centerAzRad, base.centerAltRad)++ val panned = base.pannedBy(drag)++ // Content follows the finger: the old center lands a drag away from+ // the new center (approximately — the projection is not affine, so a+ // few pixels of drift across a 144-pixel drag is expected) ...+ val reprojected = StereographicProjection(panned).project(centerSky)+ assertNotNull(reprojected)+ assertTrue(abs(reprojected.x - (base.screenW / 2 + drag.x)) < 16f, "x: ${reprojected.x}")+ assertTrue(abs(reprojected.y - (base.screenH / 2 + drag.y)) < 16f, "y: ${reprojected.y}")+ // ... and exactly for the point the pan is defined by: the sky that+ // sat at center-minus-drag now sits at the center.+ val anchorSky =+ StereographicProjection(base).unproject(Offset(base.screenW / 2 - drag.x, base.screenH / 2 - drag.y))+ assertNotNull(anchorSky)+ val anchorLanded = StereographicProjection(panned).project(anchorSky)+ assertNotNull(anchorLanded)+ assertTrue(abs(anchorLanded.x - base.screenW / 2) < 1f, "anchor x: ${anchorLanded.x}")+ assertTrue(abs(anchorLanded.y - base.screenH / 2) < 1f, "anchor y: ${anchorLanded.y}")+ }++ @Test+ fun pan_at_narrow_fov_moves_proportionally_less_sky() {+ val drag = Offset(200f, 0f)+ val widePan = base.pannedBy(drag)+ val narrowPan = base.copy(fovDeg = 15f).pannedBy(drag)++ val wideShift = abs(widePan.centerAzRad - base.centerAzRad)+ val narrowShift = abs(narrowPan.centerAzRad - base.centerAzRad)+ assertTrue(+ narrowShift < wideShift / 2,+ "narrow shift $narrowShift should be far below wide $wideShift",+ )+ }++ @Test+ fun nearby_objects_separate_and_pick_correctly_at_high_zoom() {+ // Two stars two degrees apart in azimuth, east of the view center.+ val starA = AltAz(base.centerAzRad + 4.0.toRad(), base.centerAltRad)+ val starB = AltAz(base.centerAzRad + 6.0.toRad(), base.centerAltRad)+ val centroid = StereographicProjection(base).project(starA)+ assertNotNull(centroid)++ val zoomed = base.zoomedAbout(centroid, zoomFactor = 4f)+ val proj = StereographicProjection(zoomed)+ val posA = proj.project(starA)+ val posB = proj.project(starB)+ assertNotNull(posA)+ assertNotNull(posB)+ // The centroid star stays under the fingers after zooming in.+ assertTrue(+ abs(posA.x - centroid.x) < 1f && abs(posA.y - centroid.y) < 1f,+ "centroid star moved: $posA vs $centroid",+ )+ // At the zoomed FOV the pair is far enough apart that the nearest-hit+ // rule used for taps picks the tapped star, not its neighbour.+ assertTrue(+ hypot(posA.x - posB.x, posA.y - posB.y) > 72f,+ "stars still overlap for picking",+ )+ val tapNearB = Offset(posB.x + 10f, posB.y)+ val nearest =+ listOf(starA to posA, starB to posB).minBy { (_, off) ->+ hypot(off.x - tapNearB.x, off.y - tapNearB.y)+ }+ assertEquals(starB, nearest.first)+ }+}
astronomy/src/test/java/com/vayunmathur/astronomy/platform/AstronomyViewModelTest.kt
diff --git a/astronomy/src/test/java/com/vayunmathur/astronomy/platform/AstronomyViewModelTest.kt b/astronomy/src/test/java/com/vayunmathur/astronomy/platform/AstronomyViewModelTest.ktindex f5dd6af66f..0adb024576 100644--- a/astronomy/src/test/java/com/vayunmathur/astronomy/platform/AstronomyViewModelTest.kt+++ b/astronomy/src/test/java/com/vayunmathur/astronomy/platform/AstronomyViewModelTest.kt@@ -85,6 +85,22 @@ class AstronomyViewModelTest { assertTrue(vm.isArMode.value) } + @Test fun `manual pan and pinch take the view off sensor tracking`() {+ val vm = AstronomyViewModel(app)+ assertTrue(vm.viewCenter.value is CenterOption.DevicePointing)+ vm.setView(centerAzRad = 1.0, centerAltRad = 0.5, fovDeg = 25f)+ val manual = vm.viewCenter.value+ assertTrue(manual is CenterOption.Manual)+ assertEquals(1.0, (manual as CenterOption.Manual).azRad)+ assertEquals(0.5, manual.altRad)+ assertEquals(25f, vm.fovDeg.value)+ // The gesture path clamps the field of view like every other path.+ vm.setView(centerAzRad = 1.0, centerAltRad = 0.5, fovDeg = 1f)+ assertEquals(10f, vm.fovDeg.value)+ vm.setView(centerAzRad = 1.0, centerAltRad = 0.5, fovDeg = 500f)+ assertEquals(120f, vm.fovDeg.value)+ }+ @Test fun `selection computes trajectory and rise-set, clear resets`() { val vm = AstronomyViewModel(app) await("catalog") { vm.catalogReady.value }
astronomy/src/test/java/com/vayunmathur/astronomy/platform/ManualViewArbitrationTest.kt
diff --git a/astronomy/src/test/java/com/vayunmathur/astronomy/platform/ManualViewArbitrationTest.kt b/astronomy/src/test/java/com/vayunmathur/astronomy/platform/ManualViewArbitrationTest.ktnew file mode 100644index 0000000000..5e546d41c4--- /dev/null+++ b/astronomy/src/test/java/com/vayunmathur/astronomy/platform/ManualViewArbitrationTest.kt@@ -0,0 +1,94 @@+package com.vayunmathur.astronomy.platform++import com.vayunmathur.library.sensor.DeviceOrientation+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Manual-view arbitration: exploring by pan/pinch hands the view to the user,+ * and only a large phone rotation (>= 45 degrees from the orientation at+ * takeover) hands it back to the sensors. Small rotations must not.+ */+class ManualViewArbitrationTest {+ private fun orientation(+ pointingAzDeg: Double = 90.0,+ pointingAltDeg: Double = 30.0,+ viewRotationDeg: Double = 0.0,+ ) = DeviceOrientation(+ azimuthTrueDeg = pointingAzDeg,+ azimuthMagDeg = pointingAzDeg,+ pitchDeg = 0.0,+ rollDeg = 0.0,+ accuracy = 3,+ pointingAzTrueDeg = pointingAzDeg,+ pointingAltDeg = pointingAltDeg,+ viewRotationDeg = viewRotationDeg,+ )++ @Test+ fun `identical orientations have zero rotation and stay manual`() {+ val anchor = orientation()+ assertEquals(0.0, orientationRotationDeg(anchor, anchor), 1e-9)+ assertFalse(shouldReengageTracking(anchor, anchor))+ }++ @Test+ fun `small pointing rotations stay manual`() {+ val anchor = orientation()+ assertFalse(shouldReengageTracking(anchor, orientation(pointingAzDeg = 90.0 + 44.0)))+ assertFalse(shouldReengageTracking(anchor, orientation(pointingAltDeg = 30.0 - 44.0)))+ assertEquals(44.0, orientationRotationDeg(anchor, orientation(pointingAzDeg = 134.0)), 0.01)+ }++ @Test+ fun `pointing rotation at and past 45 degrees reengages tracking`() {+ val anchor = orientation()+ assertTrue(shouldReengageTracking(anchor, orientation(pointingAzDeg = 90.0 + 45.0)))+ assertTrue(shouldReengageTracking(anchor, orientation(pointingAzDeg = 90.0 + 90.0)))+ assertTrue(shouldReengageTracking(anchor, orientation(pointingAltDeg = 30.0 + 50.0)))+ }++ @Test+ fun `azimuth wrap-around measures the short way round`() {+ val anchor = orientation(pointingAzDeg = 350.0, pointingAltDeg = 0.0)+ // 350 -> 40 is a 50-degree rotation, not 310.+ assertEquals(+ 50.0,+ orientationRotationDeg(anchor, orientation(pointingAzDeg = 40.0, pointingAltDeg = 0.0)),+ 0.01,+ )+ assertTrue(shouldReengageTracking(anchor, orientation(pointingAzDeg = 40.0, pointingAltDeg = 0.0)))+ // 350 -> 20 is only 30 degrees.+ assertFalse(shouldReengageTracking(anchor, orientation(pointingAzDeg = 20.0, pointingAltDeg = 0.0)))+ }++ @Test+ fun `pure roll about the pointing axis counts toward the rotation`() {+ val anchor = orientation()+ assertEquals(50.0, orientationRotationDeg(anchor, orientation(viewRotationDeg = 50.0)), 0.01)+ assertTrue(shouldReengageTracking(anchor, orientation(viewRotationDeg = 50.0)))+ assertFalse(shouldReengageTracking(anchor, orientation(viewRotationDeg = 30.0)))+ }++ @Test+ fun `combined small rotations stay manual until the total reaches 45`() {+ val anchor = orientation()+ // 20 degrees of yaw plus 20 degrees of roll compose to under 45.+ assertFalse(+ shouldReengageTracking(anchor, orientation(pointingAzDeg = 110.0, viewRotationDeg = 20.0)),+ )+ // 30 degrees of yaw plus 30 degrees of roll already compose past 45:+ // the total rotation is the one frame angle, not either axis alone.+ assertTrue(+ shouldReengageTracking(anchor, orientation(pointingAzDeg = 120.0, viewRotationDeg = 30.0)),+ )+ }++ @Test+ fun `no anchor or no current orientation never reengages`() {+ assertFalse(shouldReengageTracking(null, orientation()))+ assertFalse(shouldReengageTracking(orientation(), null))+ }+}
astronomy/src/test/java/com/vayunmathur/astronomy/ui/AstronomyScreensTest.kt
diff --git a/astronomy/src/test/java/com/vayunmathur/astronomy/ui/AstronomyScreensTest.kt b/astronomy/src/test/java/com/vayunmathur/astronomy/ui/AstronomyScreensTest.ktindex 4c6ca8946e..677d59504d 100644--- a/astronomy/src/test/java/com/vayunmathur/astronomy/ui/AstronomyScreensTest.kt+++ b/astronomy/src/test/java/com/vayunmathur/astronomy/ui/AstronomyScreensTest.kt@@ -76,8 +76,7 @@ class AstronomyScreensTest { showGrid = true, showDeepSky = true, showPlanets = true,- onPan = { _, _ -> },- onZoom = {},+ onViewChange = {}, onTap = {}, onObjectTap = {}, )
astronomy/src/test/java/com/vayunmathur/astronomy/ui/SkyCanvasDrawTest.kt
diff --git a/astronomy/src/test/java/com/vayunmathur/astronomy/ui/SkyCanvasDrawTest.kt b/astronomy/src/test/java/com/vayunmathur/astronomy/ui/SkyCanvasDrawTest.ktindex c9f1adc44b..19fdcf709a 100644--- a/astronomy/src/test/java/com/vayunmathur/astronomy/ui/SkyCanvasDrawTest.kt+++ b/astronomy/src/test/java/com/vayunmathur/astronomy/ui/SkyCanvasDrawTest.kt@@ -113,8 +113,7 @@ class SkyCanvasDrawTest { } private class Recorder {- val pans = mutableListOf<Pair<Double, Double>>()- val zooms = mutableListOf<Float>()+ val viewChanges = mutableListOf<ViewState>() val taps = mutableListOf<androidx.compose.ui.geometry.Offset>() val objectTaps = mutableListOf<String>() val objectOpens = mutableListOf<String>()@@ -144,8 +143,7 @@ class SkyCanvasDrawTest { TrajectoryPoint(2460000.7, AltAz(0.1, 0.6), RaDec(1.1, 0.5)), ), selectedId = selectedId,- onPan = { az, alt -> recorder.pans += az to alt },- onZoom = { recorder.zooms += it },+ onViewChange = { recorder.viewChanges += it }, onTap = { recorder.taps += it }, onObjectTap = { recorder.objectTaps += it }, onObjectOpen = { recorder.objectOpens += it },
astronomy/src/test/java/com/vayunmathur/astronomy/ui/SkyMapScreenTest.kt
diff --git a/astronomy/src/test/java/com/vayunmathur/astronomy/ui/SkyMapScreenTest.kt b/astronomy/src/test/java/com/vayunmathur/astronomy/ui/SkyMapScreenTest.ktindex 4133aa2788..51d0341590 100644--- a/astronomy/src/test/java/com/vayunmathur/astronomy/ui/SkyMapScreenTest.kt+++ b/astronomy/src/test/java/com/vayunmathur/astronomy/ui/SkyMapScreenTest.kt@@ -72,6 +72,7 @@ class SkyMapScreenTest { private class RecordingActions : SkyMapActions { val fovs = mutableListOf<Float>()+ val views = mutableListOf<Triple<Double, Double, Float>>() val selected = mutableListOf<String>() val times = mutableListOf<Pair<Instant, Boolean>>() @@ -79,6 +80,14 @@ class SkyMapScreenTest { fovs += v } + override fun setView(+ centerAzRad: Double,+ centerAltRad: Double,+ fovDeg: Float,+ ) {+ views += Triple(centerAzRad, centerAltRad, fovDeg)+ }+ override fun selectObject(id: String) { selected += id }