use super::areal::{AreaOperand, Areal, Window, WindowedAreal};
use super::label::Dimension;
use super::line_analysis::{LineSet, lines_lines_matrix, lines_polygon_matrix};
use super::point_analysis::{Target, points_matrix};
use super::polygon_analysis::polygons_matrix;
use crate::GeometryError;
use crate::types::{
Coord2d, Geometry, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct IntersectionMatrix {
pub interior_interior: Dimension,
pub interior_boundary: Dimension,
pub interior_exterior: Dimension,
pub boundary_interior: Dimension,
pub boundary_boundary: Dimension,
pub boundary_exterior: Dimension,
pub exterior_interior: Dimension,
pub exterior_boundary: Dimension,
pub exterior_exterior: Dimension,
}
impl IntersectionMatrix {
pub fn compute(a: &Polygon, b: &Polygon) -> Self {
polygons_matrix(&Areal::single(a), &Areal::single(b))
}
pub fn compute_geometry(a: &Geometry, b: &Geometry) -> Result<Self, GeometryError> {
Ok(Self::compute_operands(
&Operand::from_geometry(a)?,
&Operand::from_geometry(b)?,
))
}
pub(crate) fn compute_operands(oa: &Operand<'_>, ob: &Operand<'_>) -> Self {
use crate::topology::collection::{Strata, merged_matrix};
match (oa, ob) {
(Operand::Collection(_), _) | (_, Operand::Collection(_)) => {
merged_matrix(&Strata::of(oa), &Strata::of(ob))
}
(Operand::Area(a), Operand::Area(b)) => {
let (wa, wb) = windowed_pair(a, b);
polygons_matrix(
wa.as_ref().map_or(a as &dyn AreaOperand, |w| w),
wb.as_ref().map_or(b as &dyn AreaOperand, |w| w),
)
}
(Operand::Lines(a), Operand::Area(b)) => {
let wb = WindowedAreal::of(b, lines_window(a));
lines_polygon_matrix(a, wb.as_ref().map_or(b as &dyn AreaOperand, |w| w))
}
(Operand::Area(a), Operand::Lines(b)) => {
let wa = WindowedAreal::of(a, lines_window(b));
lines_polygon_matrix(b, wa.as_ref().map_or(a as &dyn AreaOperand, |w| w)).swap_ab()
}
(Operand::Lines(a), Operand::Lines(b)) => lines_lines_matrix(a, b),
(Operand::Points(p), other) => points_matrix(p, &other.as_target()),
(other, Operand::Points(p)) => points_matrix(p, &other.as_target()).swap_ab(),
}
}
pub(crate) fn compute_area_against(
a: &dyn AreaOperand,
b: &Geometry,
) -> Result<IntersectionMatrix, GeometryError> {
use crate::topology::collection::{Strata, merged_matrix};
Ok(match Operand::from_geometry(b)? {
Operand::Area(ob) => polygons_matrix(a, &ob),
Operand::Lines(ob) => lines_polygon_matrix(&ob, a).swap_ab(),
Operand::Points(ob) => points_matrix(&ob, &Target::Area(a)).swap_ab(),
ref ob @ Operand::Collection(_) => merged_matrix(&Strata::of_area(a), &Strata::of(ob)),
})
}
#[must_use]
pub fn swap_ab(&self) -> Self {
Self {
interior_interior: self.interior_interior,
interior_boundary: self.boundary_interior,
interior_exterior: self.exterior_interior,
boundary_interior: self.interior_boundary,
boundary_boundary: self.boundary_boundary,
boundary_exterior: self.exterior_boundary,
exterior_interior: self.interior_exterior,
exterior_boundary: self.boundary_exterior,
exterior_exterior: self.exterior_exterior,
}
}
pub fn from_pattern(pattern: &str) -> Result<Self, PatternError> {
let chars: Vec<char> = pattern.chars().collect();
if chars.len() != 9 {
return Err(PatternError {
message: "pattern must be exactly 9 characters",
});
}
let mut dims = [Dimension::Empty; 9];
#[allow(clippy::match_same_arms)]
for (i, &ch) in chars.iter().enumerate() {
dims[i] = match ch {
'F' => Dimension::Empty,
'0' => Dimension::Point,
'1' => Dimension::Line,
'2' => Dimension::Area,
'*' => Dimension::Empty,
_ => {
return Err(PatternError {
message: "invalid character in pattern: expected F, 0, 1, 2, or *",
});
}
};
}
Ok(Self {
interior_interior: dims[0],
interior_boundary: dims[1],
interior_exterior: dims[2],
boundary_interior: dims[3],
boundary_boundary: dims[4],
boundary_exterior: dims[5],
exterior_interior: dims[6],
exterior_boundary: dims[7],
exterior_exterior: dims[8],
})
}
pub fn cells(&self) -> [Dimension; 9] {
[
self.interior_interior,
self.interior_boundary,
self.interior_exterior,
self.boundary_interior,
self.boundary_boundary,
self.boundary_exterior,
self.exterior_interior,
self.exterior_boundary,
self.exterior_exterior,
]
}
}
pub(crate) enum Operand<'a> {
Points(Vec<Coord2d>),
Lines(LineSet<'a>),
Area(Areal<'a>),
Collection(crate::topology::collection::GcParts<'a>),
}
impl<'a> Operand<'a> {
pub(crate) fn from_geometry(g: &'a Geometry) -> Result<Self, GeometryError> {
Ok(match g {
Geometry::Point(p) => Self::point(p),
Geometry::MultiPoint(mp) => Self::multi_point(mp),
Geometry::LineString(l) => Self::line_string(l),
Geometry::MultiLineString(ml) => Self::multi_line_string(ml),
Geometry::Polygon(p) => Self::polygon(p),
Geometry::MultiPolygon(mp) => Self::multi_polygon(mp),
Geometry::GeometryCollection(gc) => {
return crate::topology::collection::collection_operand(gc);
}
})
}
pub(crate) fn point(p: &Point) -> Self {
Operand::Points(vec![p.coord()])
}
pub(crate) fn multi_point(mp: &MultiPoint) -> Self {
Operand::Points(mp.points().iter().map(Point::coord).collect())
}
pub(crate) fn line_string(l: &'a LineString) -> Self {
Operand::Lines(LineSet::single(l))
}
pub(crate) fn multi_line_string(ml: &'a MultiLineString) -> Self {
if ml.is_empty() {
Operand::Points(Vec::new())
} else {
Operand::Lines(LineSet::new(ml.line_strings().iter().collect()))
}
}
pub(crate) fn polygon(p: &'a Polygon) -> Self {
Operand::Area(Areal::single(p))
}
pub(crate) fn multi_polygon(mp: &'a MultiPolygon) -> Self {
if mp.is_empty() {
Operand::Points(Vec::new())
} else {
Operand::Area(Areal::multi(mp))
}
}
pub(crate) fn dimension(&self) -> Dimension {
match self {
Operand::Points(p) if p.is_empty() => Dimension::Empty,
Operand::Points(_) => Dimension::Point,
Operand::Lines(_) => Dimension::Line,
Operand::Area(_) => Dimension::Area,
Operand::Collection(gc) => crate::topology::collection::parts_dimension(gc),
}
}
fn as_target(&self) -> Target<'_> {
match self {
Operand::Points(p) => Target::Points(p),
Operand::Lines(l) => Target::Lines(l),
Operand::Area(a) => Target::Area(a),
Operand::Collection(gc) => Target::Points(&gc.pts),
}
}
}
impl std::fmt::Display for IntersectionMatrix {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for dim in self.cells() {
let ch = match dim {
Dimension::Empty => 'F',
Dimension::Point => '0',
Dimension::Line => '1',
Dimension::Area => '2',
};
write!(f, "{ch}")?;
}
Ok(())
}
}
#[derive(Debug, PartialEq)]
pub struct PatternError {
pub message: &'static str,
}
impl std::fmt::Display for PatternError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "DE-9IM pattern parse error: {}", self.message)
}
}
pub(crate) fn windowed_pair<'a>(
a: &Areal<'a>,
b: &Areal<'a>,
) -> (Option<WindowedAreal<'a>>, Option<WindowedAreal<'a>>) {
let wa = WindowedAreal::worth_it(a)
.then(|| WindowedAreal::of(a, b.all_window()))
.flatten();
let wb = WindowedAreal::worth_it(b)
.then(|| {
let w = wa
.as_ref()
.map_or_else(|| a.all_window(), |x| x.all_window());
WindowedAreal::of(b, w)
})
.flatten();
(wa, wb)
}
fn lines_window(l: &LineSet<'_>) -> Window {
l.bbox().map_or(
(
crate::types::Coord2d::new(0.0, 0.0),
crate::types::Coord2d::new(0.0, 0.0),
),
|(x0, y0, x1, y1)| {
(
crate::types::Coord2d::new(x0, y0),
crate::types::Coord2d::new(x1, y1),
)
},
)
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
#[allow(
clippy::float_cmp,
clippy::cast_possible_truncation,
clippy::cast_precision_loss,
clippy::cast_possible_wrap,
clippy::range_plus_one,
clippy::no_effect_underscore_binding
)]
mod tests {
use super::*;
use crate::types::{Coord2d, CoordSeq, LinearRing, Polygon};
fn c(x: f64, y: f64) -> Coord2d {
Coord2d::new(x, y)
}
fn seq(pts: &[(f64, f64)]) -> CoordSeq {
CoordSeq::new(pts.iter().map(|&(x, y)| c(x, y)).collect())
}
fn ccw_square(ox: f64, oy: f64, side: f64) -> Polygon {
let ring = LinearRing::new(seq(&[
(ox, oy),
(ox + side, oy),
(ox + side, oy + side),
(ox, oy + side),
]))
.unwrap();
Polygon::new_simple(ring).unwrap()
}
#[test]
fn disjoint_polygons_interior_interior_is_empty() {
let a = ccw_square(0.0, 0.0, 1.0);
let b = ccw_square(2.0, 0.0, 1.0);
let m = IntersectionMatrix::compute(&a, &b);
assert_eq!(m.interior_interior, Dimension::Empty);
assert_eq!(m.exterior_exterior, Dimension::Area);
}
#[test]
fn from_pattern_valid_with_wildcards() {
let result = IntersectionMatrix::from_pattern("FF2FF1***");
assert!(result.is_ok());
let m = result.unwrap();
assert_eq!(m.interior_interior, Dimension::Empty);
assert_eq!(m.interior_exterior, Dimension::Area);
assert_eq!(m.boundary_exterior, Dimension::Line);
}
#[test]
fn from_pattern_wrong_length_is_err() {
assert!(IntersectionMatrix::from_pattern("FF2FF1**").is_err());
assert!(IntersectionMatrix::from_pattern("FF2FF1****").is_err());
assert!(IntersectionMatrix::from_pattern("").is_err());
}
#[test]
fn from_pattern_invalid_char_is_err() {
let result = IntersectionMatrix::from_pattern("FF2FF1**X");
assert!(result.is_err());
assert!(result.unwrap_err().message.contains("invalid character"));
}
#[test]
fn display_renders_ogc_string() {
let m = IntersectionMatrix {
interior_interior: Dimension::Area,
interior_boundary: Dimension::Line,
interior_exterior: Dimension::Area,
boundary_interior: Dimension::Line,
boundary_boundary: Dimension::Point,
boundary_exterior: Dimension::Line,
exterior_interior: Dimension::Area,
exterior_boundary: Dimension::Line,
exterior_exterior: Dimension::Area,
};
assert_eq!(m.to_string(), "212101212");
}
#[test]
fn display_renders_all_dimension_chars() {
let m = IntersectionMatrix {
interior_interior: Dimension::Empty,
interior_boundary: Dimension::Point,
interior_exterior: Dimension::Line,
boundary_interior: Dimension::Area,
boundary_boundary: Dimension::Empty,
boundary_exterior: Dimension::Point,
exterior_interior: Dimension::Line,
exterior_boundary: Dimension::Area,
exterior_exterior: Dimension::Empty,
};
assert_eq!(m.to_string(), "F012F012F");
}
#[test]
fn compute_d4_edge_touching_produces_bb_line() {
let a = ccw_square(0.0, 0.0, 1.0);
let b = ccw_square(1.0, 0.0, 1.0);
let m = IntersectionMatrix::compute(&a, &b);
assert_eq!(m.boundary_boundary, Dimension::Line);
assert_eq!(m.interior_interior, Dimension::Empty);
assert_eq!(m.to_string(), "FF2F11212");
}
#[test]
fn compute_d5_vertex_touching_produces_bb_point() {
let a = ccw_square(0.0, 0.0, 1.0);
let b = ccw_square(1.0, 1.0, 1.0);
let m = IntersectionMatrix::compute(&a, &b);
assert_eq!(m.boundary_boundary, Dimension::Point);
assert_eq!(m.interior_interior, Dimension::Empty);
}
#[test]
fn compute_crossing_squares_bb_is_point() {
let a = ccw_square(0.0, 0.0, 4.0);
let b = ccw_square(2.0, 2.0, 4.0);
let m = IntersectionMatrix::compute(&a, &b);
assert_eq!(m.boundary_boundary, Dimension::Point);
assert_eq!(m.interior_interior, Dimension::Area);
assert_eq!(m.to_string(), "212101212");
}
#[test]
fn compute_d3_equal_squares_produces_correct_matrix() {
let a = ccw_square(0.0, 0.0, 1.0);
let b = ccw_square(0.0, 0.0, 1.0);
let m = IntersectionMatrix::compute(&a, &b);
assert_eq!(m.interior_interior, Dimension::Area, "II");
assert_eq!(m.interior_boundary, Dimension::Empty, "IB");
assert_eq!(m.interior_exterior, Dimension::Empty, "IE");
assert_eq!(m.boundary_interior, Dimension::Empty, "BI");
assert_eq!(m.boundary_boundary, Dimension::Line, "BB: shared boundary");
assert_eq!(m.boundary_exterior, Dimension::Empty, "BE");
assert_eq!(m.exterior_interior, Dimension::Empty, "EI");
assert_eq!(m.exterior_boundary, Dimension::Empty, "EB");
assert_eq!(m.exterior_exterior, Dimension::Area, "EE");
assert_eq!(m.to_string(), "2FFF1FFF2", "OGC string for equal polygons");
}
#[test]
fn compute_d1_b_inside_a_produces_correct_matrix() {
let a = ccw_square(0.0, 0.0, 4.0);
let b = ccw_square(1.0, 1.0, 2.0);
let m = IntersectionMatrix::compute(&a, &b);
assert_eq!(m.interior_interior, Dimension::Area, "II");
assert_eq!(
m.interior_boundary,
Dimension::Line,
"IB: B's ring inside A"
);
assert_eq!(m.interior_exterior, Dimension::Area, "IE: annular region");
assert_eq!(m.boundary_interior, Dimension::Empty, "BI");
assert_eq!(m.boundary_boundary, Dimension::Empty, "BB");
assert_eq!(
m.boundary_exterior,
Dimension::Line,
"BE: A's ring outside B"
);
assert_eq!(m.exterior_interior, Dimension::Empty, "EI");
assert_eq!(m.exterior_boundary, Dimension::Empty, "EB");
assert_eq!(m.exterior_exterior, Dimension::Area, "EE");
}
#[test]
fn compute_d2_a_inside_b_produces_correct_matrix() {
let a = ccw_square(1.0, 1.0, 2.0);
let b = ccw_square(0.0, 0.0, 4.0);
let m = IntersectionMatrix::compute(&a, &b);
assert_eq!(m.interior_interior, Dimension::Area, "II");
assert_eq!(m.interior_boundary, Dimension::Empty, "IB");
assert_eq!(m.interior_exterior, Dimension::Empty, "IE");
assert_eq!(
m.boundary_interior,
Dimension::Line,
"BI: A's ring inside B"
);
assert_eq!(m.boundary_boundary, Dimension::Empty, "BB");
assert_eq!(m.boundary_exterior, Dimension::Empty, "BE");
assert_eq!(m.exterior_interior, Dimension::Area, "EI: annular region");
assert_eq!(
m.exterior_boundary,
Dimension::Line,
"EB: B's ring in A's exterior"
);
assert_eq!(m.exterior_exterior, Dimension::Area, "EE");
}
}