Modern Apps git

← Modern-Apps.git

maps: pivot 3D tilt camera on terrain altitude

Commit
bd207f4baf47c1e290aace7982d157e7b552d07a
Author
Vayun Mathur <[email protected]>
When
2026-11-08 19:28 UTC (27 days ago)
Parents
1f88d66
When tilting into 3D perspective the camera model pivoted the view around a plane at 0 m above sea level. Over high terrain the eye point ended up below the ground surface, so terrain clipped through the view; the coast looked fine only because it sits near 0 m.

Resolve a per-frame tilt pivot from the finest resident tile that carries a heightmap at the camera target, and raise the eye by that elevation (equivalently: substitute h -> h - H0 in the camera model) on both the Rust projection path and the Kotlin Projection mirror. Where no heightmap exists (ocean, unloaded tiles) the pivot stays 0.0, which is exactly the old behaviour.

Notable details: - New Camera::pivot_dp (world px at zoom; 0 = legacy sea-level pivot), resolved at the top of Renderer::render, gated on pitch > 0 and the flat projection (globe/Moon untouched). - Selection still uses the unpivoted JNI camera, i.e. the conservative sea-level trapezoid. - Placement cache keys and frame versions carry the pivot (exact bits plus 32-px buckets), so a changed pivot re-places labels. - Kotlin gains Projection(pivotDp), MapNative.tiltPivotDp, and a CameraState.pivotDp refreshed once per frame without waking extra recompositions. - File-length gate: sampler moved to vulkan/renderer/pivot.rs, screen_to_world_over_terrain to camera_terrain.rs, and PlacementKey to placement_reuse.rs; no behaviour change.

Verified with :library:map:compileDebugKotlin, :maps:compileDevKotlin, :library:map:lint, and cargo check --locked --offline --all-targets (all green).

Diff

