mln-rs-style 0.0.21

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! The world square a map draws in, which tile 0/0/0 covers and the quad tree
//! of tiles subdivides, and how lng/lat maps to and from it: Web Mercator, or
//! the coordinate reference system of a registered projection.

use std::f64::consts::PI;
use std::sync::Arc;

use geometry::Point;
use mln_wire::Wire;

use super::mapping::{BoxSamples, CrsMapping, WorldBox};
use super::{Crs, NO_ANSWER, TileMatrixSet, is_answer};
use crate::constants::{DEGREES_MAX, EARTH_RADIUS_M, LATITUDE_MAX, TILE_SIZE_D};
use crate::error::Error;
use crate::geo::{LatLng, LatLngBounds, WrapMode};
use crate::math::{clamp_f64, deg2rad, rad2deg};

/// How a map's lng/lat maps to and from its world square, where tile 0/0/0
/// spans 0 to 1 on both axes and y grows down: Web Mercator's, the default,
/// or a registered projection's.
///
/// Each mapping converts positions in batches its own way, and has its own
/// properties: whether its world wraps, the latitudes it keeps, its tile
/// matrix set, and the scales of its ground and its heights. Everything else
/// is the same for every mapping. Two mappings are equal when they are the
/// same one: Mercator, or the same registered projection's.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct WorldMapping(Plane);

/// The plane that a [`WorldMapping`] maps lng/lat to.
#[derive(Clone, Debug, Default)]
enum Plane {
    /// Web Mercator, whose world repeats east and west.
    #[default]
    Mercator,
    /// A registered projection's coordinate reference system: a bounded
    /// plane, with no world copies and no wrapping.
    Crs(Arc<CrsMapping>),
}

impl PartialEq for Plane {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Plane::Mercator, Plane::Mercator) => true,
            (Plane::Crs(a), Plane::Crs(b)) => Arc::ptr_eq(a, b),
            _ => false,
        }
    }
}

impl Eq for Plane {}

/// Web Mercator's mapping, the default, for code that needs a reference to
/// it.
pub static MERCATOR: WorldMapping = WorldMapping(Plane::Mercator);

impl WorldMapping {
    /// A mapping of the registered projection `crs`, equal only to its
    /// clones. A registry makes one for each of its projections, which every
    /// map drawn in it shares.
    #[must_use]
    pub fn new(crs: Arc<Crs>) -> WorldMapping {
        WorldMapping(Plane::Crs(Arc::new(CrsMapping::new(crs))))
    }

    /// `mercator`, or the registered projection's name.
    #[must_use]
    pub fn name(&self) -> &str {
        match &self.0 {
            Plane::Mercator => "mercator",
            Plane::Crs(mapping) => &mapping.crs().name,
        }
    }

    /// Whether the world repeats east and west, with world copies and
    /// longitude wrapping.
    #[must_use]
    pub fn wraps(&self) -> bool {
        matches!(self.0, Plane::Mercator)
    }

    /// The latitudes, south and north, that the world keeps: Mercator's
    /// limit, past which it puts every location on the square's edge, or a
    /// registered projection's range, from the center of its tile matrix
    /// set toward each pole up to where the projection stretches distances
    /// along the meridian ten times as much as at the center, found once,
    /// when first asked for.
    #[must_use]
    pub fn latitude_range(&self) -> [f64; 2] {
        match &self.0 {
            Plane::Mercator => [-LATITUDE_MAX, LATITUDE_MAX],
            Plane::Crs(mapping) => mapping.latitude_range(),
        }
    }

    /// `lat_lng` in the world copy that longitudes from -180 to 180 cover,
    /// where the world wraps; unchanged where it doesn't.
    #[must_use]
    pub fn wrap(&self, lat_lng: LatLng) -> LatLng {
        if self.wraps() { lat_lng.wrapped() } else { lat_lng }
    }

