1use crate::constants;
8use crate::error::Error;
9use crate::math::{clamp_f64, rad2deg, wrap};
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum WrapMode {
13 Unwrapped,
14 Wrapped,
15}
16
17#[derive(Clone, Copy, Debug, PartialEq, mln_wire::Wire)]
18pub struct LatLng {
19 lat: f64,
20 lon: f64,
21}
22
23impl Default for LatLng {
24 fn default() -> Self {
25 LatLng { lat: 0.0, lon: 0.0 }
26 }
27}
28
29fn lat_(z: u8, y: i64) -> f64 {
30 let n = std::f64::consts::PI - 2.0 * std::f64::consts::PI * y as f64 / 2.0f64.powf(f64::from(z));
31 rad2deg((0.5 * (n.exp() - (-n).exp())).atan())
32}
33
34fn lon_(z: u8, x: i64) -> f64 {
35 x as f64 / 2.0f64.powf(f64::from(z)) * constants::DEGREES_MAX - constants::LONGITUDE_MAX
36}
37
38impl LatLng {
39 pub fn new(lat: f64, lon: f64) -> Result<Self, Error> {
42 Self::with_mode(lat, lon, WrapMode::Unwrapped)
43 }
44
45 pub fn with_mode(lat: f64, lon: f64, mode: WrapMode) -> Result<Self, Error> {
46 if lat.is_nan() {
47 return Err(Error::invalid_argument("latitude must not be NaN"));
48 }
49 if lon.is_nan() {
50 return Err(Error::invalid_argument("longitude must not be NaN"));
51 }
52 if lat.abs() > 90.0 {
53 return Err(Error::invalid_argument("latitude must be between -90 and 90"));
54 }
55 if !lon.is_finite() {
56 return Err(Error::invalid_argument("longitude must not be infinite"));
57 }
58 let mut result = LatLng { lat, lon };
59 if mode == WrapMode::Wrapped {
60 result.wrap();
61 }
62 Ok(result)
63 }
64
65 #[must_use]
69 pub fn saturating(lat: f64, lon: f64, mode: WrapMode) -> Self {
70 let lat = if lat.is_nan() { 0.0 } else { lat.clamp(-90.0, 90.0) };
71 let lon = if lon.is_nan() { 0.0 } else { lon.clamp(f64::MIN, f64::MAX) };
72 let mut result = LatLng { lat, lon };
73 if mode == WrapMode::Wrapped {
74 result.wrap();
75 }
76 result
77 }
78
79 pub(crate) const fn new_unchecked(lat: f64, lon: f64) -> Self {
81 LatLng { lat, lon }
82 }
83
84 #[must_use]
85 pub fn from_unwrapped_tile(z: u8, x: u32, y: u32, wrap: i16) -> Self {
86 LatLng::new_unchecked(lat_(z, i64::from(y)), lon_(z, i64::from(x)) + f64::from(wrap) * constants::DEGREES_MAX)
87 }
88
89 #[must_use]
90 pub fn latitude(&self) -> f64 {
91 self.lat
92 }
93
94 #[must_use]
95 pub fn longitude(&self) -> f64 {
96 self.lon
97 }
98
99 #[must_use]
100 pub fn wrapped(&self) -> LatLng {
101 let mut r = *self;
102 r.wrap();
103 r
104 }
105
106 pub fn wrap(&mut self) {
107 self.lon = wrap(self.lon, -constants::LONGITUDE_MAX, constants::LONGITUDE_MAX);
108 }
109
110 pub fn unwrap_for_shortest_path(&mut self, end: &LatLng) {
113 let delta = (end.lon - self.lon).abs();
114 if delta <= constants::LONGITUDE_MAX || delta >= constants::DEGREES_MAX {
115 return;
116 }
117 if self.lon > 0.0 && end.lon < 0.0 {
118 self.lon -= constants::DEGREES_MAX;
119 } else if self.lon < 0.0 && end.lon > 0.0 {
120 self.lon += constants::DEGREES_MAX;
121 }
122 }
123}
124
125#[derive(Clone, Copy, Debug)]
126pub struct LatLngBounds {
127 sw: LatLng,
128 ne: LatLng,
129 bounded: bool,
130}
131
132impl LatLngBounds {
133 const fn from_corners(sw: LatLng, ne: LatLng) -> Self {
134 LatLngBounds { sw, ne, bounded: true }
135 }
136
137 #[must_use]
139 pub fn world() -> Self {
140 LatLngBounds::from_corners(LatLng::new_unchecked(-90.0, -180.0), LatLng::new_unchecked(90.0, 180.0))
141 }
142
143 #[must_use]
145 pub fn singleton(a: LatLng) -> Self {
146 LatLngBounds::from_corners(a, a)
147 }
148
149 #[must_use]
152 pub fn hull(a: LatLng, b: LatLng) -> Self {
153 let mut bounds = LatLngBounds::from_corners(a, a);
154 bounds.extend(&b);
155 bounds
156 }
157
158 #[must_use]
161 pub fn empty() -> Self {
162 let mut bounds = Self::world();
163 std::mem::swap(&mut bounds.sw, &mut bounds.ne);
164 bounds
165 }
166
167 #[must_use]
173 pub fn infinite() -> Self {
174 LatLngBounds {
175 sw: LatLng::new_unchecked(-90.0, -180.0),
176 ne: LatLng::new_unchecked(90.0, 180.0),
177 bounded: false,
178 }
179 }
180
181 #[must_use]
183 pub fn from_canonical_tile(z: u8, x: u32, y: u32) -> Self {
184 LatLngBounds::from_corners(
185 LatLng::new_unchecked(lat_(z, i64::from(y) + 1), lon_(z, i64::from(x))),
186 LatLng::new_unchecked(lat_(z, i64::from(y)), lon_(z, i64::from(x) + 1)),
187 )
188 }
189
190 #[must_use]
191 pub fn valid(&self) -> bool {
192 (self.sw.latitude() <= self.ne.latitude()) && (self.sw.longitude() <= self.ne.longitude())
193 }
194
195 #[must_use]
196 pub fn south(&self) -> f64 {
197 self.sw.latitude()
198 }
199 #[must_use]
200 pub fn west(&self) -> f64 {
201 self.sw.longitude()
202 }
203 #[must_use]
204 pub fn north(&self) -> f64 {
205 self.ne.latitude()
206 }
207 #[must_use]
208 pub fn east(&self) -> f64 {
209 self.ne.longitude()
210 }
211
212 #[must_use]
213 pub fn southwest(&self) -> LatLng {
214 self.sw
215 }
216 #[must_use]
217 pub fn northeast(&self) -> LatLng {
218 self.ne
219 }
220 #[must_use]
221 pub fn southeast(&self) -> LatLng {
222 LatLng::new_unchecked(self.south(), self.east())
223 }
224 #[must_use]
225 pub fn northwest(&self) -> LatLng {
226 LatLng::new_unchecked(self.north(), self.west())
227 }
228
229 #[must_use]
230 pub fn center(&self) -> LatLng {
231 LatLng::new_unchecked(
234 f64::midpoint(self.sw.latitude(), self.ne.latitude()),
235 f64::midpoint(self.sw.longitude(), self.ne.longitude()),
236 )
237 }
238
239 #[must_use]
240 pub fn constrain(&self, p: &LatLng) -> LatLng {
241 if !self.bounded {
242 return *p;
243 }
244
245 let mut lat = p.latitude();
246 let mut lng = p.longitude();
247
248 if !self.contains_latitude(lat) {
249 lat = clamp_f64(lat, self.south(), self.north());
250 }
251
252 if !self.contains_longitude(lng, WrapMode::Unwrapped) {
253 lng = clamp_f64(lng, self.west(), self.east());
254 }
255
256 LatLng::new_unchecked(lat, lng)
257 }
258
259 pub fn extend(&mut self, point: &LatLng) {
260 self.sw = LatLng::new_unchecked(
261 f64::min(point.latitude(), self.sw.latitude()),
262 f64::min(point.longitude(), self.sw.longitude()),
263 );
264 self.ne = LatLng::new_unchecked(
265 f64::max(point.latitude(), self.ne.latitude()),
266 f64::max(point.longitude(), self.ne.longitude()),
267 );
268 }
269
270 #[must_use]
271 pub fn is_empty(&self) -> bool {
272 self.sw.latitude() > self.ne.latitude() || self.sw.longitude() > self.ne.longitude()
273 }
274
275 #[must_use]
276 pub fn crosses_antimeridian(&self) -> bool {
277 self.sw.wrapped().longitude() > self.ne.wrapped().longitude()
278 }
279
280 #[must_use]
281 pub fn contains(&self, point: &LatLng) -> bool {
282 self.contains_with_mode(point, WrapMode::Unwrapped)
283 }
284
285 #[must_use]
286 pub fn contains_with_mode(&self, point: &LatLng, wrap: WrapMode) -> bool {
287 self.contains_latitude(point.latitude()) && self.contains_longitude(point.longitude(), wrap)
288 }
289
290 fn contains_latitude(&self, latitude: f64) -> bool {
291 latitude >= self.south() && latitude <= self.north()
292 }
293
294 fn contains_longitude(&self, longitude: f64, wrap: WrapMode) -> bool {
295 if longitude >= self.west() && longitude <= self.east() {
296 return true;
297 }
298
299 if wrap == WrapMode::Wrapped {
300 let wrapped = LatLngBounds::from_corners(self.sw.wrapped(), self.ne.wrapped());
301 let longitude = crate::math::wrap(longitude, -constants::LONGITUDE_MAX, constants::LONGITUDE_MAX);
302 if self.crosses_antimeridian() {
303 return (longitude >= -constants::LONGITUDE_MAX && longitude <= wrapped.east())
304 || (longitude >= wrapped.west() && longitude <= constants::LONGITUDE_MAX);
305 }
306
307 return longitude >= wrapped.west() && longitude <= wrapped.east();
308 }
309
310 false
311 }
312}
313
314impl Default for LatLngBounds {
315 fn default() -> Self {
316 Self::infinite()
317 }
318}
319
320impl PartialEq for LatLngBounds {
321 fn eq(&self, b: &LatLngBounds) -> bool {
322 (!self.bounded && !b.bounded) || (self.bounded && b.bounded && self.sw == b.sw && self.ne == b.ne)
323 }
324}
325
326#[cfg(test)]
327mod tests {
328 use approx::assert_abs_diff_eq;
329
330 use super::*;
331 use crate::constants::{LATITUDE_MAX, LONGITUDE_MAX};
332
333 fn ll(lat: f64, lon: f64) -> LatLng {
334 LatLng::new(lat, lon).unwrap()
335 }
336
337 #[test]
338 fn invalid_coordinates_fail_with_a_message() {
339 for (lat, lon, message) in [
340 (f64::NAN, 0.0, "latitude must not be NaN"),
341 (0.0, f64::NAN, "longitude must not be NaN"),
342 (91.0, 0.0, "latitude must be between -90 and 90"),
343 (0.0, f64::INFINITY, "longitude must not be infinite"),
344 ] {
345 assert_eq!(LatLng::new(lat, lon), Err(Error::invalid_argument(message)), "{lat}, {lon}");
346 }
347 assert_eq!(ll(45.0, 190.0).longitude(), 190.0);
348 }
349
350 #[test]
351 fn saturating_clamps_and_zeroes_what_new_rejects() {
352 let lat_lng = LatLng::saturating(f64::NAN, f64::INFINITY, WrapMode::Unwrapped);
353 assert_eq!((0.0, f64::MAX), (lat_lng.latitude(), lat_lng.longitude()));
354 let lat_lng = LatLng::saturating(-100.0, f64::NAN, WrapMode::Unwrapped);
355 assert_eq!((-90.0, 0.0), (lat_lng.latitude(), lat_lng.longitude()));
356 assert_eq!(190.0 - 360.0, LatLng::saturating(0.0, 190.0, WrapMode::Wrapped).longitude());
357 }
358
359 #[test]
360 fn wrapping_brings_a_longitude_within_180() {
361 for (lon, wrapped) in
362 [(-180.1, 179.9), (180.9, -179.1), (190.0, -170.0), (-360.5, -0.5), (360.5, 0.5), (360_000.5, 0.5)]
363 {
364 assert_abs_diff_eq!(ll(0.0, lon).wrapped().longitude(), wrapped, epsilon = 1e-9);
365 assert_abs_diff_eq!(
366 LatLng::with_mode(0.0, lon, WrapMode::Wrapped).unwrap().longitude(),
367 wrapped,
368 epsilon = 1e-9
369 );
370 }
371 }
372
373 #[test]
374 fn a_tiles_corner_and_bounds() {
375 for (z, x, y, wrap, lat, lon) in [
376 (0, 0, 0, 0, LATITUDE_MAX, -LONGITUDE_MAX),
377 (19, 0, 0, 0, LATITUDE_MAX, -LONGITUDE_MAX),
378 (0, 0, 0, 1, LATITUDE_MAX, LONGITUDE_MAX),
379 (0, 0, 0, -1, LATITUDE_MAX, -540.0),
380 ] {
381 let corner = LatLng::from_unwrapped_tile(z, x, y, wrap);
382 assert_abs_diff_eq!(&[corner.latitude(), corner.longitude()][..], &[lat, lon][..], epsilon = 1e-9);
383 }
384 for ((z, x, y), west_south_east_north) in [
385 ((0, 0, 0), [-LONGITUDE_MAX, -LATITUDE_MAX, LONGITUDE_MAX, LATITUDE_MAX]),
386 ((1, 0, 1), [-LONGITUDE_MAX, -LATITUDE_MAX, 0.0, 0.0]),
387 ((1, 1, 1), [0.0, -LATITUDE_MAX, LONGITUDE_MAX, 0.0]),
388 ((1, 0, 0), [-LONGITUDE_MAX, 0.0, 0.0, LATITUDE_MAX]),
389 ] {
390 let bounds = LatLngBounds::from_canonical_tile(z, x, y);
391 let edges = [bounds.west(), bounds.south(), bounds.east(), bounds.north()];
392 assert_abs_diff_eq!(&edges[..], &west_south_east_north[..], epsilon = 1e-9);
393 }
394 }
395
396 #[test]
397 fn hull_spans_two_opposite_corners_in_either_order() {
398 let (s, w, n, e) = (1.0, 2.0, 3.0, 4.0);
399 for (a, b) in [(ll(s, w), ll(n, e)), (ll(n, e), ll(s, w)), (ll(s, e), ll(n, w)), (ll(n, w), ll(s, e))] {
400 let bounds = LatLngBounds::hull(a, b);
401 assert_eq!([bounds.south(), bounds.west(), bounds.north(), bounds.east()], [s, w, n, e], "{a:?}, {b:?}");
402 assert_eq!(
403 [bounds.southwest(), bounds.southeast(), bounds.northeast(), bounds.northwest(), bounds.center()],
404 [ll(s, w), ll(s, e), ll(n, e), ll(n, w), ll(2.0, 3.0)]
405 );
406 }
407 let singleton = LatLngBounds::singleton(ll(s, w));
408 assert_eq!([singleton.south(), singleton.west(), singleton.north(), singleton.east()], [s, w, s, w]);
409 let world = LatLngBounds::world();
410 assert_eq!([world.south(), world.west(), world.north(), world.east()], [-90.0, -180.0, 90.0, 180.0]);
411 assert!(LatLngBounds::empty().is_empty());
412 assert!(!world.is_empty());
413 }
414
415 #[test]
416 fn extending_empty_bounds_covers_the_points() {
417 let mut b = LatLngBounds::empty();
418 assert!(!b.valid());
419 b.extend(&LatLng::new(10.0, 20.0).unwrap());
420 b.extend(&LatLng::new(-10.0, -20.0).unwrap());
421 assert!(b.valid());
422 assert!(b.contains(&LatLng::new(0.0, 0.0).unwrap()));
423 assert!(!b.contains(&LatLng::new(11.0, 0.0).unwrap()));
424 }
425
426 #[test]
429 fn contains_a_point_between_its_edges_or_wrapped_into_them() {
430 let within_100 = LatLngBounds::hull(ll(50.0, -100.0), ll(-50.0, 100.0));
431 let within_160 = LatLngBounds::hull(ll(50.0, -160.0), ll(-50.0, 160.0));
432 let across_antimeridian = LatLngBounds::hull(ll(50.0, -200.0), ll(-50.0, -160.0));
433 for (bounds, point, unwrapped, wrapped) in [
434 (within_100, ll(0.0, -100.0), true, true),
435 (within_100, ll(-50.0, 100.0), true, true),
436 (within_100, ll(0.0, 170.0), false, false),
437 (within_100, ll(0.0, 365.0), false, true),
438 (within_160, ll(0.0, 170.0), false, false),
439 (within_160, ll(0.0, -170.0), false, false),
440 (across_antimeridian, ll(0.0, -170.0), true, true),
441 (across_antimeridian, ll(0.0, 170.0), false, true),
442 (across_antimeridian, ll(0.0, 190.0), false, true),
443 (across_antimeridian, ll(0.0, 541.0), false, true),
444 ] {
445 assert_eq!(bounds.contains(&point), unwrapped, "{bounds:?} {point:?}");
446 assert_eq!(bounds.contains_with_mode(&point, WrapMode::Wrapped), wrapped, "{bounds:?} {point:?} wrapped");
447 }
448 }
449
450 #[test]
453 fn infinite_bounds_contain_what_the_world_does() {
454 let b = LatLngBounds::infinite();
455 assert!(!b.contains(&LatLng::new(0.0, 200.0).unwrap()));
456 assert_eq!(b.constrain(&ll(0.0, 200.0)), ll(0.0, 200.0));
457 assert_eq!(LatLngBounds::infinite(), LatLngBounds::default());
458 assert_ne!(LatLngBounds::infinite(), LatLngBounds::world());
459 }
460}