library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt b/library/map/src/main/java/com/vayunmathur/library/map/CameraState.ktindex 929b891bd6..468db00831 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/CameraState.kt@@ -98,6 +98,18 @@ class CameraState(initial: CameraPosition = CameraPosition()) {     /** Viewport size in logical (dp) units; null until first layout. */     internal var viewportDp: Size? by mutableStateOf(null) +    /**+     * Tilt-pivot elevation under the camera target, in world px at [CameraPosition.zoom].+     *+     * Refreshed once per frame by the rendered surface (see `SurfaceMapRenderer`) from the+     * same resident heightmaps the renderer resolves its own pivot from, so the Compose+     * [projection] pivots on what the basemap drew with. 0.0 until the first tilted frame+     * resolves it — the legacy sea-level pivot — and always 0.0 offshore or before tiles+     * load, exactly like the renderer's fallback. Only read under pitch (flat frames key+     * heights out) and never on the globe path, which projects differently.+     */+    internal var pivotDp: Double by mutableStateOf(0.0)+     /**      * Task-17 pick provider: registered by the rendered surface (see      * `VulkanMapSurface`), answering `(box, layerIds) -> placed labels`.@@ -148,6 +160,7 @@ class CameraState(initial: CameraPosition = CameraPosition()) {                 position.target, position.zoom, vp.width, vp.height,                 position.pitch, position.bearing, labelQueryProvider, markerPickProvider,                 globe = globeEnabled && position.zoom < GLOBE_DETAIL_ZOOM,+                pivotDp = pivotDp,             )         }     }
library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt b/library/map/src/main/java/com/vayunmathur/library/map/MapNative.ktindex 7b4494e53a..ea50dde587 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/MapNative.kt@@ -105,6 +105,15 @@ internal object MapNative {         moon: Boolean,     ): Boolean +    /**+     * Tilt-pivot elevation under [lon]/[lat] in world px at [zoom] — the height the+     * renderer pivots a tilted frame on (see `Renderer::render`), for the Compose overlay+     * [Projection] so markers and gestures use the same pivot the basemap drew with.+     * Returns 0.0 — the legacy sea-level pivot — on a dead handle or where no resident+     * tile has DEM (oceans, unloaded tiles), exactly the renderer's fallback.+     */+    external fun tiltPivotDp(handle: Long, lon: Float, lat: Float, zoom: Float): Double+     /**      * Upload the Moon raster pair: [colorRgba] is `width x height` RGBA8 (the      * converted LROC color), [demRg] is `demWidth x demHeight` RG8 packed uint16
library/map/src/main/java/com/vayunmathur/library/map/Projection.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/Projection.kt b/library/map/src/main/java/com/vayunmathur/library/map/Projection.ktindex 42550aad09..6822d4ebdd 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/Projection.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/Projection.kt@@ -82,6 +82,17 @@ class Projection internal constructor(      * indistinguishable from flat — see [CameraState.globeEnabled]).      */     private val globe: Boolean = false,+    /**+     * Tilt-pivot elevation under the projection centre, in world px at [zoom].+     *+     * Mirrors the renderer's per-frame `Camera::pivot_dp`: under pitch the camera model+     * pivots on the terrain height at the target rather than on sea level, so over high+     * ground overlays stay glued to their ground points instead of sliding downhill.+     * Refreshed per frame by the rendered surface (see `SurfaceMapRenderer`) from the+     * same resident heightmaps the renderer resolves its own pivot from; 0.0 is the+     * legacy sea-level pivot (oceans, unloaded tiles, and every flat frame).+     */+    private val pivotDp: Double = 0.0, ) {     private val halfW = widthDp / 2.0     private val halfH = heightDp / 2.0@@ -120,23 +131,27 @@ class Projection internal constructor(         val pitch = Math.toRadians(pitchDeg)         val psin = sin(pitch)         val pcos = cos(pitch)-        val w = d - psin * sy+        // The eye sits d·cos above the pivot terrain (mirroring `Camera::perspective`),+        // so the forward ray carries the pivot height on both the constant column and w.+        val w = d - psin * sy + pcos * pivotDp         // Behind the eye — only past the horizon, which the pitch cap keeps off-screen. Push it         // far off rather than dividing by a non-positive w.         if (w <= 0.0) return DpOffset(OFF_SCREEN_DP.dp, OFF_SCREEN_DP.dp)         val screenX = halfW + (fx * sx / w) * halfW-        val screenY = halfH + (fy * pcos * sy / w) * halfH+        val screenY = halfH + (fy * (pcos * sy + psin * pivotDp) / w) * halfH         return DpOffset(screenX.toFloat().dp, screenY.toFloat().dp)     }      /**      * Geographic position under a screen [offset] (from the viewport top-left).      *-     * The tilted branch intersects the eye ray with the flat ground **plane**, ignoring terrain-     * elevation: over relief this leaves a bounded vertical error, which is fine for gestures-     * (pan/anchor follow the finger approximately). Exact ground/feature hits under tilt go through-     * the GPU instead — label picks via `pickLabels` and precise hits via `pickAt`'s id/depth-     * readback — both of which are terrain-correct because they read what was actually drawn.+     * The tilted branch intersects the eye ray with the pivot **plane** at [pivotDp] above+     * sea level — the terrain height the renderer pivoted on — rather than with the flat+     * ground plane: over relief this leaves only the local height-minus-pivot error, which+     * is fine for gestures (pan/anchor follow the finger approximately). Exact+     * ground/feature hits under tilt go through the GPU instead — label picks via+     * `pickLabels` and precise hits via `pickAt`'s id/depth readback — both of which are+     * terrain-correct because they read what was actually drawn.      */     fun positionFromScreenLocation(offset: DpOffset): GeoPoint {         if (globe) return globePositionFromScreenLocation(offset)@@ -152,12 +167,13 @@ class Projection internal constructor(             val pcos = cos(pitch)             val ndcX = (offset.x.value - halfW) / halfW             val ndcY = (offset.y.value - halfH) / halfH-            // Invert clip.y = fy*cos*sy / (d - sin*sy) for sy, then clip.x for sx. The denominator-            // only vanishes at/above the horizon, which the pitch cap keeps off-screen; clamp to a-            // tiny positive so a query exactly on it maps far away rather than to a NaN.+            // Invert clip.y = fy*(cos*sy + sin*h0) / (d - sin*sy + cos*h0) for sy, then+            // clip.x for sx. The denominator only vanishes at/above the horizon, which the+            // pitch cap keeps off-screen; clamp to a tiny positive so a query exactly on it+            // maps far away rather than to a NaN.             val denom = (fy * pcos + ndcY * psin).coerceAtLeast(MIN_PERSPECTIVE_DENOM)-            sy = ndcY * d / denom-            val w = d - psin * sy+            sy = (ndcY * (d + pcos * pivotDp) - fy * psin * pivotDp) / denom+            val w = d - psin * sy + pcos * pivotDp             sx = ndcX * w / fx         }         // Inverse bearing rotation (mirroring `Camera::screen_to_world`): the screen offset back
library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt
diff --git a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.ktindex eb0434311b..7d0a59ff3d 100644--- a/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt+++ b/library/map/src/main/java/com/vayunmathur/library/map/SurfaceMapRenderer.kt@@ -496,12 +496,41 @@ class SurfaceMapRenderer(     fun renderFrame(frameTimeNanos: Long): Boolean {         val snapshot = readFrameSnapshot() ?: return false         trackFrameChange(snapshot)+        refreshTiltPivot(snapshot)         val drawn = renderSnapshot(snapshot, frameTimeNanos)         if (drawn) onFrame()         if (!regionResolved) applyRegionMask()         return drawn     } +    /**+     * Refresh the Compose camera's tilt pivot from the resident heightmaps, so overlays+     * positioned through [Projection] pivot on the same terrain the basemap draws with.+     *+     * Only under pitch on the flat path — the renderer's own gate (`Renderer::render`+     * resolves its pivot exactly when `pitch > 0` off-globe) — and only on the Compose+     * path, which is the sole reader of the pivot state. Writes only on change, so a+     * settled pivot costs no recomposition; while tiles stream in the pivot converges and+     * overlays track it a frame behind the basemap. A dead handle cannot reach here+     * (`readFrameSnapshot` returns null first), and the native side answers 0.0 — the+     * legacy sea-level pivot — wherever no resident tile has DEM.+     */+    private fun refreshTiltPivot(snapshot: FrameSnapshot) {+        val state = composeCamera ?: return+        val position = snapshot.position+        if (position.pitch <= 0.0 || snapshot.globe) {+            if (state.pivotDp != 0.0) state.pivotDp = 0.0+            return+        }+        val pivot = MapNative.tiltPivotDp(+            handle,+            position.target.longitude.toFloat(),+            position.target.latitude.toFloat(),+            position.zoom.toFloat(),+        )+        if (pivot != state.pivotDp) state.pivotDp = pivot+    }+     /** Camera + viewport + globe state for one frame, or null when nothing can draw. */     private data class FrameSnapshot(         val position: CameraPosition,
library/map/src/main/rust/src/bridge/frame.rs
diff --git a/library/map/src/main/rust/src/bridge/frame.rs b/library/map/src/main/rust/src/bridge/frame.rsindex cf662800cb..17a2c032e7 100644--- a/library/map/src/main/rust/src/bridge/frame.rs+++ b/library/map/src/main/rust/src/bridge/frame.rs@@ -63,6 +63,7 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_render<'l>(         density,         bearing_deg: bearing as f64,         pitch_deg: (pitch as f64).clamp(0.0, crate::camera::PITCH_MAX_DEG),+        pivot_dp: 0.0,         globe,         moon,         time_seconds: ((frame_time_nanos.rem_euclid(crate::camera::CLOCK_WRAP_NANOS)) as f64
library/map/src/main/rust/src/bridge/pick.rs
diff --git a/library/map/src/main/rust/src/bridge/pick.rs b/library/map/src/main/rust/src/bridge/pick.rsindex 3c2a5616ae..7a118b05b8 100644--- a/library/map/src/main/rust/src/bridge/pick.rs+++ b/library/map/src/main/rust/src/bridge/pick.rs@@ -3,7 +3,7 @@ //! Pure move out of `bridge.rs`; no logic changes. use super::handle::handle_mut; use jni::objects::{JClass, JObject};-use jni::sys::{jfloat, jlong, jobjectArray};+use jni::sys::{jdouble, jfloat, jlong, jobjectArray}; use jni::{jni_str, EnvUnowned}; /// Task-17 pick: placed labels intersecting the query box (Dp from the /// viewport top-left). Returns `\u{1}`-joined `layerId/name/kind/lon/lat/featureId/regionId`@@ -91,3 +91,29 @@ pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_pickAt<'l>(     let y = (y_dp.max(0.0) * density).round() as u32;     map.renderer.pick_at(x, y) as jlong }++/// Tilt-pivot elevation under a geo point, in world px at `zoom`.+///+/// The host-side counterpart of the renderer's per-frame pivot resolution (see+/// `Renderer::render`): the Compose overlay [`Projection`](../../../..) — which+/// positions markers and answers gesture unprojection on the CPU — must pivot+/// on the same terrain height the renderer drew with, or overlays drift off+/// their ground points under tilt. Returns 0.0 — the legacy sea-level pivot —+/// on a dead handle or where no resident tile has DEM (oceans, unloaded+/// tiles), exactly the fallback the renderer uses, so both sides agree there+/// too. `lon`/`lat`/`zoom` are `Float` for the same significant-digits reason+/// as [`render`](Java_com_vayunmathur_library_map_MapNative_render)'s camera.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_map_MapNative_tiltPivotDp<'l>(+    _env: EnvUnowned<'l>,+    _class: JClass<'l>,+    handle: jlong,+    lon: jfloat,+    lat: jfloat,+    zoom: jfloat,+) -> jdouble {+    let Some(map) = handle_mut(handle) else {+        return 0.0;+    };+    map.renderer.pivot_dp_at(lon as f64, lat as f64, zoom as f64)+}
library/map/src/main/rust/src/camera.rs
diff --git a/library/map/src/main/rust/src/camera.rs b/library/map/src/main/rust/src/camera.rsindex fb8bbdcdf0..138ad727fb 100644--- a/library/map/src/main/rust/src/camera.rs+++ b/library/map/src/main/rust/src/camera.rs@@ -74,6 +74,17 @@ pub struct Camera {     /// true perspective (real z, w-divide) and [`screen_quad_to_clip`](Self::screen_quad_to_clip)     /// billboards its quad upright.     pub pitch_deg: f64,+    /// Terrain elevation of the tilt pivot, in world px at this camera's zoom.+    ///+    /// Zero is the legacy sea-level pivot: every tilted matrix below is then+    /// bit-for-bit what it always was. Nonzero raises the pivot plane to the+    /// terrain height under the camera target, so the eye (kept `d·cos` above+    /// the pivot) stays out of the ground over high terrain instead of diving+    /// under it. Resolved per frame in `Renderer::render` from the finest+    /// resident heightmap tile covering the target; oceans and unloaded tiles+    /// keep zero. Ignored at pitch 0 (the ortho fast path keys heights out of+    /// x/y) and on the globe/Moon paths.+    pub pivot_dp: f64,     /// Seconds since an arbitrary epoch, forwarded from the host's per-frame `frameTimeNanos`.     ///     /// **Bounded to `[0, `[`CLOCK_WRAP_SECONDS`]`)` and wraps** — see [`CLOCK_WRAP_NANOS`] for
library/map/src/main/rust/src/camera_extra.rs
diff --git a/library/map/src/main/rust/src/camera_extra.rs b/library/map/src/main/rust/src/camera_extra.rsindex 4915b5e7e1..1e6fe5dfe9 100644--- a/library/map/src/main/rust/src/camera_extra.rs+++ b/library/map/src/main/rust/src/camera_extra.rs@@ -226,9 +226,12 @@ impl Camera {         let p = self.perspective();         let sx = cos * dx + sin * dy;         let sy = -sin * dx + cos * dy;-        let aw = p.d - psin * sy;+        // Pivoted anchor: the ground point sits H0 above sea level, so the eye+        // is H0 higher too and the anchor's clip depth/height carry the pivot.+        let h0 = self.pivot_dp;+        let aw = p.d - psin * sy + pcos * h0;         let ax = p.fx * sx;-        let ay = p.fy * pcos * sy;+        let ay = p.fy * (pcos * sy + psin * h0);         let az = p.depth_a * aw - p.depth_b;         let rx = radius_dp / (self.width_dp as f64 / 2.0) * aw;         let ry = radius_dp / (self.height_dp as f64 / 2.0) * aw;@@ -253,7 +256,7 @@ impl Camera {     }      /// The tilt-dependent perspective constants for this camera. See [`Perspective`].-    fn perspective(&self) -> Perspective {+    pub(crate) fn perspective(&self) -> Perspective {         let half_w = self.width_dp as f64 / 2.0;         let half_h = self.height_dp as f64 / 2.0;         // MapLibre-like: the centre sits 1.5 viewport-heights from the eye. `d` cancels at@@ -303,6 +306,13 @@ impl Camera {         } = self.perspective();         let [au, av, a0] = a;         let [bu, bv, b0] = b;+        // The tilt pivot: ground heights are measured from `pivot_dp` (world px+        // above sea level), not from sea level. Substituting `hh → hh − H0` in+        // the camera model raises the eye by H0 alongside the pivot plane, so+        // its height above the pivot terrain stays `d·cos > 0` and the+        // viewpoint never dives under high terrain. H0 = 0 is the legacy+        // sea-level pivot, term-for-term what this always was.+        let h0 = self.pivot_dp;         // Column-major: the u, v, height and constant columns of (Xclip, Yclip, Zclip, Wclip).         [             (fx * au) as f32,@@ -318,9 +328,9 @@ impl Camera {             (depth_a * -cos) as f32,             (-cos) as f32, //             (fx * a0) as f32,-            (fy * cos * b0) as f32,-            (depth_a * (d - sin * b0) - depth_b) as f32,-            (d - sin * b0) as f32,+            (fy * (cos * b0 + sin * h0)) as f32,+            (depth_a * (d - sin * b0 + cos * h0) - depth_b) as f32,+            (d - sin * b0 + cos * h0) as f32,         ]     } @@ -347,13 +357,15 @@ impl Camera {             let (psin, pcos) = self.pitch_deg.to_radians().sin_cos();             let ndc_x = (screen_x_dp - half_w) / half_w;             let ndc_y = (screen_y_dp - half_h) / half_h;-            // Invert clip.y = fy*cos*sy / (d - sin*sy) for sy, then clip.x for sx.+            // Invert clip.y = fy*(cos*sy + sin*H0) / (d - sin*sy + cos*H0) for+            // sy, then clip.x for sx. H0 = 0 is the legacy sea-level solve.             let denom = p.fy * pcos + ndc_y * psin;             if denom <= 0.0 {                 return None; // at or above the horizon: the ray never meets the ground.             }-            sy = ndc_y * p.d / denom;-            let w = p.d - psin * sy;+            let h0 = self.pivot_dp;+            sy = (ndc_y * (p.d + pcos * h0) - p.fy * psin * h0) / denom;+            let w = p.d - psin * sy + pcos * h0;             sx = ndc_x * w / p.fx;         }         // Inverse bearing rotation: screen-flat offset back to a world-px offset from centre.@@ -363,98 +375,6 @@ impl Camera {         })     } -    /// The ground world-px under a screen point, intersecting the eye ray with the **displaced-    /// terrain** rather than the flat plane — the ray/heightfield extension of-    /// [`screen_to_world`](Self::screen_to_world) that WS-G's seam in-    /// [`perspective_plane`](Self::perspective_plane) anticipates.-    ///-    /// `height_at` returns the terrain height at a world-px ground position, in **world px** — the-    /// same unit the perspective matrix's `z` input uses (metres scaled by the tile's-    /// world-px-per-metre; see [`crate::tess::terrain`]). It is a closure rather than a field so-    /// this stays a pure function of the camera: the renderer passes a sampler over its resident-    /// heightmaps, tests pass a synthetic surface.-    ///-    /// At `pitch_deg == 0` the projection ignores height for x/y, so a tap lands on exactly the-    /// flat-plane point regardless of relief and this returns-    /// [`screen_to_world`](Self::screen_to_world) unchanged. Above zero it walks the eye ray from-    /// the eye toward the flat-plane hit, sampling `height_at`, and returns the first crossing of-    /// the terrain surface, refined by bisection.-    ///-    /// The march exploits that the map from screen-flat `(sx, sy, height)` to camera space is-    /// affine, so the eye ray is a straight line there: the eye is `(0, d·sin, d·cos)` (solving the-    /// camera model in [`perspective_plane`](Self::perspective_plane) for the origin) and the-    /// flat-plane hit is the ray's `height == 0` point, so the segment between them — extended a-    /// little past the plane for below-sea terrain — is the ray. `None` above the horizon-    /// (impossible on-screen under [`PITCH_MAX_DEG`]) or when the ray never meets the terrain, in-    /// which case the flat-plane hit is the best answer.-    pub fn screen_to_world_over_terrain(-        &self,-        screen_x_dp: f64,-        screen_y_dp: f64,-        height_at: impl Fn(WorldPx) -> f64,-    ) -> Option<WorldPx> {-        if self.pitch_deg == 0.0 {-            return self.screen_to_world(screen_x_dp, screen_y_dp);-        }-        // The flat-plane hit is the ray's height-0 point and, with the eye, fixes its direction.-        let plane = self.screen_to_world(screen_x_dp, screen_y_dp)?;-        let center = project(self.center_lon, self.center_lat, self.zoom);-        let (cos, sin) = self.rotation();-        // The plane hit as a screen-flat offset from the centre: the inverse of the final rotation-        // `screen_to_world` applies.-        let dxw = plane.x - center.x;-        let dyw = plane.y - center.y;-        let sx1 = cos * dxw + sin * dyw;-        let sy1 = -sin * dxw + cos * dyw;-        // The eye in the same (sx, sy, height) frame, and the ray toward the plane hit.-        let p = self.perspective();-        let (psin, pcos) = self.pitch_deg.to_radians().sin_cos();-        let eye = (0.0f64, p.d * psin, p.d * pcos);-        let dir = (sx1 - eye.0, sy1 - eye.1, 0.0 - eye.2);--        let world_at = |t: f64| {-            let sx = eye.0 + t * dir.0;-            let sy = eye.1 + t * dir.1;-            WorldPx {-                x: center.x + cos * sx - sin * sy,-                y: center.y + sin * sx + cos * sy,-            }-        };-        let ray_height = |t: f64| eye.2 + t * dir.2;-        // Positive while the ray is above the terrain, non-positive once it has crossed below.-        let gap = |t: f64| ray_height(t) - height_at(world_at(t));--        // March from the eye toward (and a little past) the plane hit. Terrain above sea rises-        // toward the ray, so its crossing is at t <= 1; below-sea terrain can push it past 1, so the-        // march overshoots before giving up. The pitch cap keeps the whole thing bounded.-        const STEPS: usize = 96;-        const T_MAX: f64 = 1.5;-        if gap(0.0) <= 0.0 {-            // The eye is at or under the terrain: degenerate, fall back to the plane hit.-            return Some(plane);-        }-        let mut prev_t = 0.0;-        for i in 1..=STEPS {-            let t = T_MAX * i as f64 / STEPS as f64;-            if gap(t) <= 0.0 {-                // A crossing is bracketed in (prev_t, t]; bisect to refine it.-                let (mut lo, mut hi) = (prev_t, t);-                for _ in 0..40 {-                    let mid = 0.5 * (lo + hi);-                    if gap(mid) > 0.0 {-                        lo = mid;-                    } else {-                        hi = mid;-                    }-                }-                return Some(world_at(0.5 * (lo + hi)));-            }-            prev_t = t;-        }-        // The ray grazed above every sample: the flat-plane hit is the best available answer.-        Some(plane)-    }-     /// The screen point (Dp from the viewport top-left) a ground world-px projects to, or `None`     /// when it falls behind the eye. The forward twin of [`screen_to_world`](Self::screen_to_world);     /// exists mainly so the round-trip is testable and the Kotlin `Projection` can mirror it.@@ -472,13 +392,14 @@ impl Camera {         }         let p = self.perspective();         let (psin, pcos) = self.pitch_deg.to_radians().sin_cos();-        let w = p.d - psin * sy;+        let h0 = self.pivot_dp;+        let w = p.d - psin * sy + pcos * h0;         if w <= 0.0 {             return None;         }         Some((             half_w + (p.fx * sx / w) * half_w,-            half_h + (p.fy * pcos * sy / w) * half_h,+            half_h + (p.fy * (pcos * sy + psin * h0) / w) * half_h,         ))     } 
library/map/src/main/rust/src/camera_extra2.rs
diff --git a/library/map/src/main/rust/src/camera_extra2.rs b/library/map/src/main/rust/src/camera_extra2.rsindex dfc9d2726b..3ff1c09449 100644--- a/library/map/src/main/rust/src/camera_extra2.rs+++ b/library/map/src/main/rust/src/camera_extra2.rs@@ -13,6 +13,7 @@ pub(crate) mod tests {             density: 1.0,             bearing_deg: 0.0,             pitch_deg: 0.0,+            pivot_dp: 0.0,             time_seconds: 0.0,             globe: false,             moon: false,@@ -105,6 +106,7 @@ pub(crate) mod tests {             density: 1.0,             bearing_deg: 0.0,             pitch_deg: 0.0,+            pivot_dp: 0.0,             time_seconds: 0.0,             globe: false,             moon: false,
library/map/src/main/rust/src/camera_extra3.rs
diff --git a/library/map/src/main/rust/src/camera_extra3.rs b/library/map/src/main/rust/src/camera_extra3.rsindex b9c6789e96..cc7a6ed5d1 100644--- a/library/map/src/main/rust/src/camera_extra3.rs+++ b/library/map/src/main/rust/src/camera_extra3.rs@@ -110,6 +110,7 @@ mod tests {             untilted,             Camera {                 pitch_deg: 0.0,+                pivot_dp: 0.0,                 ..level             }             .tile_to_clip(12, 654, 1583)@@ -128,6 +129,7 @@ mod tests {             quad,             Camera {                 pitch_deg: 0.0,+                pivot_dp: 0.0,                 ..level             }             .screen_quad_to_clip(-122.4194, 37.7749, 28.0)@@ -140,6 +142,7 @@ mod tests {         // its bottom row is no longer the ortho `(_, _, 0, 1)`, so a w-divide happens.         let tilted = Camera {             pitch_deg: 45.0,+            pivot_dp: 0.0,             ..camera(12.0)         }         .tile_to_clip(12, 2048, 2048);@@ -158,6 +161,7 @@ mod tests {                 center_lon: -122.4194,                 center_lat: 37.7749,                 pitch_deg: pitch,+                pivot_dp: 0.0,                 ..camera(12.0)             };             let m = cam.screen_quad_to_clip(-122.4194, 37.7749, 28.0);@@ -192,6 +196,7 @@ mod tests {                 center_lon: -122.4,                 center_lat: 37.7,                 pitch_deg: pitch,+                pivot_dp: 0.0,                 ..camera(12.0)             };             let center = project(-122.4, 37.7, 12.0);@@ -209,6 +214,7 @@ mod tests {         // the top of a tilted view recedes toward the horizon. At pitch 0 the two are equal.         let cam = Camera {             pitch_deg: 45.0,+            pivot_dp: 0.0,             ..camera(12.0)         };         let center = project(cam.center_lon, cam.center_lat, 12.0);@@ -245,6 +251,7 @@ mod tests {             center_lon: -122.4,             center_lat: 37.7,             pitch_deg: 50.0,+            pivot_dp: 0.0,             ..camera(13.0)         };         for &(x, y) in &[(256.0, 120.0), (256.0, 256.0), (300.0, 400.0)] {@@ -266,6 +273,7 @@ mod tests {             center_lon: 0.0,             center_lat: 0.0,             pitch_deg: 55.0,+            pivot_dp: 0.0,             ..camera(14.0)         };         let pixel = (256.0, 80.0); // above the centre: up-map, toward the horizon@@ -297,6 +305,7 @@ mod tests {             center_lon: 2.35,             center_lat: 48.85,             pitch_deg: 45.0,+            pivot_dp: 0.0,             width_dp: 411.0,             height_dp,             ..camera(13.0)@@ -348,6 +357,7 @@ mod tests {             center_lon: 0.0,             center_lat: 0.0,             pitch_deg: 50.0,+            pivot_dp: 0.0,             width_dp: 411.0,             height_dp,             ..camera(14.0)
library/map/src/main/rust/src/camera_globe_tests.rs
diff --git a/library/map/src/main/rust/src/camera_globe_tests.rs b/library/map/src/main/rust/src/camera_globe_tests.rsindex f9975e3171..c01cace1d1 100644--- a/library/map/src/main/rust/src/camera_globe_tests.rs+++ b/library/map/src/main/rust/src/camera_globe_tests.rs@@ -17,6 +17,7 @@ mod tests {             density: 1.0,             bearing_deg: 0.0,             pitch_deg: 0.0,+            pivot_dp: 0.0,             globe: true,             moon: false,             time_seconds: 0.0,
library/map/src/main/rust/src/camera_terrain.rs
diff --git a/library/map/src/main/rust/src/camera_terrain.rs b/library/map/src/main/rust/src/camera_terrain.rsnew file mode 100644index 0000000000..3ce3f69b1b--- /dev/null+++ b/library/map/src/main/rust/src/camera_terrain.rs@@ -0,0 +1,106 @@+//! Terrain-aware screen-ray casting for the tilted camera.+//!+//! File-length split from `camera_extra`: the eye-ray march that intersects a screen ray+//! with the terrain surface instead of the flat ground plane. It lives apart because the+//! flat projection helpers stay sea-level pure; this is the one camera method that reads+//! a heightfield — pivot-relative, so high ground resolves against the pivot the frame+//! drew with (see [`Camera::pivot_dp`](crate::camera::Camera)).+use crate::camera::{project, Camera, WorldPx};++impl Camera {+    /// The ground world-px under a screen point, intersecting the eye ray with the **displaced+    /// terrain** rather than the flat plane — the ray/heightfield extension of+    /// [`screen_to_world`](Self::screen_to_world) that WS-G's seam in+    /// [`perspective_plane`](Self::perspective_plane) anticipates.+    ///+    /// `height_at` returns the terrain height at a world-px ground position, in **world px** — the+    /// same unit the perspective matrix's `z` input uses (metres scaled by the tile's+    /// world-px-per-metre; see [`crate::tess::terrain`]). It is a closure rather than a field so+    /// this stays a pure function of the camera: the renderer passes a sampler over its resident+    /// heightmaps, tests pass a synthetic surface.+    ///+    /// At `pitch_deg == 0` the projection ignores height for x/y, so a tap lands on exactly the+    /// flat-plane point regardless of relief and this returns+    /// [`screen_to_world`](Self::screen_to_world) unchanged. Above zero it walks the eye ray from+    /// the eye toward the flat-plane hit, sampling `height_at`, and returns the first crossing of+    /// the terrain surface, refined by bisection.+    ///+    /// The march exploits that the map from screen-flat `(sx, sy, height)` to camera space is+    /// affine, so the eye ray is a straight line there: the eye is `(0, d·sin, d·cos)` (solving the+    /// camera model in [`perspective_plane`](Self::perspective_plane) for the origin) and the+    /// flat-plane hit is the ray's `height == 0` point, so the segment between them — extended a+    /// little past the plane for below-sea terrain — is the ray. `None` above the horizon+    /// (impossible on-screen under [`PITCH_MAX_DEG`]) or when the ray never meets the terrain, in+    /// which case the flat-plane hit is the best answer.+    pub fn screen_to_world_over_terrain(+        &self,+        screen_x_dp: f64,+        screen_y_dp: f64,+        height_at: impl Fn(WorldPx) -> f64,+    ) -> Option<WorldPx> {+        if self.pitch_deg == 0.0 {+            return self.screen_to_world(screen_x_dp, screen_y_dp);+        }+        // The flat-plane hit is the ray's height-0 point and, with the eye, fixes its direction.+        let plane = self.screen_to_world(screen_x_dp, screen_y_dp)?;+        let center = project(self.center_lon, self.center_lat, self.zoom);+        let (cos, sin) = self.rotation();+        // The plane hit as a screen-flat offset from the centre: the inverse of the final rotation+        // `screen_to_world` applies.+        let dxw = plane.x - center.x;+        let dyw = plane.y - center.y;+        let sx1 = cos * dxw + sin * dyw;+        let sy1 = -sin * dxw + cos * dyw;+        // The eye in the same (sx, sy, height) frame, and the ray toward the plane hit.+        let p = self.perspective();+        let (psin, pcos) = self.pitch_deg.to_radians().sin_cos();+        let eye = (0.0f64, p.d * psin, p.d * pcos);+        let dir = (sx1 - eye.0, sy1 - eye.1, 0.0 - eye.2);++        let world_at = |t: f64| {+            let sx = eye.0 + t * dir.0;+            let sy = eye.1 + t * dir.1;+            WorldPx {+                x: center.x + cos * sx - sin * sy,+                y: center.y + sin * sx + cos * sy,+            }+        };+        let ray_height = |t: f64| eye.2 + t * dir.2;+        // Positive while the ray is above the terrain, non-positive once it has crossed below.+        // Pivot-relative: `plane` above is the pivot-plane hit (via the pivoted+        // `screen_to_world`) and the eye frame rides H0 with it, so the march+        // compares the ray against `height − H0`. H0 = 0 is the legacy march.+        let h0 = self.pivot_dp;+        let gap = |t: f64| ray_height(t) - (height_at(world_at(t)) - h0);++        // March from the eye toward (and a little past) the plane hit. Terrain above sea rises+        // toward the ray, so its crossing is at t <= 1; below-sea terrain can push it past 1, so the+        // march overshoots before giving up. The pitch cap keeps the whole thing bounded.+        const STEPS: usize = 96;+        const T_MAX: f64 = 1.5;+        if gap(0.0) <= 0.0 {+            // The eye is at or under the terrain: degenerate, fall back to the plane hit.+            return Some(plane);+        }+        let mut prev_t = 0.0;+        for i in 1..=STEPS {+            let t = T_MAX * i as f64 / STEPS as f64;+            if gap(t) <= 0.0 {+                // A crossing is bracketed in (prev_t, t]; bisect to refine it.+                let (mut lo, mut hi) = (prev_t, t);+                for _ in 0..40 {+                    let mid = 0.5 * (lo + hi);+                    if gap(mid) > 0.0 {+                        lo = mid;+                    } else {+                        hi = mid;+                    }+                }+                return Some(world_at(0.5 * (lo + hi)));+            }+            prev_t = t;+        }+        // The ray grazed above every sample: the flat-plane hit is the best available answer.+        Some(plane)+    }+}
library/map/src/main/rust/src/lib.rs
diff --git a/library/map/src/main/rust/src/lib.rs b/library/map/src/main/rust/src/lib.rsindex 04f295c91b..f1673ba3b9 100644--- a/library/map/src/main/rust/src/lib.rs+++ b/library/map/src/main/rust/src/lib.rs@@ -38,6 +38,7 @@ pub mod camera; pub mod camera_extra; pub mod camera_extra2; pub mod camera_extra3;+pub mod camera_terrain; pub mod camera_globe; #[cfg(test)] mod camera_globe_tests;
library/map/src/main/rust/src/overlay_tests.rs
diff --git a/library/map/src/main/rust/src/overlay_tests.rs b/library/map/src/main/rust/src/overlay_tests.rsindex f8019d04db..ab65ea8505 100644--- a/library/map/src/main/rust/src/overlay_tests.rs+++ b/library/map/src/main/rust/src/overlay_tests.rs@@ -42,6 +42,7 @@             density: 3.0,             bearing_deg: bearing,             pitch_deg: 0.0,+            pivot_dp: 0.0,             time_seconds: 0.0,             globe: false,             moon: false,
library/map/src/main/rust/src/tile/placement_part3.rs
diff --git a/library/map/src/main/rust/src/tile/placement_part3.rs b/library/map/src/main/rust/src/tile/placement_part3.rsindex a9789e9f02..f8958c1c91 100644--- a/library/map/src/main/rust/src/tile/placement_part3.rs+++ b/library/map/src/main/rust/src/tile/placement_part3.rs@@ -17,6 +17,7 @@ mod tests_tilt {             density: 2.0,             bearing_deg: 0.0,             pitch_deg,+            pivot_dp: 0.0,             time_seconds: 0.0,             globe: false,             moon: false,
library/map/src/main/rust/src/tile/select/tests.rs
diff --git a/library/map/src/main/rust/src/tile/select/tests.rs b/library/map/src/main/rust/src/tile/select/tests.rsindex 31deedb00c..dd887701c1 100644--- a/library/map/src/main/rust/src/tile/select/tests.rs+++ b/library/map/src/main/rust/src/tile/select/tests.rs@@ -11,6 +11,7 @@ fn camera(lon: f64, lat: f64, zoom: f64, w: f32, h: f32) -> Camera {         density: 1.0,         bearing_deg: 0.0,         pitch_deg: 0.0,+        pivot_dp: 0.0,         time_seconds: 0.0,         globe: false,         moon: false,
library/map/src/main/rust/src/tile/select/tests_part2.rs
diff --git a/library/map/src/main/rust/src/tile/select/tests_part2.rs b/library/map/src/main/rust/src/tile/select/tests_part2.rsindex 5275e7eac9..f404990ffd 100644--- a/library/map/src/main/rust/src/tile/select/tests_part2.rs+++ b/library/map/src/main/rust/src/tile/select/tests_part2.rs@@ -11,6 +11,7 @@ fn camera(lon: f64, lat: f64, zoom: f64, w: f32, h: f32) -> Camera {         density: 1.0,         bearing_deg: 0.0,         pitch_deg: 0.0,+        pivot_dp: 0.0,         time_seconds: 0.0,         globe: false,         moon: false,@@ -135,6 +136,7 @@ fn a_tilted_viewport_pulls_in_the_trapezoid_toward_the_horizon() {     let level = camera(-122.4194, 37.7749, 14.0, 411.0, 891.0);     let tilted = Camera {         pitch_deg: 55.0,+        pivot_dp: 0.0,         ..level     };     let flat = visible(&level, 0, 16);@@ -161,6 +163,7 @@ fn every_on_screen_ground_point_of_a_tilted_view_lands_in_a_selected_tile() {     // renderer draws with, so selection and drawing agree.     let c = Camera {         pitch_deg: 50.0,+        pivot_dp: 0.0,         bearing_deg: 30.0,         ..camera(2.3522, 48.8566, 13.0, 411.0, 891.0)     };@@ -199,6 +202,7 @@ fn a_zero_pitch_selection_is_unchanged() {         visible(             &Camera {                 pitch_deg: 0.0,+                pivot_dp: 0.0,                 ..c             },             0,@@ -210,6 +214,7 @@ fn a_zero_pitch_selection_is_unchanged() {         visible(             &Camera {                 pitch_deg: 0.0,+                pivot_dp: 0.0,                 ..turned             },             0,
library/map/src/main/rust/src/tile/select/tests_part3.rs
diff --git a/library/map/src/main/rust/src/tile/select/tests_part3.rs b/library/map/src/main/rust/src/tile/select/tests_part3.rsindex ee677bd5a0..1b903ad5a6 100644--- a/library/map/src/main/rust/src/tile/select/tests_part3.rs+++ b/library/map/src/main/rust/src/tile/select/tests_part3.rs@@ -35,6 +35,7 @@ fn camera(lon: f64, lat: f64, zoom: f64, w: f32, h: f32) -> Camera {         density: 1.0,         bearing_deg: 0.0,         pitch_deg: 0.0,+        pivot_dp: 0.0,         time_seconds: 0.0,         globe: false,         moon: false,@@ -65,6 +66,7 @@ fn resident_demand_fits_the_cap_with_headroom() {                     for globe in [false, true] {                         let c = Camera {                             pitch_deg: pitch,+                            pivot_dp: 0.0,                             bearing_deg: bearing,                             globe,                             ..camera(-122.4194, 37.7749, zoom as f64, w, h)
library/map/src/main/rust/src/tile/symbol/tests.rs
diff --git a/library/map/src/main/rust/src/tile/symbol/tests.rs b/library/map/src/main/rust/src/tile/symbol/tests.rsindex c29f66b2c6..35c285cd3b 100644--- a/library/map/src/main/rust/src/tile/symbol/tests.rs+++ b/library/map/src/main/rust/src/tile/symbol/tests.rs@@ -294,6 +294,7 @@ fn camera(pitch_deg: f64) -> Camera {         density: 1.0,         bearing_deg: 0.0,         pitch_deg,+        pivot_dp: 0.0,         time_seconds: 0.0,         globe: false,         moon: false,@@ -304,6 +305,7 @@ fn camera(pitch_deg: f64) -> Camera { fn ortho2x2(cam: &Camera, z: u8, x: u32, y: u32) -> [f32; 4] {     let flat = Camera {         pitch_deg: 0.0,+        pivot_dp: 0.0,         ..*cam     }     .tile_to_clip(z, x, y);
library/map/src/main/rust/src/tile/symbol/tests_extra.rs
diff --git a/library/map/src/main/rust/src/tile/symbol/tests_extra.rs b/library/map/src/main/rust/src/tile/symbol/tests_extra.rsindex b20cd2bf20..4747614cee 100644--- a/library/map/src/main/rust/src/tile/symbol/tests_extra.rs+++ b/library/map/src/main/rust/src/tile/symbol/tests_extra.rs@@ -14,6 +14,7 @@ fn camera(pitch_deg: f64) -> Camera {         density: 1.0,         bearing_deg: 0.0,         pitch_deg,+        pivot_dp: 0.0,         time_seconds: 0.0,         globe: false,         moon: false,@@ -24,6 +25,7 @@ fn camera(pitch_deg: f64) -> Camera { fn ortho2x2(cam: &Camera, z: u8, x: u32, y: u32) -> [f32; 4] {     let flat = Camera {         pitch_deg: 0.0,+        pivot_dp: 0.0,         ..*cam     }     .tile_to_clip(z, x, y);@@ -323,6 +325,7 @@ fn an_icon_push_built_from_parts_matches_icon_push() {     let (z, x, y) = CENTRED_TILE;     let flat = Camera {         pitch_deg: 0.0,+        pivot_dp: 0.0,         ..cam     }     .tile_to_clip(z, x, y);@@ -349,6 +352,7 @@ fn an_icon_push_built_from_parts_matches_icon_push() {     let level = camera(0.0);     let flat_level = Camera {         pitch_deg: 0.0,+        pivot_dp: 0.0,         ..level     }     .tile_to_clip(z, x, y);@@ -374,6 +378,7 @@ fn the_derived_flag_drives_billboard_clip_the_way_the_shader_reads_it() {         let m = cam.tile_to_clip(z, x, y);         let flat = Camera {             pitch_deg: 0.0,+            pivot_dp: 0.0,             ..cam         }         .tile_to_clip(z, x, y);
library/map/src/main/rust/src/vulkan/renderer/fog.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/fog.rs b/library/map/src/main/rust/src/vulkan/renderer/fog.rsindex bfc9c7eb38..daa61ee4c6 100644--- a/library/map/src/main/rust/src/vulkan/renderer/fog.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/fog.rs@@ -150,6 +150,7 @@ mod tests {             density: 2.0,             bearing_deg: 0.0,             pitch_deg: pitch,+            pivot_dp: 0.0,             time_seconds: 0.0,             globe: false,             moon: false,
library/map/src/main/rust/src/vulkan/renderer/frame.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/frame.rs b/library/map/src/main/rust/src/vulkan/renderer/frame.rsindex 4542e8d06f..6044d7058b 100644--- a/library/map/src/main/rust/src/vulkan/renderer/frame.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/frame.rs@@ -255,6 +255,18 @@ impl Renderer {         clear: u32,         filter: &crate::style::KindFilter,     ) -> Result<bool, String> {+        // Tilt-pivot resolution: under pitch the camera model pivots on the terrain height+        // at the target, not on sea level, so over high ground the eye stays `d·cos` above+        // the pivot instead of diving under the terrain. Resolved here — after selection+        // ran on the unpivoted JNI camera (a conservative sea-level trapezoid) — from the+        // finest resident heightmap tile covering the target; oceans and unloaded tiles+        // resolve 0.0, the legacy pivot, bit-for-bit. Flat, globe and Moon frames skip it:+        // pitch 0 keys heights out of x/y and the globe/Moon paths project differently.+        let mut pivoted = *camera;+        if camera.pitch_deg > 0.0 && !crate::camera::globe_active(camera) {+            pivoted.pivot_dp = self.ground_pivot_dp(camera);+        }+        let camera = &pivoted;         self.last_camera = Some(*camera);         if self.width == 0 || self.height == 0 {             return Ok(true);
library/map/src/main/rust/src/vulkan/renderer/mod.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/mod.rs b/library/map/src/main/rust/src/vulkan/renderer/mod.rsindex 9d824e3f97..53477eeb41 100644--- a/library/map/src/main/rust/src/vulkan/renderer/mod.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/mod.rs@@ -17,6 +17,7 @@ mod placement; mod placement_markers; mod placement_refresh; mod placement_reuse;+mod pivot; mod quad; mod rebuild; mod record;@@ -231,51 +232,6 @@ struct TransientBuffers { /// acceptance order it landed). type AcceptSet = HashMap<u64, (bool, u32)>; -/// Everything [`Renderer::place_symbols`] reads that can change what it decides.-///-/// Floats are compared as bit patterns rather than by value. This is an identity test — "is this-/// the same camera the last accept-set was computed from" — and not a question about numeric-/// closeness, so bits are both the correct comparison and the one that needs no epsilon.-///-/// `center_lon`/`center_lat`/`zoom`/`bearing`/`pitch` carry the exact camera for the fast exact-hit-/// path; `bucket_*` carry the quantised camera for the retained-collision slow path (see-/// [`same_bucket`](PlacementKey::same_bucket)): a small pan inside one bucket reuses the accept-set-/// without re-running the quadratic placer.-#[derive(PartialEq, Eq, Clone)]-struct PlacementKey {-    center_lon: u64,-    center_lat: u64,-    zoom: u64,-    bearing: u64,-    pitch: u64,-    /// Quantised camera bucket: zoom in 1/32-level bins, bearing/pitch in 4° bins, centre in-    /// ~1/1024-tile bins at the floored zoom. Two frames in one bucket share a collision answer-    /// (only the outcome lags; boxes still re-project per frame in `refresh_placed`).-    bucket_zoom: i64,-    bucket_bearing: i64,-    bucket_pitch: i64,-    bucket_lon: i64,-    bucket_lat: i64,-    /// Whether the globe path was active: globe and flat project through different box-    /// builders, so a bucket never spans the projection switch.-    globe: bool,-    width_dp: u32,-    height_dp: u32,-    density: u32,-    extent: (u32, u32),-    filter: crate::style::KindFilter,-    /// Every resident tile with its upload stamp, so a tile that arrives or is replaced re-places-    /// even though the camera has not moved. `camera.time_seconds` is deliberately *not* in this-    /// key: it changes every frame and enters no collision box.-    tiles: Vec<(u64, u32)>,-    /// The style, by layer count. A style or toggle change re-tessellates the resident set, which-    /// restamps every tile above, so this only has to catch the layer set itself changing.-    layers: usize,-    /// The marker generation ([`Renderer::marker_epoch`]): a pushed pin set must re-place even-    /// when the camera has not moved, so a new pin immediately culls the POIs it covers.-    markers: u64,-}- /// Per-frame synchronisation and its command buffer. struct Frame {     command_buffer: vk::CommandBuffer,
library/map/src/main/rust/src/vulkan/renderer/mod_extra.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/mod_extra.rs b/library/map/src/main/rust/src/vulkan/renderer/mod_extra.rsindex 7deceb20b1..b7f648f1a8 100644--- a/library/map/src/main/rust/src/vulkan/renderer/mod_extra.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/mod_extra.rs@@ -11,9 +11,10 @@ use std::cell::Cell; use std::collections::HashMap;  use super::{-    AcceptSet, Frame, Overlay, PlacedHit, PlacementKey, ResidentTile, RouteBuffers,+    AcceptSet, Frame, Overlay, PlacedHit, ResidentTile, RouteBuffers,     TransientBuffers, };+use super::placement_reuse::PlacementKey; use super::quad::Quad; use super::upload_pool::UploadPool; use crate::style::LayerKind;@@ -261,6 +262,9 @@ pub(crate) struct FrameVersion {     zoom: u64,     bearing: u64,     pitch: u64,+    /// Exact tilt-pivot elevation bits: the pivot moves the projection, so a frame whose+    /// pivot resolved differently must submit rather than early-out.+    pivot: u64,     width_dp: u32,     height_dp: u32,     density: u32,@@ -293,6 +297,7 @@ impl FrameVersion {             zoom: camera.zoom.to_bits(),             bearing: camera.bearing_deg.to_bits(),             pitch: camera.pitch_deg.to_bits(),+            pivot: camera.pivot_dp.to_bits(),             width_dp: camera.width_dp.to_bits(),             height_dp: camera.height_dp.to_bits(),             density: camera.density.to_bits(),
library/map/src/main/rust/src/vulkan/renderer/pivot.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/pivot.rs b/library/map/src/main/rust/src/vulkan/renderer/pivot.rsnew file mode 100644index 0000000000..a806b2a1f8--- /dev/null+++ b/library/map/src/main/rust/src/vulkan/renderer/pivot.rs@@ -0,0 +1,59 @@+//! Tilt-pivot elevation sampling for pitched frames.+//!+//! File-length split from the frame loop (see [`render`](super::Renderer::render)): the+//! per-frame pivot resolution that walks the resident tile pyramid for the terrain height+//! under the camera target — and the shared sampler behind it, exposed for the host-side+//! overlay projection so markers and gestures pivot on what the basemap drew with.+use super::Renderer;+use crate::camera::Camera;+use crate::tile::select;++impl Renderer {+    /// Tilt-pivot elevation under the camera target, in world px at this zoom.+    ///+    /// Walks the tile pyramid from the finest level that can hold the target+    /// (`floor(zoom)`, clamped to 0..=22) down to z0 and samples the first+    /// resident tile carrying a heightmap, at the target's tile-local (u, v).+    /// Metres become world px through the tile's own span over its ground+    /// width — the same normalisation the label ground sampler uses, inverted.+    ///+    /// Returns 0.0 — the legacy sea-level pivot — where no resident tile has+    /// DEM (oceans, unloaded tiles), so those frames render exactly as before.+    pub(super) fn ground_pivot_dp(&self, camera: &Camera) -> f64 {+        self.pivot_dp_at(camera.center_lon, camera.center_lat, camera.zoom)+    }++    /// Tilt-pivot elevation under an arbitrary geo point, in world px at `zoom`:+    /// the shared sampler behind [`ground_pivot_dp`](Self::ground_pivot_dp), exposed+    /// for the host-side overlay projection through+    /// [`tiltPivotDp`](Java_com_vayunmathur_library_map_MapNative_tiltPivotDp), so+    /// markers and gestures use the same pivot the renderer drew with. Same 0.0+    /// fallback where no resident tile has DEM.+    pub(crate) fn pivot_dp_at(&self, lon: f64, lat: f64, zoom: f64) -> f64 {+        use crate::tile::geometry::{sample_ground_metres, tile_ground_width_m};+        let z_top = zoom.floor().clamp(0.0, 22.0) as u8;+        let c = crate::camera::project(lon, lat, zoom);+        let size = crate::camera::world_size(zoom);+        for z in (0..=z_top).rev() {+            let n = 2u32.pow(z as u32); // tiles per side; z <= 22 fits u32 and TileId's 22-bit x/y.+            let span = size / f64::from(n); // == camera.tile_span_dp(z).+            let tx = ((c.x / span).floor() as u32).min(n - 1);+            let ty = ((c.y / span).floor() as u32).min(n - 1);+            let key = select::TileId { z, x: tx, y: ty }.key();+            let Some(tile) = self.tiles.get(&key) else {+                continue;+            };+            if tile.heightmap.is_none() {+                continue;+            }+            let u = ((c.x - f64::from(tx) * span) / span) as f32;+            let v = ((c.y - f64::from(ty) * span) / span) as f32;+            let Some(m) = sample_ground_metres(&tile.heightmap, u, v) else {+                continue;+            };+            let width = tile_ground_width_m(z, ty).max(f64::MIN_POSITIVE);+            return f64::from(m) * span / width;+        }+        0.0+    }+}
library/map/src/main/rust/src/vulkan/renderer/placement.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/placement.rs b/library/map/src/main/rust/src/vulkan/renderer/placement.rsindex aae61b1cb4..3235a845dc 100644--- a/library/map/src/main/rust/src/vulkan/renderer/placement.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/placement.rs@@ -1,7 +1,9 @@ use super::{     anchors_for, kind_name,-    placement_reuse::{box_inputs, box_inputs_with_arms, bucket_for, reuse_cached_accept},-    AcceptSet, Overlay, PlacedHit, PlacementKey, Renderer, QUAD_INDICES,+    placement_reuse::{+        box_inputs, box_inputs_with_arms, bucket_for, reuse_cached_accept, PlacementKey,+    },+    AcceptSet, Overlay, PlacedHit, Renderer, QUAD_INDICES, }; use crate::camera::Camera; use crate::marker::Marker;@@ -61,7 +63,7 @@ impl Renderer {     ) -> AcceptSet {         use crate::tile::placement;         let globe = crate::camera::globe_active(camera);-        let (bucket_zoom, bucket_bearing, bucket_pitch, bucket_lon, bucket_lat) =+        let (bucket_zoom, bucket_bearing, bucket_pitch, bucket_pivot, bucket_lon, bucket_lat) =             bucket_for(camera);         let key = PlacementKey {             center_lon: camera.center_lon.to_bits(),@@ -69,9 +71,11 @@ impl Renderer {             zoom: camera.zoom.to_bits(),             bearing: camera.bearing_deg.to_bits(),             pitch: camera.pitch_deg.to_bits(),+            pivot: camera.pivot_dp.to_bits(),             bucket_zoom,             bucket_bearing,             bucket_pitch,+            bucket_pivot,             bucket_lon,             bucket_lat,             globe,
library/map/src/main/rust/src/vulkan/renderer/placement_reuse.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/placement_reuse.rs b/library/map/src/main/rust/src/vulkan/renderer/placement_reuse.rsindex ee543c8beb..821a25a309 100644--- a/library/map/src/main/rust/src/vulkan/renderer/placement_reuse.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/placement_reuse.rs@@ -6,8 +6,66 @@ //! accept-set, the [`PlacementKey`] universe comparison behind it, and the //! per-label collision-box inputs the candidate loop reads. A real submodule //! (not `include!`), so imports are explicit below.-use super::PlacementKey; use super::AcceptSet;++/// Everything [`Renderer::place_symbols`](super::Renderer::place_symbols) reads that can change+/// what it decides.+///+/// File-length split from the renderer root (see `mod.rs`): the key lives here with the+/// reuse machinery that compares it, instead of beside the buffer structs.+///+/// Floats are compared as bit patterns rather than by value. This is an identity test — "is this+/// the same camera the last accept-set was computed from" — and not a question about numeric+/// closeness, so bits are both the correct comparison and the one that needs no epsilon.+///+/// `center_lon`/`center_lat`/`zoom`/`bearing`/`pitch` carry the exact camera for the fast exact-hit+/// path; `bucket_*` carry the quantised camera for the retained-collision slow path (see+/// [`same_bucket`](PlacementKey::same_bucket)): a small pan inside one bucket reuses the accept-set+/// without re-running the quadratic placer.+#[derive(PartialEq, Eq, Clone)]+pub(crate) struct PlacementKey {+    pub(super) center_lon: u64,+    pub(super) center_lat: u64,+    pub(super) zoom: u64,+    pub(super) bearing: u64,+    pub(super) pitch: u64,+    /// Exact tilt-pivot elevation bits: the pivot moves the projection, so a still camera+    /// whose pivot resolved differently (a finer DEM tile arrived) must not exact-hit.+    /// Like centre, it is pose, not universe — drift reuse ignores it (see `within_drift`)+    /// and the bucket below carries its coarse bins.+    pub(super) pivot: u64,+    /// Quantised camera bucket: zoom in 1/32-level bins, bearing/pitch in 4° bins, centre in+    /// ~1/1024-tile bins at the floored zoom. Two frames in one bucket share a collision answer+    /// (only the outcome lags; boxes still re-project per frame in `refresh_placed`).+    pub(super) bucket_zoom: i64,+    pub(super) bucket_bearing: i64,+    pub(super) bucket_pitch: i64,+    /// Coarse pivot bins (32 world px): pivot changes within a bin reuse the accept-set,+    /// a bin crossing re-places. Self-scaling — a fixed ground height is fewer px at low+    /// zoom, where its projection effect is negligible, and more where it matters.+    pub(super) bucket_pivot: i64,+    pub(super) bucket_lon: i64,+    pub(super) bucket_lat: i64,+    /// Whether the globe path was active: globe and flat project through different box+    /// builders, so a bucket never spans the projection switch.+    pub(super) globe: bool,+    pub(super) width_dp: u32,+    pub(super) height_dp: u32,+    pub(super) density: u32,+    pub(super) extent: (u32, u32),+    pub(super) filter: crate::style::KindFilter,+    /// Every resident tile with its upload stamp, so a tile that arrives or is replaced re-places+    /// even though the camera has not moved. `camera.time_seconds` is deliberately *not* in this+    /// key: it changes every frame and enters no collision box.+    pub(super) tiles: Vec<(u64, u32)>,+    /// The style, by layer count. A style or toggle change re-tessellates the resident set, which+    /// restamps every tile above, so this only has to catch the layer set itself changing.+    pub(super) layers: usize,+    /// The marker generation ([`Renderer::marker_epoch`](super::Renderer::marker_epoch)): a pushed+    /// pin set must re-place even when the camera has not moved, so a new pin immediately culls+    /// the POIs it covers.+    pub(super) markers: u64,+} use crate::camera::Camera; use crate::style::Layer; use crate::tile::geometry;@@ -97,6 +155,7 @@ impl PlacementKey {         self.bucket_zoom == other.bucket_zoom             && self.bucket_bearing == other.bucket_bearing             && self.bucket_pitch == other.bucket_pitch+            && self.bucket_pivot == other.bucket_pivot             && self.bucket_lon == other.bucket_lon             && self.bucket_lat == other.bucket_lat             && self.globe == other.globe@@ -245,20 +304,23 @@ fn collision_padding_dp(zoom: f64) -> f32 { /// /// Bin sizes: zoom in 1/32-level bins (a slow pinch crosses ~2 bins/sec — each re-place is a /// stable answer, not flicker); bearing/pitch in 4° bins (inside the old 2° drift budget's-/// spirit but coarser, because boxes re-project anyway); centre in ~1/1024-tile bins at the+/// spirit but coarser, because boxes re-project anyway); pivot in 32-world-px bins (a tile+/// refining under a still camera usually stays in-bin and reuses; panning into genuinely+/// higher ground crosses bins and re-places); centre in ~1/1024-tile bins at the /// floored zoom (sub-pixel at every zoom — a pan crosses a bin every few frames at most). /// Globe is part of the key (flat and globe project through different box builders).-pub(super) fn bucket_for(camera: &Camera) -> (i64, i64, i64, i64, i64) {+pub(super) fn bucket_for(camera: &Camera) -> (i64, i64, i64, i64, i64, i64) {     let zoom_bin = (camera.zoom * 32.0).floor() as i64;     let bearing_bin = (camera.bearing_deg.rem_euclid(360.0) / 4.0).floor() as i64;     let pitch_bin = (camera.pitch_deg / 4.0).floor() as i64;+    let pivot_bin = (camera.pivot_dp / 32.0).floor() as i64;     // Centre bins in tile units at the floored zoom: zoom-independent bin density.     let floor_z = camera.zoom.floor().clamp(0.0, 22.0);     let span = 512.0 * 2f64.powf(floor_z);     let centre = crate::camera::project(camera.center_lon, camera.center_lat, floor_z);     let lon_bin = (centre.x / span * 1024.0).floor() as i64;     let lat_bin = (centre.y / span * 1024.0).floor() as i64;-    (zoom_bin, bearing_bin, pitch_bin, lon_bin, lat_bin)+    (zoom_bin, bearing_bin, pitch_bin, pivot_bin, lon_bin, lat_bin) }  #[cfg(test)]@@ -276,6 +338,7 @@ mod tests {             density: 2.0,             bearing_deg: bearing,             pitch_deg: pitch,+            pivot_dp: 0.0,             time_seconds: 0.0,             globe: false,             moon: false,@@ -325,8 +388,8 @@ mod tests {         let low_b = camera(-122.4194 + shift_lon, 37.7749, 6.0, 0.0, 0.0);         let high_a = camera(-122.4194, 37.7749, 14.0, 0.0, 0.0);         let high_b = camera(-122.4194 + shift_lon, 37.7749, 14.0, 0.0, 0.0);-        let low_moved = bucket_for(&low_a).3 != bucket_for(&low_b).3;-        let high_moved = bucket_for(&high_a).3 != bucket_for(&high_b).3;+        let low_moved = bucket_for(&low_a).4 != bucket_for(&low_b).4;+        let high_moved = bucket_for(&high_a).4 != bucket_for(&high_b).4;         // At z6 the shift is sub-bin (stays), at z14 it crosses bins (moves): the point         // is the scaling holds, i.e. bins track ground, not zoom floats.         assert!(!low_moved || high_moved);
library/map/src/main/rust/src/vulkan/renderer/record_symbol.rs
diff --git a/library/map/src/main/rust/src/vulkan/renderer/record_symbol.rs b/library/map/src/main/rust/src/vulkan/renderer/record_symbol.rsindex 64b1998611..c01cbd8888 100644--- a/library/map/src/main/rust/src/vulkan/renderer/record_symbol.rs+++ b/library/map/src/main/rust/src/vulkan/renderer/record_symbol.rs@@ -218,6 +218,7 @@ impl Renderer {         // which is exactly the silent failure this sharing exists to make unrepresentable.         let flat_clip = Camera {             pitch_deg: 0.0,+            pivot_dp: 0.0,             ..*camera         }         .tile_to_clip(tz, tx, ty);