    /// The tile grid whose tile 0/0/0 is the world square:
    /// [`TileMatrixSet::WEB_MERCATOR`] on Mercator.
    #[must_use]
    pub fn tile_matrix_set(&self) -> TileMatrixSet {
        match &self.0 {
            Plane::Mercator => TileMatrixSet::WEB_MERCATOR,
            Plane::Crs(mapping) => mapping.crs().tile_matrix_set,
        }
    }

    /// Each lng/lat in degrees of `lng_lats` to its place in the world
    /// square, into `world`, which is as long: NaN where the projection has
    /// none. Mercator puts a latitude past its limit on the square's edge, as
    /// [`project`](Self::project) does and
    /// [`project_from_center`](Self::project_from_center) and
    /// [`places_from_lng_lats`](Self::places_from_lng_lats) don't.
    pub fn world_from_lng_lats(&self, lng_lats: &[[f64; 2]], world: &mut [[f64; 2]]) {
        match &self.0 {
            Plane::Mercator => mercator_places(lng_lats, world, mercator_latitude),
            Plane::Crs(mapping) => mapping.world_from_lng_lats(lng_lats, world),
        }
    }

    /// Each lng/lat in degrees of `lng_lats` to its place on the plane of the
    /// world square, into `places`, which is as long, as
    /// [`world_from_lng_lats`](Self::world_from_lng_lats) does, but on
    /// Mercator past its latitude limit too, outside the square, where the
    /// buffers of its edge tiles reach.
    pub fn places_from_lng_lats(&self, lng_lats: &[[f64; 2]], places: &mut [[f64; 2]]) {
        match &self.0 {
            Plane::Mercator => mercator_places(lng_lats, places, |latitude| latitude),
            Plane::Crs(mapping) => mapping.world_from_lng_lats(lng_lats, places),
        }
    }

    /// Each place in the world square of `world` to lng/lat in degrees, into
    /// `lng_lats`, which is as long, with the latitude within 90 degrees of
    /// the equator. A registered projection's place that has no answer of its
    /// own takes the nearest one inside the world square, or else the last
    /// one with an answer on the line to the square's center, or else the
    /// converter's own finite answer there, as GL JS's
    /// [`CRSWorldCoordinateHelper.lngLatFromWorld`](https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/geo/projection/crs.ts#L112-L120)
    /// does; NaN where there is none of these.
    pub fn lng_lats_from_world(&self, world: &[[f64; 2]], lng_lats: &mut [[f64; 2]]) {
        match &self.0 {
            Plane::Mercator => {
                for (lng_lat, point) in lng_lats.iter_mut().zip(world) {
                    let answer = mercator_lng_lat(*point);
                    *lng_lat = if is_answer(&answer) { answer } else { NO_ANSWER };
                }
            }
            Plane::Crs(mapping) => mapping.lng_lats_from_world(world, lng_lats),
        }
    }

    /// The place of `lat_lng` in the world square, NaN where the projection
    /// has none.
    #[must_use]
    pub fn world_from_lat_lng(&self, lat_lng: &LatLng) -> Point<f64> {
        let mut world = [[0.0; 2]];
        self.world_from_lng_lats(&[[lat_lng.longitude(), lat_lng.latitude()]], &mut world);
        Point::new(world[0][0], world[0][1])
    }

    /// The location of a place in the world square, as
    /// [`lng_lats_from_world`](Self::lng_lats_from_world) finds it. Fails
    /// with [`ErrorKind::InvalidArgument`](crate::error::ErrorKind) where it
    /// finds none.
    pub fn lat_lng_from_world(&self, world: &Point<f64>) -> Result<LatLng, Error> {
        let mut lng_lat = [[0.0; 2]];
        self.lng_lats_from_world(&[[world.x, world.y]], &mut lng_lat);
        if !is_answer(&lng_lat[0]) {
            return Err(Error::invalid_argument(format!(
                "the projection \"{}\" has no location at the world position {}, {}",
                self.name(),
                world.x,
                world.y
            )));
        }
        LatLng::with_mode(lng_lat[0][1], lng_lat[0][0], WrapMode::Unwrapped)
    }

