use std::collections::VecDeque;
use std::convert::Infallible;
use std::iter::Peekable;
use geo_types::{Coord, Geometry, Polygon};
use geometry::Point;
use mln_style::error::Error;
use mln_style::geo::LatLng;
use mln_style::geometry::{FeatureType, to_feature_type};
use mln_style::math::clamp_f64;
use mln_vec_map::VecMap;
use crate::geo::projection::Projection;
use crate::tile::UnwrappedTileID;
pub(crate) type Bounds = Vec<Bound>;
pub(crate) type BoundsMap = VecMap<u32, Bounds>;
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct Bound {
pub(crate) points: Vec<Point<f64>>,
pub(crate) current_point: usize,
pub(crate) winding: bool,
}
impl Bound {
#[must_use]
pub(crate) fn interpolate(&self, y: u32) -> f64 {
let p0 = &self.points[self.current_point];
let p1 = &self.points[self.current_point + 1];
let dx = p1.x - p0.x;
let dy = p1.y - p0.y;
let mut x = p0.x;
if dx == 0.0 {
return x;
} else if dy == 0.0 {
return if f64::from(y) <= p0.y { p0.x } else { p1.x };
}
if f64::from(y) < p0.y {
return x;
}
if f64::from(y) > p1.y {
return p1.x;
}
x = (dx / dy) * (f64::from(y) - p0.y) + p0.x;
x
}
}
type PointList = Vec<Point<f64>>;
#[derive(Clone, Copy, Debug, PartialEq)]
struct TileSpan {
xmin: i32,
xmax: i32,
winding: bool,
}
fn start_list_on_local_minimum(points: &mut PointList) {
let end = points.len();
let mut prev_pt = end - 2;
let mut pt = 0;
let mut next_pt = pt + 1;
while pt != end {
if (points[pt].y <= points[prev_pt].y) && (points[pt].y < points[next_pt].y) {
break;
}
prev_pt = pt;
pt += 1;
next_pt += 1;
if next_pt == end {
next_pt = 1;
}
}
if pt == end {
return;
}
if points.last() == points.first() {
points.pop();
}
points.rotate_left(pt);
points.push(points[0]);
}
fn create_bound_towards_maximum(points: &PointList, pt: &mut usize) -> Bound {
if points.len() - *pt < 2 {
return Bound::default();
}
let begin = *pt;
let mut next_pt = begin + 1;
while points[*pt].y <= points[next_pt].y {
*pt += 1;
next_pt += 1;
if next_pt == points.len() {
*pt += 1;
break;
}
}
let pt_distance = next_pt - begin;
if pt_distance < 2 {
return Bound::default();
}
let mut bnd = Bound::default();
bnd.points.reserve(next_pt - begin);
bnd.points.extend_from_slice(&points[begin..next_pt]);
bnd.winding = true;
bnd
}
fn create_bound_towards_minimum(points: &PointList, pt: &mut usize) -> Bound {
if points.len() - *pt < 2 {
return Bound::default();
}
let begin = *pt;
let mut next_pt = begin + 1;
while points[*pt].y > points[next_pt].y {
*pt += 1;
next_pt += 1;
if next_pt == points.len() {
*pt += 1;
break;
}
}
let pt_distance = next_pt - begin;
if pt_distance < 2 {
return Bound::default();
}
let mut bnd = Bound::default();
bnd.points.reserve(next_pt - begin);
bnd.points.extend(points[begin..next_pt].iter().rev().copied());
bnd.winding = false;
bnd
}
fn start_row(y: f64, max_tile: f64) -> u32 {
clamp_f64(y, 0.0, max_tile).floor() as u32
}
fn build_bounds_map(points: &mut PointList, max_tile: u32, et: &mut BoundsMap, closed: bool) {
if points.len() < 2 {
return;
}
if closed {
start_list_on_local_minimum(points);
}
let mut points_iter = 0;
while points_iter != points.len() {
let to_max = create_bound_towards_maximum(points, &mut points_iter);
let to_min = create_bound_towards_minimum(points, &mut points_iter);
if to_max.points.len() >= 2 {
let y = start_row(to_max.points[0].y, f64::from(max_tile));
et.entry(y).or_default().push(to_max);
}
if to_min.points.len() >= 2 {
let y = start_row(to_min.points[0].y, f64::from(max_tile));
et.entry(y).or_default().push(to_min);
}
}
debug_assert_eq!(points_iter, points.len());
}
fn update_span(xp: &mut TileSpan, x: f64) {
xp.xmin = std::cmp::min(xp.xmin, x.floor() as i32);
xp.xmax = std::cmp::max(xp.xmax, x.ceil() as i32);
}
fn scan_row(y: u32, active_bounds: &mut Bounds) -> Vec<TileSpan> {
let mut tile_range: Vec<TileSpan> = Vec::with_capacity(active_bounds.len());
let y1 = y.wrapping_add(1);
for b in active_bounds.iter_mut() {
let mut xp = TileSpan { xmin: i32::MAX, xmax: 0, winding: b.winding };
let mut x;
let num_edges = b.points.len() - 1;
while b.current_point < num_edges {
x = b.interpolate(y);
update_span(&mut xp, x);
let p1 = b.points[b.current_point + 1];
if p1.y > f64::from(y1) {
x = b.interpolate(y1);
update_span(&mut xp, x);
break;
} else if b.current_point == num_edges - 1 {
x = p1.x;
update_span(&mut xp, x);
}
b.current_point += 1;
}
tile_range.push(xp);
}
active_bounds.retain(|bound| {
!(bound.current_point == bound.points.len() - 1 && bound.points[bound.current_point].y <= f64::from(y1))
});
tile_range.sort_by_key(|span| (span.xmin, span.xmax));
tile_range
}
struct BuildBoundsMap<P> {
zoom: i32,
project: P,
}
impl<E, P: Fn(Point<f64>) -> Result<Point<f64>, E>> BuildBoundsMap<P> {
fn max_tile(&self) -> i32 {
1i32.wrapping_shl(self.zoom as u32)
}
fn build_table(&self, points: &[Coord<f64>], et: &mut BoundsMap, closed: bool) -> Result<(), E> {
let mut projected_points: PointList = Vec::with_capacity(points.len());
for &p in points {
projected_points.push((self.project)(Point::from(p))?);
}
build_bounds_map(&mut projected_points, self.max_tile() as u32, et, closed);
Ok(())
}
fn build_polygon_table(&self, polygon: &Polygon<f64>, et: &mut BoundsMap) -> Result<(), E> {
for ring in std::iter::once(polygon.exterior()).chain(polygon.interiors()) {
self.build_table(&ring.0, et, true)?;
}
Ok(())
}
fn point(&self, p: Coord<f64>, et: &mut BoundsMap) -> Result<(), E> {
let mut bnd = Bound::default();
let point = (self.project)(Point::from(p))?;
bnd.points.extend([point, point]);
bnd.winding = false;
let y = start_row(point.y, f64::from(self.max_tile()));
et.entry(y).or_default().push(bnd);
Ok(())
}
fn multi_point(&self, points: &geo_types::MultiPoint<f64>, et: &mut BoundsMap) -> Result<(), E> {
for p in points {
self.point(p.0, et)?;
}
Ok(())
}
fn apply(&self, geom: &Geometry<f64>) -> Result<BoundsMap, E> {
let mut et = BoundsMap::new();
match geom {
Geometry::GeometryCollection(_) => {}
Geometry::Point(p) => self.point(p.0, &mut et)?,
Geometry::MultiPoint(points) => self.multi_point(points, &mut et)?,
Geometry::Line(line) => self.build_table(&[line.start, line.end], &mut et, false)?,
Geometry::LineString(line) => self.build_table(&line.0, &mut et, false)?,
Geometry::MultiLineString(lines) => {
for line in lines {
self.build_table(&line.0, &mut et, false)?;
}
}
Geometry::Rect(rect) => self.build_polygon_table(&rect.to_polygon(), &mut et)?,
Geometry::Triangle(triangle) => self.build_polygon_table(&triangle.to_polygon(), &mut et)?,
Geometry::Polygon(polygon) => self.build_polygon_table(polygon, &mut et)?,
Geometry::MultiPolygon(polygons) => {
for polygon in polygons {
self.build_polygon_table(polygon, &mut et)?;
}
}
}
Ok(et)
}
}
type TileSpans = VecDeque<(i32, i32)>;
pub(crate) struct Impl {
zoom: i32,
is_closed: bool,
current_bounds: Peekable<mln_vec_map::IntoIter<u32, Bounds>>,
active_bounds: Bounds,
tile_x_spans: TileSpans,
tile_y: u32,
tile_x: i32,
}
impl Impl {
pub(crate) fn new(z: i32, geom: &Geometry<f64>) -> Impl {
let Ok(this) = Self::build(z, geom, Ok::<_, Infallible>);
this
}
pub(crate) fn new_projected(z: i32, geom: &Geometry<f64>) -> Result<Impl, Error> {
Self::build(z, geom, |p: Point<f64>| Ok(Projection::project_zoom(&LatLng::new(p.y, p.x)?, z)))
}
fn build<E>(
z: i32,
geom: &Geometry<f64>,
project: impl Fn(Point<f64>) -> Result<Point<f64>, E>,
) -> Result<Impl, E> {
let is_closed = to_feature_type(Some(geom)) == FeatureType::Polygon;
let bounds_map = BuildBoundsMap { zoom: z, project }.apply(geom)?;
let empty = bounds_map.is_empty();
let mut this = Impl {
zoom: z,
is_closed,
current_bounds: bounds_map.into_iter().peekable(),
active_bounds: Bounds::new(),
tile_x_spans: TileSpans::new(),
tile_y: 0,
tile_x: 0,
};
if empty {
return Ok(this);
}
this.tile_y = 0;
this.next_row();
if let Some(&(first, _)) = this.tile_x_spans.front() {
this.tile_x = first;
}
Ok(this)
}
fn next_row(&mut self) {
if let Some(&(first, _)) = self.current_bounds.peek()
&& self.active_bounds.is_empty()
&& first > self.tile_y
{
self.tile_y = first;
}
let tile_y = self.tile_y;
if let Some((_, bounds)) = self.current_bounds.next_if(|&(first, _)| first == tile_y) {
self.active_bounds.extend(bounds);
}
let xps = scan_row(self.tile_y, &mut self.active_bounds);
if xps.is_empty() {
return;
}
let mut x_min = xps[0].xmin;
let mut x_max = xps[0].xmax;
let mut nz_rule: i32 = if xps[0].winding { 1 } else { -1 };
for xp in &xps[1..] {
if (!self.is_closed || nz_rule == 0) && xp.xmin > x_max && xp.xmax >= x_max {
self.tile_x_spans.push_back((x_min, x_max));
x_min = xp.xmin;
}
nz_rule += if xp.winding { 1 } else { -1 };
x_max = std::cmp::max(x_min, xp.xmax);
}
self.tile_x_spans.push_back((x_min, x_max));
}
#[must_use]
pub(crate) fn has_next(&self) -> bool {
match self.tile_x_spans.front() {
Some(&(_, second)) => self.tile_x < second && self.tile_y < 1u32.wrapping_shl(self.zoom as u32),
None => false,
}
}
}
impl Iterator for Impl {
type Item = UnwrappedTileID;
fn next(&mut self) -> Option<UnwrappedTileID> {
if !self.has_next() {
return None;
}
let x = self.tile_x;
let y = self.tile_y;
self.tile_x += 1;
if self.tile_x_spans.front().is_some_and(|&(_, end)| self.tile_x >= end) {
self.tile_x_spans.pop_front();
if self.tile_x_spans.is_empty() {
self.tile_y = self.tile_y.wrapping_add(1);
self.next_row();
}
if let Some(&(first, _)) = self.tile_x_spans.front() {
self.tile_x = first;
}
}
Some(UnwrappedTileID::new(self.zoom as u8, i64::from(x), i64::from(y)))
}
}