use crate::CoordinateType;
use crate::point::Point;
use crate::polygon::Polygon;
pub use crate::traits::{BoundingBox, DoubledOrientedArea, MapPointwise, WindingNumber};
use crate::edge::Edge;
use crate::prelude::Rect;
use crate::traits::{TryBoundingBox, TryIntoBoundingBox};
use std::iter::FromIterator;
#[derive(Default, Clone, Debug, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct MultiPolygon<T> {
pub polygons: Vec<Polygon<T>>,
}
impl<T> MultiPolygon<T> {
pub fn new() -> Self {
Self { polygons: vec![] }
}
pub fn from_polygons(polygons: Vec<Polygon<T>>) -> Self {
MultiPolygon { polygons }
}
pub fn len(&self) -> usize {
self.polygons.len()
}
pub fn is_empty(&self) -> bool {
self.polygons.is_empty()
}
pub fn insert(&mut self, polygon: Polygon<T>) {
self.polygons.push(polygon)
}
}
impl<T: Copy> MultiPolygon<T> {
pub fn all_edges_iter(&self) -> impl Iterator<Item = Edge<T>> + '_ {
self.polygons.iter().flat_map(|p| p.all_edges_iter())
}
}
impl<T> WindingNumber<T> for MultiPolygon<T>
where
T: CoordinateType,
{
fn winding_number(&self, point: Point<T>) -> isize {
self.polygons.iter().map(|p| p.winding_number(point)).sum()
}
}
impl<T> MapPointwise<T> for MultiPolygon<T>
where
T: CoordinateType,
{
fn transform<F: Fn(Point<T>) -> Point<T>>(&self, tf: F) -> Self {
MultiPolygon::from_polygons(self.polygons.iter().map(|p| p.transform(&tf)).collect())
}
}
impl<T, IP: Into<Polygon<T>>> From<IP> for MultiPolygon<T> {
fn from(x: IP) -> Self {
MultiPolygon::from_polygons(vec![x.into()])
}
}
impl<T> From<Vec<Polygon<T>>> for MultiPolygon<T> {
fn from(polygons: Vec<Polygon<T>>) -> Self {
MultiPolygon { polygons }
}
}
impl<T, IP: Into<Polygon<T>>> FromIterator<IP> for MultiPolygon<T> {
fn from_iter<I: IntoIterator<Item = IP>>(iter: I) -> Self {
MultiPolygon::from_polygons(iter.into_iter().map(|p| p.into()).collect())
}
}
impl<T> IntoIterator for MultiPolygon<T> {
type Item = Polygon<T>;
type IntoIter = ::std::vec::IntoIter<Polygon<T>>;
fn into_iter(self) -> Self::IntoIter {
self.polygons.into_iter()
}
}
impl<T: CoordinateType> TryBoundingBox<T> for MultiPolygon<T> {
fn try_bounding_box(&self) -> Option<Rect<T>> {
self.polygons.iter().try_into_bounding_box()
}
}