    /// The point of `lat_lng` in a world `scale` times the tile size wide, a
    /// latitude past Mercator's limit on the square's edge.
    #[must_use]
    pub fn project(&self, lat_lng: &LatLng, scale: f64) -> Point<f64> {
        let world_size = scale * TILE_SIZE_D;
        let world = self.world_from_lat_lng(lat_lng);
        Point::new(world.x * world_size, world.y * world_size)
    }

    /// The location of a point in a world `scale` times the tile size wide,
    /// in the world copy that `wrap_mode` asks for where the world wraps.
    /// Fails as [`lat_lng_from_world`](Self::lat_lng_from_world) does.
    pub fn unproject(&self, point: &Point<f64>, scale: f64, wrap_mode: WrapMode) -> Result<LatLng, Error> {
        let world_size = scale * TILE_SIZE_D;
        let lat_lng = self.lat_lng_from_world(&Point::new(point.x / world_size, point.y / world_size))?;
        Ok(if wrap_mode == WrapMode::Wrapped { self.wrap(lat_lng) } else { lat_lng })
    }

    /// The place of `lat_lng` in a world `scale` times the tile size wide,
    /// measured from the world square's center, with y down, where a
    /// camera keeps its center: measured from the center, a location near it
    /// keeps the precision that the offset of the square's corner would
    /// round away. On Mercator it goes past the latitude limit too, as the
    /// globe's center and an unconstrained one do, up to a finite distance
    /// past the square's edge at the poles. NaN where the projection has no
    /// place for it.
    #[must_use]
    pub fn project_from_center(&self, lat_lng: &LatLng, scale: f64) -> Point<f64> {
        let world_size = scale * TILE_SIZE_D;
        if let Plane::Mercator = self.0 {
            return Point::new(
                lat_lng.longitude() / DEGREES_MAX * world_size,
                -mercator_north(lat_lng.latitude()) / (PI * 2.0) * world_size,
            );
        }
        let place = self.world_from_lat_lng(lat_lng);
        Point::new((place.x - 0.5) * world_size, (place.y - 0.5) * world_size)
    }

    /// The location of a place in a world `scale` times the tile size wide,
    /// measured from the world square's center, as
    /// [`project_from_center`](Self::project_from_center) measures it, in the
    /// world copy that `wrap_mode` asks for where the world wraps. A place of
    /// a registered projection without a location of its own takes the one
    /// that [`lng_lats_from_world`](Self::lng_lats_from_world) falls back on,
    /// and a coordinate that is NaN where there is none is
    /// [`LatLng::saturating`]'s.
    #[must_use]
    pub fn unproject_from_center(&self, point: &Point<f64>, scale: f64, wrap_mode: WrapMode) -> LatLng {
        let world_size = scale * TILE_SIZE_D;
        if let Plane::Mercator = self.0 {
            let longitude = point.x / world_size * DEGREES_MAX;
            let latitude = mercator_latitude_at(-point.y / world_size * (PI * 2.0));
            return LatLng::saturating(latitude, longitude, wrap_mode);
        }
        let mut lng_lat = [[0.0; 2]];
        self.lng_lats_from_world(&[[0.5 + point.x / world_size, 0.5 + point.y / world_size]], &mut lng_lat);
        LatLng::saturating(lng_lat[0][1], lng_lat[0][0], WrapMode::Unwrapped)
    }

    /// Whether a place in the world square has a location of its own,
    /// rather than the nearest one that
    /// [`lng_lats_from_world`](Self::lng_lats_from_world) falls back on:
    /// always on Mercator.
    #[must_use]
    pub fn has_lat_lng(&self, world: &Point<f64>) -> bool {
        match &self.0 {
            Plane::Mercator => true,
            Plane::Crs(mapping) => mapping.has_lat_lng([world.x, world.y]),
        }
    }

