utiles_core/bbox.rs
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 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
//! Bounding-boxes!
use crate::lnglat::LngLat;
use crate::parsing::parse_bbox;
use crate::tile::Tile;
use crate::tile_like::TileLike;
use crate::{xy, Point2d};
use serde::{Deserialize, Serialize};
/// Bounding box tuple
#[derive(Debug, Clone, Copy, PartialEq, Deserialize, Serialize)]
pub struct BBoxTuple(f64, f64, f64, f64);
/// Bounding box struct
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
pub struct BBox {
/// west/left boundary
pub west: f64,
/// south/bottom boundary
pub south: f64,
/// east/right boundary
pub east: f64,
/// north/top boundary
pub north: f64,
}
/// Web Mercator Bounding box struct
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct WebBBox {
/// lower-left corner (west, south)/(left, bottom)
min: Point2d<f64>,
/// upper-right corner (east, north)/(right, top)
max: Point2d<f64>,
}
/// Bounding box containable enum
pub enum BBoxContainable {
/// `LngLat`
LngLat(LngLat),
/// `BBox`
BBox(BBox),
/// Tile
Tile(Tile),
}
impl From<(f64, f64, f64, f64)> for BBox {
fn from(bbox: (f64, f64, f64, f64)) -> Self {
BBox::new(bbox.0, bbox.1, bbox.2, bbox.3)
}
}
impl From<(i32, i32, i32, i32)> for BBox {
fn from(bbox: (i32, i32, i32, i32)) -> Self {
// convert to f64
let bbox = (
f64::from(bbox.0),
f64::from(bbox.1),
f64::from(bbox.2),
f64::from(bbox.3),
);
BBox {
north: bbox.0,
south: bbox.1,
east: bbox.2,
west: bbox.3,
}
}
}
impl BBox {
/// Create a new `BBox`
#[must_use]
pub fn new(west: f64, south: f64, east: f64, north: f64) -> Self {
BBox {
west,
south,
east,
north,
}
}
/// Returns a bounding box that covers the entire world.
#[must_use]
pub fn world_planet() -> Self {
BBox {
west: -180.0,
south: -90.0,
east: 180.0,
north: 90.0,
}
}
/// Returns a bounding box that covers the entire web mercator world.
#[must_use]
pub fn world_web() -> Self {
BBox {
west: -180.0,
south: -85.051_129,
east: 180.0,
north: 85.051_129,
}
}
#[must_use]
pub fn clamp_web(&self) -> Self {
BBox {
west: self.west.max(-180.0),
south: self.south.max(-85.051_129),
east: self.east.min(180.0),
north: self.north.min(85.051_129),
}
}
#[must_use]
pub fn clamp(&self, o: &BBox) -> Self {
BBox {
west: self.west.max(o.west),
south: self.south.max(o.south),
east: self.east.min(o.east),
north: self.north.min(o.north),
}
}
#[must_use]
pub fn geo_wrap(&self) -> Self {
let east = LngLat::geo_wrap_lng(self.east);
let west = LngLat::geo_wrap_lng(self.west);
BBox {
west,
south: self.south,
east,
north: self.north,
}
}
#[must_use]
pub fn is_antimeridian(&self) -> bool {
self.west > self.east
}
/// Returns true if the bounding box crosses the antimeridian (the 180-degree meridian).
#[must_use]
pub fn crosses_antimeridian(&self) -> bool {
self.west > self.east
}
/// Returns the bounding box as a tuple
#[must_use]
pub fn tuple(&self) -> (f64, f64, f64, f64) {
(self.west(), self.south(), self.east(), self.north())
}
/// Returns the top/north boundary of the bounding box
#[must_use]
pub fn north(&self) -> f64 {
self.north
}
/// Returns the bottom/south boundary of the bounding box
#[must_use]
pub fn south(&self) -> f64 {
self.south
}
/// Returns the right/east boundary of the bounding box
#[must_use]
pub fn east(&self) -> f64 {
self.east
}
/// Returns the left/west boundary of the bounding box
#[must_use]
pub fn west(&self) -> f64 {
self.west
}
/// Returns the top/north boundary of the bounding box
#[must_use]
pub fn top(&self) -> f64 {
self.north
}
/// Returns the bottom/south boundary of the bounding box
#[must_use]
pub fn bottom(&self) -> f64 {
self.south
}
/// Returns the right/east boundary of the bounding box
#[must_use]
pub fn right(&self) -> f64 {
self.east
}
/// Returns the left/west boundary of the bounding box
#[must_use]
pub fn left(&self) -> f64 {
self.west
}
/// Returns the geojson tuple/array representation of the bounding box
#[must_use]
#[inline]
pub fn json_arr(&self) -> String {
format!(
"[{},{},{},{}]",
self.west(),
self.south(),
self.east(),
self.north()
)
}
/// Returns the gdal-ish string representation of the bounding box
#[must_use]
#[inline]
pub fn projwin_str(&self) -> String {
format!(
"{} {} {} {}",
self.west(),
self.north(),
self.east(),
self.south()
)
}
/// Returns the center of the bounding box as a `LngLat`
#[must_use]
pub fn contains_lnglat(&self, lnglat: &LngLat) -> bool {
let lng = lnglat.lng();
let lat = lnglat.lat();
if self.crosses_antimeridian() {
if (lng >= self.west || lng <= self.east)
&& lat >= self.south
&& lat <= self.north
{
return true;
}
} else if lng >= self.west
&& lng <= self.east
&& lat >= self.south
&& lat <= self.north
{
return true;
}
false
}
/// Returns true if the current instance contains the given `Tile`
#[must_use]
pub fn contains_tile(&self, tile: &Tile) -> bool {
let bbox = tile.bbox();
self.contains_bbox(&bbox.into())
}
/// Returns true if the current instance contains the given `BBox`
#[must_use]
pub fn contains_bbox(&self, other: &BBox) -> bool {
if self.is_antimeridian() {
// BBox crosses the antimeridian
if other.is_antimeridian() {
// Other BBox also crosses the antimeridian
if self.west <= other.west && self.east >= other.east {
// The current BBox contains the other BBox
self.south <= other.south && self.north >= other.north
} else {
false
}
// Other BBox does not cross the antimeridian
} else if self.west <= other.west || self.east >= other.east {
// The current BBox contains the other BBox
self.south <= other.south && self.north >= other.north
} else {
false
}
} else {
self.north >= other.north
&& self.south <= other.south
&& self.east >= other.east
&& self.west <= other.west
}
}
/// Returns true if the current instance contains the given `BBoxContainable` object.
#[must_use]
pub fn contains(&self, other: &BBoxContainable) -> bool {
match other {
BBoxContainable::LngLat(lnglat) => self.contains_lnglat(lnglat),
BBoxContainable::BBox(bbox) => self.contains_bbox(bbox),
BBoxContainable::Tile(tile) => self.contains_tile(tile),
}
}
/// Returns true if the current instance is within the given bounding box.
#[must_use]
pub fn is_within(&self, other: &BBox) -> bool {
self.north <= other.north
&& self.south >= other.south
&& self.east <= other.east
&& self.west >= other.west
}
/// Returns true if the current instance intersects with the given bounding box.
#[must_use]
pub fn intersects(&self, other: &BBox) -> bool {
self.north >= other.south
&& self.south <= other.north
&& self.east >= other.west
&& self.west <= other.east
}
/// Returns a vector of bounding boxes (`BBox`) associated with the current instance.
///
/// If the instance crosses the antimeridian (the 180-degree meridian), this function
/// returns two `BBox` instances:
/// - The first bounding box covers the area from the object's western boundary to 180 degrees east.
/// - The second bounding box covers the area from -180 degrees west to the object's eastern boundary.
///
/// If the instance does not cross the antimeridian, the function returns a vector
/// containing a single `BBox` that represents the current instance itself.
///
/// # Returns
/// `Vec<BBox>`: A vector containing one `BBox` if the instance does not cross the antimeridian,
/// or two `BBox`es if it does.
///
/// # Examples
///
/// ```
/// use utiles_core::BBox;
/// let example = BBox::new(-10.0, -10.0, 10.0, 10.0);
/// let bboxes = example.bboxes();
/// assert_eq!(bboxes.len(), 1);
///
/// let bboxes_crosses = BBox::new(179.0, -89.0, -179.0, 89.0).bboxes();
/// assert_eq!(bboxes_crosses.len(), 2); // Split into two bounding boxes
/// ```
#[must_use]
pub fn bboxes(&self) -> Vec<BBox> {
if self.crosses_antimeridian() {
vec![
BBox {
north: self.north,
south: self.south,
east: 180.0,
west: self.west,
},
BBox {
north: self.north,
south: self.south,
east: self.east,
west: -180.0,
},
]
} else {
vec![*self]
}
}
/// Return upper left corner of bounding box as `LngLat`
#[must_use]
pub fn ul(&self) -> LngLat {
LngLat::new(self.west, self.north)
}
/// Return upper right corner of bounding box as `LngLat`
#[must_use]
pub fn ur(&self) -> LngLat {
LngLat::new(self.east, self.north)
}
/// Return lower right corner of bounding box as `LngLat`
#[must_use]
pub fn lr(&self) -> LngLat {
LngLat::new(self.east, self.south)
}
/// Return lower left corner of bounding box as `LngLat`
#[must_use]
pub fn ll(&self) -> LngLat {
LngLat::new(self.west, self.south)
}
/// Mbt metadata bounds string
#[must_use]
pub fn mbt_bounds(&self) -> String {
format!("{},{},{},{}", self.west, self.south, self.east, self.north)
}
}
/// Merge a vector of bboxes into a single bbox handling antimeridian
#[must_use]
pub fn geobbox_merge(bboxes: &[BBox]) -> BBox {
if bboxes.is_empty() {
return BBox::world_planet();
}
if bboxes.len() == 1 {
return bboxes[0];
}
// TODO: Figure this out at somepoint...
// let any_crosses_antimeridian = bboxes.iter().any(|bbox| bbox.crosses_antimeridian());
let mut west = f64::INFINITY;
let mut south = f64::INFINITY;
let mut east = f64::NEG_INFINITY;
let mut north = f64::NEG_INFINITY;
for bbox in bboxes {
if bbox.west < west {
west = bbox.west;
}
if bbox.south < south {
south = bbox.south;
}
if bbox.east > east {
east = bbox.east;
}
if bbox.north > north {
north = bbox.north;
}
}
BBox::new(west, south, east, north).geo_wrap()
}
impl From<BBox> for BBoxTuple {
fn from(bbox: BBox) -> Self {
BBoxTuple(bbox.west, bbox.south, bbox.east, bbox.north)
}
}
impl From<BBoxTuple> for BBox {
fn from(tuple: BBoxTuple) -> Self {
BBox::new(tuple.0, tuple.1, tuple.2, tuple.3)
}
}
impl From<&String> for BBox {
fn from(s: &String) -> Self {
// remove leading and trailing quotes
let s = s.trim_matches('"');
parse_bbox(s).unwrap_or_else(|_e| BBox::world_planet())
}
}
impl TryFrom<&str> for BBox {
type Error = &'static str;
fn try_from(s: &str) -> Result<Self, Self::Error> {
parse_bbox(s).map_err(|_| "Failed to parse BBox")
}
}
impl WebBBox {
#[must_use]
pub fn new(left: f64, bottom: f64, right: f64, top: f64) -> Self {
WebBBox {
min: Point2d::new(left, bottom),
max: Point2d::new(right, top),
}
}
#[must_use]
#[inline]
pub fn min(&self) -> Point2d<f64> {
self.min
}
#[must_use]
#[inline]
pub fn max(&self) -> Point2d<f64> {
self.max
}
#[must_use]
#[inline]
pub fn left(&self) -> f64 {
self.min.x
}
#[must_use]
#[inline]
pub fn bottom(&self) -> f64 {
self.min.y
}
#[must_use]
#[inline]
pub fn right(&self) -> f64 {
self.max.x
}
#[must_use]
#[inline]
pub fn top(&self) -> f64 {
self.max.y
}
#[must_use]
#[inline]
pub fn width(&self) -> f64 {
self.max.x - self.min.x
}
#[must_use]
#[inline]
pub fn west(&self) -> f64 {
self.min.x
}
#[must_use]
#[inline]
pub fn south(&self) -> f64 {
self.min.y
}
#[must_use]
#[inline]
pub fn east(&self) -> f64 {
self.max.x
}
#[must_use]
#[inline]
pub fn north(&self) -> f64 {
self.max.y
}
/// Returns the geojson tuple/array representation of the bounding box
#[must_use]
#[inline]
pub fn json_arr(&self) -> String {
format!(
"[{},{},{},{}]",
self.west(),
self.south(),
self.east(),
self.north()
)
}
/// Returns the gdal-ish string representation of the bounding box
#[must_use]
#[inline]
pub fn projwin_str(&self) -> String {
format!(
"{} {} {} {}",
self.west(),
self.north(),
self.east(),
self.south()
)
}
}
impl From<BBox> for WebBBox {
fn from(bbox: BBox) -> Self {
let (west_merc, south_merc) = xy(bbox.west(), bbox.south(), None);
let (east_merc, north_merc) = xy(bbox.east(), bbox.north(), None);
WebBBox::new(west_merc, south_merc, east_merc, north_merc)
}
}
impl From<Tile> for WebBBox {
fn from(tile: Tile) -> Self {
let bbox = tile.geobbox();
WebBBox::new(bbox.west, bbox.south, bbox.east, bbox.north)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_merge_bboxes_non_crossing() {
let bboxes = vec![
BBox::new(-100.0, -10.0, -90.0, 10.0), // Does not cross the anti-meridian
BBox::new(-120.0, -5.0, -100.0, 5.0), // Does not cross the anti-meridian
];
let expected = BBox::new(-120.0, -10.0, -90.0, 10.0);
let result = geobbox_merge(&bboxes);
assert_eq!(result, expected);
}
// =========================================================================
// TODO - Antimeridian bbox... it's not as straight forward as I thought...
// =========================================================================
// #[test]
// fn test_merge_bboxes_antimeridian() {
// let bboxes = vec![
// BBox::new(170.0, -10.0, -170.0, 10.0), // Crosses the anti-meridian
// BBox::new(160.0, -5.0, 170.0, 5.0), // Crosses the anti-meridian
// ];
//
// let expected = BBox::new(160.0, -10.0, -170.0, 10.0);
// let result = geobbox_merge(&bboxes);
//
// assert_eq!(result, expected);
// }
// #[test]
// fn test_merge_mixed_bboxes() {
// let bboxes = vec![
// BBox::new(170.0, -10.0, -170.0, 10.0), // Crosses the anti-meridian
// BBox::new(-100.0, -20.0, 100.0, 20.0), // Does not cross the anti-meridian
// ];
//
// let expected = BBox::new(-100.0, -20.0, -170.0, 20.0);
// let result = geobbox_merge(&bboxes);
//
// assert_eq!(result, expected);
// }
}