Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / library / map / src / main / rust / src / camera.rs

camera.rs233 lines · 11.4 KiBRaw
1//! The camera: a snapshot from Kotlin to a per-tile clip-space matrix.
2//!
3//! Web Mercator on a 512-logical-px tile grid (world = 512 * 2^zoom), matching
4//! `:library:map`'s `Mercator.kt` — the Kotlin side owns the public `Projection`
5//! in `Dp`, this side has to agree with it or every overlay drifts from the
6//! basemap under it.
7//!
8//! 512 is also what gives MapLibre parity: the vector archives are authored on
9//! that convention, so at the same zoom float a tile covers the same ground and
10//! renders at the same size. This used to be a 256 grid with a compensating +1
11//! zoom offset applied at the JNI boundary, which produced the right ground scale
12//! by a different route but had two costs: tile addressing took the floor of the
13//! *offset* zoom, so a screenful fetched four times as many tiles as MapLibre
14//! does, and every style ramp — widths, `text_size`, opacity and the `min_zoom`
15//! layer gating — was evaluated one level away from the zoom the authored
16//! `basemap.json` those values were transcribed from meant by it.
17//!
18//! Only the camera crosses JNI, once per frame. Everything per-tile is derived here.
19
20/// Logical pixels across one tile: 512, the convention the archives are authored on.
21///
22/// World scale is 512 * 2^zoom, which is MapLibre's, so tile addressing is the plain
23/// floor of the camera zoom and every ramp is evaluated at the zoom the style means.
24pub const TILE_SIZE: f64 = 512.0;
25
26/// Largest camera tilt we allow, in degrees.
27///
28/// Not cosmetic: at this cap the horizon still sits above the top of the screen (the
29/// perspective's far edge is a finite ground distance), so [`Camera::screen_to_world`]
30/// always meets the ground plane and tile selection never has to cover an infinite
31/// trapezoid. `fy = d/half_h = 3` and the horizon enters the screen only past
32/// `atan(fy) ≈ 71°`, so 65 leaves a margin. See [`Camera::pitch_deg`].
33pub const PITCH_MAX_DEG: f64 = 65.0;
34
35/// The camera as Kotlin measured it.
36#[derive(Clone, Copy, Debug)]
37pub struct Camera {
38 pub center_lon: f64,
39 pub center_lat: f64,
40 pub zoom: f64,
41 /// Viewport in logical pixels (Dp), as the Compose host measured it.
42 pub width_dp: f32,
43 pub height_dp: f32,
44 /// Device pixels per Dp. The only place a physical pixel enters.
45 pub density: f32,
46 /// Whether this frame draws the Moon instead of the Earth vector basemap.
47 ///
48 /// Only read while [`globe_active`] holds: the Moon path skips tile
49 /// selection/fetch entirely (the raster pair is one uploaded texture, not
50 /// tiles) and draws the textured sphere instead. False on every path but
51 /// the maps body switch.
52 pub moon: bool,
53 /// Whether to draw the orthographic-sphere globe rather than the flat map.
54 ///
55 /// False on every path but the phone globe toggle (and always false past
56 /// [`GLOBE_FLAT_THRESHOLD`], where the sphere is sub-pixel from flat): the
57 /// flat derivation below is then taken bit-for-bit as before. When true,
58 /// [`tile_to_clip`](Self::tile_to_clip) bends each tile onto the sphere and
59 /// [`visible`](crate::tile::select::visible) selects the disc the viewport
60 /// sees.
61 pub globe: bool,
62 /// Which compass direction points **up** the screen, in degrees clockwise from
63 /// north. Zero is north-up, which is every path but heading-up car navigation.
64 ///
65 /// A rotation, not a tilt: it composes into the clip matrices as a plain 2x2. Tilt is
66 /// [`pitch_deg`](Self::pitch_deg), which is the perspective term and composes separately.
67 pub bearing_deg: f64,
68 /// Camera tilt away from straight-down, in degrees, expected in `0..=`[`PITCH_MAX_DEG`]
69 /// (the JNI boundary clamps it; the matrices below assume nothing).
70 ///
71 /// Zero is the classic top-down orthographic map — every path but the tilt gesture — and
72 /// is short-circuited in every matrix builder so the ortho fast-path is byte-for-byte what
73 /// it always was. Above zero [`world_quad_to_clip`](Self::world_quad_to_clip) produces a
74 /// true perspective (real z, w-divide) and [`screen_quad_to_clip`](Self::screen_quad_to_clip)
75 /// billboards its quad upright.
76 pub pitch_deg: f64,
77 /// Terrain elevation of the tilt pivot, in world px at this camera's zoom.
78 ///
79 /// Zero is the legacy sea-level pivot: every tilted matrix below is then
80 /// bit-for-bit what it always was. Nonzero raises the pivot plane to the
81 /// terrain height under the camera target, so the eye (kept `d·cos` above
82 /// the pivot) stays out of the ground over high terrain instead of diving
83 /// under it. Resolved per frame in `Renderer::render` from the finest
84 /// resident heightmap tile covering the target; oceans and unloaded tiles
85 /// keep zero. Ignored at pitch 0 (the ortho fast path keys heights out of
86 /// x/y) and on the globe/Moon paths.
87 pub pivot_dp: f64,
88 /// Seconds since an arbitrary epoch, forwarded from the host's per-frame `frameTimeNanos`.
89 ///
90 /// **Bounded to `[0, `[`CLOCK_WRAP_SECONDS`]`)` and wraps** — see [`CLOCK_WRAP_NANOS`] for
91 /// why. Anything measuring an elapsed time against it has to take the difference modulo
92 /// the period, or a stamp taken just before a wrap reads as an hour in the future.
93 ///
94 /// Not part of the projection — it never enters a matrix, so it changes no camera test —
95 /// but it rides on the camera because it is the other thing that arrives exactly once per
96 /// frame. The renderer forwards it to shaders through the `Push.misc.w` slot; the animated
97 /// workstreams (dash phase, LOD morph, vehicles) read it there.
98 pub time_seconds: f32,
99}
100
101/// The period [`Camera::time_seconds`] is reduced modulo, in nanoseconds.
102///
103/// The host's `frameTimeNanos` is a boot-relative clock that grows without bound, and
104/// `time_seconds` is an `f32` with ~7 significant digits — so after a long uptime the raw
105/// value would quantise to tens of milliseconds and coarsen every animation that reads it.
106/// Reducing it first keeps the resolution; the cost is that the clock wraps, which every
107/// reader has to allow for.
108pub const CLOCK_WRAP_NANOS: i64 = 3_600_000_000_000;
109
110/// [`CLOCK_WRAP_NANOS`] in seconds: the period of [`Camera::time_seconds`].
111///
112/// An elapsed time against that clock is `(now - then).rem_euclid(CLOCK_WRAP_SECONDS)`. A
113/// plain subtraction is wrong across a wrap, and wrong by an entire period rather than
114/// slightly — which reads as a stamp an hour in the future rather than a moment in the past.
115pub const CLOCK_WRAP_SECONDS: f32 = 3600.0;
116
117/// A point in Web Mercator world pixels at some zoom.
118#[derive(Clone, Copy, Debug, PartialEq)]
119pub struct WorldPx {
120 pub x: f64,
121 pub y: f64,
122}
123
124/// The tilt-dependent constants of the perspective projection, computed once per matrix.
125///
126/// Only built on the pitched path; the ortho fast-path never touches it. `d` is the
127/// camera-to-centre distance and cancels at pitch 0, so its only job is setting how strong
128/// the foreshortening is; `fx`/`fy` are focal terms; `depth_a`/`depth_b` map view distance to
129/// Vulkan's `[0, 1]` clip depth (`ndc_z = depth_a - depth_b/w`).
130#[derive(Clone, Copy)]
131pub(crate) struct Perspective {
132 pub(crate) fx: f64,
133 pub(crate) fy: f64,
134 pub(crate) d: f64,
135 pub(crate) depth_a: f64,
136 pub(crate) depth_b: f64,
137}
138
139/// Total map width and height in logical px at `zoom`.
140pub fn world_size(zoom: f64) -> f64 {
141 TILE_SIZE * 2f64.powf(zoom)
142}
143
144/// Project lon/lat degrees to world px at `zoom`.
145pub fn project(lon: f64, lat: f64, zoom: f64) -> WorldPx {
146 let size = world_size(zoom);
147 // Mercator y is undefined at the poles; this is the standard web-mapping clamp
148 // and the same constant `Mercator.kt` uses.
149 let lat = lat.clamp(-85.051_128_78, 85.051_128_78);
150 let x = (lon + 180.0) / 360.0 * size;
151 let sin_lat = (lat * std::f64::consts::PI / 180.0).sin();
152 let y = (0.5 - ((1.0 + sin_lat) / (1.0 - sin_lat)).ln() / (4.0 * std::f64::consts::PI)) * size;
153 WorldPx { x, y }
154}
155
156/// Inverse of [`project`].
157pub fn unproject(x: f64, y: f64, zoom: f64) -> (f64, f64) {
158 let size = world_size(zoom);
159 let lon = x / size * 360.0 - 180.0;
160 let n = std::f64::consts::PI - 2.0 * std::f64::consts::PI * y / size;
161 let lat = n.sinh().atan() * 180.0 / std::f64::consts::PI;
162 (lon, lat)
163}
164
165/// Past this zoom the sphere is sub-pixel from flat, so [`Camera::tile_to_clip`]
166/// and the Kotlin `Projection` both take the flat path bit-identically. Must stay
167/// in step with the Kotlin `GLOBE_DETAIL_ZOOM`.
168pub const GLOBE_FLAT_THRESHOLD: f64 = 8.0;
169
170/// Zoom at which [`globe_radius`] starts blending from the half-world sphere toward the flat
171/// map's scale. Must stay in step with the Kotlin `GLOBE_BLEND_START_ZOOM`.
172pub const GLOBE_BLEND_START: f64 = 5.0;
173
174/// Screen radius of the globe in Dp, for a camera at `zoom` centred on `center_lat`.
175///
176/// Zoomed out (below [`GLOBE_BLEND_START`]) it is half the world width, so the sphere shows
177/// half the planet across its diameter and fills the screen. By [`GLOBE_FLAT_THRESHOLD`] it
178/// must match the flat Mercator scale at the centre — `world / (2 * pi * cos(lat))` — or the
179/// switch to the flat map jumps about 1.65 zoom levels. Between the two the factor blends
180/// geometrically. Mirrors the Kotlin `globeRadius`.
181pub fn globe_radius(zoom: f64, center_lat: f64) -> f64 {
182 let t =
183 ((zoom - GLOBE_BLEND_START) / (GLOBE_FLAT_THRESHOLD - GLOBE_BLEND_START)).clamp(0.0, 1.0);
184 let cos = center_lat.to_radians().cos().max(0.05);
185 let to_flat = 1.0 / (std::f64::consts::PI * cos);
186 world_size(zoom) / 2.0 * to_flat.powf(t)
187}
188
189/// Whether this camera draws the globe: the flag on, and close enough out that
190/// the sphere reads as a sphere rather than as the flat map.
191pub fn globe_active(camera: &Camera) -> bool {
192 camera.globe && camera.zoom < GLOBE_FLAT_THRESHOLD
193}
194
195/// Whether this frame draws the Moon: Moon selected *and* the globe active.
196/// Below the threshold the Moon reads as Earth (flat vector path), so a
197/// zoomed-in Moon never shows a stale raster.
198pub fn moon_active(camera: &Camera) -> bool {
199 camera.moon && globe_active(camera)
200}
201
202/// 3D unit-sphere point of (`lon`, `lat`) in the basis facing the camera centre:
203/// the centre maps to (0, 0, 1), east is +x, north is +y, the far side is z < 0.
204/// Mirrors the Kotlin `globePoint`, which must stay in step.
205pub fn globe_point(center_lon: f64, center_lat: f64, lon: f64, lat: f64) -> (f64, f64, f64) {
206 use std::f64::consts::PI;
207 let lat_r = lat * PI / 180.0;
208 let d_lon = (lon - center_lon) * PI / 180.0;
209 let c_lat_r = center_lat * PI / 180.0;
210 let (sy, cy) = (c_lat_r.sin(), c_lat_r.cos());
211 let cos_lat = lat_r.cos();
212 let sin_lat = lat_r.sin();
213 let x = cos_lat * d_lon.sin();
214 let y = cy * sin_lat - sy * cos_lat * d_lon.cos();
215 let z = sy * sin_lat + cy * cos_lat * d_lon.cos();
216 (x, y, z)
217}
218
219/// Inverse of [`globe_point`]: the lon/lat of a unit-sphere point in the
220/// centre-facing basis. Mirrors the Kotlin `globeLonLat`.
221pub fn globe_lonlat(center_lon: f64, center_lat: f64, x: f64, y: f64, z: f64) -> (f64, f64) {
222 use std::f64::consts::PI;
223 let c_lat_r = center_lat * PI / 180.0;
224 let (sy, cy) = (c_lat_r.sin(), c_lat_r.cos());
225 let ex = x;
226 let ey = cy * y + sy * z;
227 let ez = -sy * y + cy * z;
228 let lat = ey.clamp(-1.0, 1.0).asin() * 180.0 / PI;
229 let lon = center_lon + ex.atan2(ez) * 180.0 / PI;
230 // Wrap to -180..180.
231 let lon = ((lon + 180.0) % 360.0 + 360.0) % 360.0 - 180.0;
232 (lon, lat.clamp(-90.0, 90.0))
233}