    /// How many meters of height a world unit stands for at `lat_lng`, the
    /// scale that the map draws heights at there, such as terrain,
    /// extrusions and the camera's altitude: on Mercator, the ground meters
    /// a world unit spans at its latitude, so that heights match the ground;
    /// in a registered projection, the extent of its tile matrix set, its
    /// units taken as meters, anywhere.
    #[must_use]
    pub fn height_meters_per_world_unit(&self, lat_lng: &LatLng) -> f64 {
        match &self.0 {
            Plane::Mercator => mercator_meters_per_world_unit(lat_lng.latitude()),
            Plane::Crs(mapping) => mapping.crs().tile_matrix_set.extent_at_zoom0,
        }
    }

    /// How many meters on the ground a world unit spans at the lng/lat
    /// `lng_lat`, in degrees, along `step`, a short step in the world square
    /// from its place: on Mercator, the scale at its latitude, the same in
    /// every direction; in a registered projection, whose scale can change
    /// with the direction, the ground distance from `lng_lat` to the location
    /// at the step's end, on the sphere of GL JS's
    /// [`LngLat.distanceTo`](https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/geo/lng_lat.ts#L133-L140),
    /// over the step's length. NaN where the projection has no place for
    /// `lng_lat`.
    #[must_use]
    pub fn ground_meters_per_world_unit(&self, lng_lat: [f64; 2], step: [f64; 2]) -> f64 {
        let Plane::Crs(mapping) = &self.0 else {
            return mercator_meters_per_world_unit(lng_lat[1]);
        };
        let mut place = [[0.0; 2]];
        mapping.world_from_lng_lats(&[lng_lat], &mut place);
        let mut end = [[0.0; 2]];
        mapping.lng_lats_from_world(&[[place[0][0] + step[0], place[0][1] + step[1]]], &mut end);
        ground_distance(lng_lat, end[0]) / step[0].hypot(step[1])
    }

    /// The places in the world square of a lng/lat box sampled on a grid,
    /// 17 points on a side with its edges and corners, and how far its edges
    /// stray from the lines between neighboring samples, which a shape that
    /// holds the samples grows by to hold the box. Corners alone miss most of
    /// a box whose edges curve, as a parallel does around a pole, and the
    /// inside of the box matters where a projection runs off to infinity.
    #[must_use]
    pub fn lng_lat_box_samples(&self, bounds: &LatLngBounds) -> BoxSamples {
        BoxSamples::new(bounds, |lng_lats, world| self.world_from_lng_lats(lng_lats, world))
    }

    /// The rectangle in the world square around a lng/lat box, as
    /// [`BoxSamples::world_box`] finds it from the box's samples.
    #[must_use]
    pub fn lng_lat_box_to_world_box(&self, bounds: &LatLngBounds) -> WorldBox {
        self.lng_lat_box_samples(bounds).world_box()
    }
}

/// A mapping crosses as the name of its registered projection, or none for
/// Mercator's, and the reading side takes the mapping that the
/// [`StyleRegistry`](crate::StyleRegistry) in its context has by that name.
impl Wire for WorldMapping {
    fn write(&self, w: &mut mln_wire::Writer) {
        match &self.0 {
            Plane::Mercator => false.write(w),
            Plane::Crs(mapping) => {
                true.write(w);
                mln_wire::write_str(w, &mapping.crs().name);
            }
        }
    }

    fn read(r: &mut mln_wire::Reader<'_>) -> Option<Self> {
        if !bool::read(r)? {
            return Some(WorldMapping::default());
        }
        let name = mln_wire::read_str(r)?;
        let world = match r.context::<crate::StyleRegistry>() {
            None => Err("a projection without a registry to resolve it against"),
            Some(registry) => registry.projection(name).cloned().ok_or("unknown projection"),
        };
        match world {
            Ok(world) => Some(world),
            Err(message) => r.fail(message),
        }
    }
}

/// The earth's mean radius in meters, GL JS's
/// [`earthRadius`](https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/geo/lng_lat.ts#L8),
/// on which its `LngLat.distanceTo` measures.
const MEAN_EARTH_RADIUS_M: f64 = 6_371_008.8;

/// The ground distance in meters between two lng/lats in degrees, on the
/// sphere of GL JS's
/// [`LngLat.distanceTo`](https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/geo/lng_lat.ts#L133-L140):
/// by the haversine formula, which keeps the centimeters across a few pixels
/// at the highest zooms, where the spherical law of cosines of
/// `distanceTo` rounds them to nothing.
fn ground_distance([lng_a, lat_a]: [f64; 2], [lng_b, lat_b]: [f64; 2]) -> f64 {
    let (lat_a, lat_b) = (lat_a.to_radians(), lat_b.to_radians());
    let (half_latitude, half_longitude) = ((lat_b - lat_a) / 2.0, (lng_b - lng_a).to_radians() / 2.0);
    let haversine = half_latitude.sin().powi(2) + lat_a.cos() * lat_b.cos() * half_longitude.sin().powi(2);
    let chord = haversine.sqrt();
    // Rounding can take it past 1; a NaN stays NaN.
    2.0 * MEAN_EARTH_RADIUS_M * (if chord > 1.0 { 1.0 } else { chord }).asin()
}

/// `latitude` within Web Mercator's limit, past which Mercator puts every
/// location on the world square's edge.
fn mercator_latitude(latitude: f64) -> f64 {
    clamp_f64(latitude, -LATITUDE_MAX, LATITUDE_MAX)
}

/// How many meters on the ground a world unit of Web Mercator spans at
/// `latitude`, kept within Mercator's limit: the length of the parallel.
fn mercator_meters_per_world_unit(latitude: f64) -> f64 {
    deg2rad(mercator_latitude(latitude)).cos() * (PI * 2.0) * EARTH_RADIUS_M
}

/// How far north of the equator Web Mercator puts `latitude`, in degrees,
/// in a world 2π wide: asinh(tan φ), which is ln(tan(π/4 + φ/2)) and stays
/// finite at the poles.
fn mercator_north(latitude: f64) -> f64 {
    deg2rad(latitude).tan().asinh()
}

/// The latitude in degrees that Web Mercator puts `north` of the equator, in
/// a world 2π wide: the inverse of [`mercator_north`].
fn mercator_latitude_at(north: f64) -> f64 {
    rad2deg(north.sinh().atan())
}

/// Web Mercator's places of `lng_lats`, in degrees, into `places`, each
/// latitude through `latitude` first: NaN where a lng/lat isn't finite.
fn mercator_places(lng_lats: &[[f64; 2]], places: &mut [[f64; 2]], latitude: impl Fn(f64) -> f64) {
    for (place, &[lng, lat]) in places.iter_mut().zip(lng_lats) {
        *place = if is_answer(&[lng, lat]) { mercator_point([lng, latitude(lat)]) } else { NO_ANSWER };
    }
}

/// Web Mercator's place in the world square of a lng/lat in degrees.
fn mercator_point([longitude, latitude]: [f64; 2]) -> [f64; 2] {
    [0.5 + longitude / DEGREES_MAX, 0.5 - mercator_north(latitude) / (PI * 2.0)]
}

/// The lng/lat in degrees of a place in Web Mercator's world square, the
/// inverse of [`mercator_point`], NaN or infinite where the place is.
fn mercator_lng_lat([x, y]: [f64; 2]) -> [f64; 2] {
    [(x - 0.5) * DEGREES_MAX, mercator_latitude_at((0.5 - y) * (PI * 2.0))]
}