use anyhow::{Context as _, ensure};
use geo::{BoundingRect, Coord, CoordsIter, LineString, MultiPolygon, Rect, coord};
use serde::{Deserialize, Serialize};
use geolith::terrain::cog::Cog;
use geolith::terrain::crs::Crs;
use geolith::terrain::dem::{Dem, GeoTransform};
pub const EARTH_RADIUS_M: f64 = 6_371_008.8;
const GRID_TOLERANCE_PIXELS: f64 = 1e-3;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Grid {
pub width: u32,
pub height: u32,
pub transform: GeoTransform,
}
impl Grid {
pub fn from_dem(dem: &Dem) -> anyhow::Result<Grid> {
ensure!(
dem.crs == Crs::Wgs84,
"area numbers need an EPSG:4326 raster in this version"
);
Ok(Grid {
width: dem.width,
height: dem.height,
transform: dem.transform,
})
}
pub fn from_cog(cog: &Cog) -> anyhow::Result<Grid> {
ensure!(
cog.crs() == Crs::Wgs84,
"area numbers need an EPSG:4326 raster in this version"
);
let (width, height) = cog.size(0).context("the raster has no level 0")?;
let transform = cog.geo_transform(0).context("the raster has no level 0")?;
Ok(Grid {
width,
height,
transform,
})
}
#[must_use]
pub fn matches(&self, other: &Grid) -> bool {
let (a, b) = (&self.transform, &other.transform);
let cells = f64::from(self.width.max(self.height));
let axis = |origin_a: f64, origin_b: f64, pixel_a: f64, pixel_b: f64| {
let limit = GRID_TOLERANCE_PIXELS * pixel_a.abs();
(origin_a - origin_b).abs() <= limit && (pixel_a - pixel_b).abs() * cells <= limit
};
self.width == other.width
&& self.height == other.height
&& axis(a.origin_x, b.origin_x, a.pixel_width, b.pixel_width)
&& axis(a.origin_y, b.origin_y, a.pixel_height, b.pixel_height)
}
#[must_use]
pub fn cell_area_m2(&self, row: u32) -> f64 {
let t = &self.transform;
let top = t.origin_y - f64::from(row) * t.pixel_height;
let bottom = top - t.pixel_height;
EARTH_RADIUS_M
* EARTH_RADIUS_M
* t.pixel_width.to_radians()
* (top.to_radians().sin() - bottom.to_radians().sin()).abs()
}
fn cell_rect(&self, col: u32, row: u32) -> Rect<f64> {
let t = &self.transform;
let x0 = t.origin_x + f64::from(col) * t.pixel_width;
let y0 = t.origin_y - f64::from(row) * t.pixel_height;
Rect::new(
coord! { x: x0, y: y0 },
coord! { x: x0 + t.pixel_width, y: y0 - t.pixel_height },
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct CellWeight {
pub col: u32,
pub row: u32,
pub fraction: f64,
pub area_m2: f64,
}
fn cell_range(lo: f64, hi: f64, origin: f64, step: f64, len: u32) -> (u32, u32) {
let clamp = |v: f64| v.clamp(0.0, f64::from(len)) as u32;
(
clamp(((lo - origin) / step).floor()),
clamp(((hi - origin) / step).ceil()),
)
}
fn clipped_ring_area(ring: &LineString<f64>, cell: &Rect<f64>) -> f64 {
let (min, max) = (cell.min(), cell.max());
let mut points: Vec<Coord<f64>> = ring.0.iter().map(|c| *c - min).collect();
if points.len() > 1 && points.first() == points.last() {
points.pop();
}
let (w, h) = (max.x - min.x, max.y - min.y);
let edges = [
(true, 0.0, true),
(true, w, false),
(false, 0.0, true),
(false, h, false),
];
for (on_x, bound, keep_above) in edges {
let axis = |c: Coord<f64>| if on_x { c.x } else { c.y };
if points.is_empty() {
return 0.0;
}
let inside = |c: Coord<f64>| {
if keep_above {
axis(c) >= bound
} else {
axis(c) <= bound
}
};
let mut out = Vec::with_capacity(points.len() + 4);
let mut prev = points[points.len() - 1];
for &cur in &points {
let (cur_in, prev_in) = (inside(cur), inside(prev));
if cur_in != prev_in {
let t = (bound - axis(prev)) / (axis(cur) - axis(prev));
out.push(prev + (cur - prev) * t);
}
if cur_in {
out.push(cur);
}
prev = cur;
}
points = out;
}
if points.len() < 3 {
return 0.0;
}
let mut twice = 0.0;
let mut prev = points[points.len() - 1];
for &cur in &points {
twice += prev.x * cur.y - cur.x * prev.y;
prev = cur;
}
(twice / 2.0).abs()
}
fn clipped_area(shape: &MultiPolygon<f64>, cell: &Rect<f64>) -> f64 {
shape
.iter()
.map(|p| {
let holes: f64 = p
.interiors()
.iter()
.map(|r| clipped_ring_area(r, cell))
.sum();
(clipped_ring_area(p.exterior(), cell) - holes).max(0.0)
})
.sum()
}
fn clamped_index(v: f64, lo: u32, hi: u32) -> u32 {
v.floor().clamp(f64::from(lo), f64::from(hi)) as u32
}
#[derive(Debug, Clone, Copy)]
struct Crossing {
x: f64,
delta: i32,
ring: u32,
}
struct Rings<'a> {
rings: Vec<(&'a LineString<f64>, usize, bool)>,
exteriors: Vec<usize>,
}
impl<'a> Rings<'a> {
fn new(shape: &'a MultiPolygon<f64>) -> Self {
let mut rings = Vec::with_capacity(shape.iter().map(|p| 1 + p.interiors().len()).sum());
let mut exteriors = Vec::with_capacity(shape.0.len());
for (part, p) in shape.iter().enumerate() {
exteriors.push(rings.len());
rings.push((p.exterior(), part, true));
rings.extend(p.interiors().iter().map(|r| (r, part, false)));
}
Self { rings, exteriors }
}
}
struct Sweep<'r, 'a> {
rings: &'r Rings<'a>,
winding: Vec<i32>,
holes_around: Vec<u32>,
part_inside: Vec<bool>,
parts_inside: usize,
}
impl<'r, 'a> Sweep<'r, 'a> {
fn new(rings: &'r Rings<'a>) -> Self {
Self {
rings,
winding: vec![0; rings.rings.len()],
holes_around: vec![0; rings.exteriors.len()],
part_inside: vec![false; rings.exteriors.len()],
parts_inside: 0,
}
}
fn apply(&mut self, c: &Crossing) {
let ring = c.ring as usize;
let (_, part, exterior) = self.rings.rings[ring];
let before = self.winding[ring] != 0;
self.winding[ring] += c.delta;
let after = self.winding[ring] != 0;
if before != after && !exterior {
if after {
self.holes_around[part] += 1;
} else {
self.holes_around[part] -= 1;
}
}
let inside = self.winding[self.rings.exteriors[part]] != 0 && self.holes_around[part] == 0;
if inside != self.part_inside[part] {
self.part_inside[part] = inside;
if inside {
self.parts_inside += 1;
} else {
self.parts_inside -= 1;
}
}
}
fn reset(&mut self, crossings: &[Crossing]) {
for c in crossings {
self.winding[c.ring as usize] = 0;
let part = self.rings.rings[c.ring as usize].1;
self.holes_around[part] = 0;
self.part_inside[part] = false;
}
self.parts_inside = 0;
}
}
#[must_use]
pub fn has_finite_vertices(shape: &MultiPolygon<f64>) -> bool {
shape
.coords_iter()
.all(|c| c.x.is_finite() && c.y.is_finite())
}
#[must_use]
pub fn cell_weights(shape: &MultiPolygon<f64>, grid: &Grid) -> Vec<CellWeight> {
if !has_finite_vertices(shape) {
return Vec::new();
}
let Some(bbox) = shape.bounding_rect() else {
return Vec::new();
};
let t = &grid.transform;
let (col0, col1) = cell_range(
bbox.min().x,
bbox.max().x,
t.origin_x,
t.pixel_width,
grid.width,
);
let (row0, row1) = cell_range(
-bbox.max().y,
-bbox.min().y,
-t.origin_y,
t.pixel_height,
grid.height,
);
if col0 >= col1 || row0 >= row1 {
return Vec::new();
}
let (cols, rows) = ((col1 - col0) as usize, (row1 - row0) as usize);
let col_cells: Vec<Rect<f64>> = (col0..col1).map(|c| grid.cell_rect(c, row0)).collect();
let row_cells: Vec<Rect<f64>> = (row0..row1).map(|r| grid.cell_rect(col0, r)).collect();
let centre_x: Vec<f64> = col_cells.iter().map(|c| c.center().x).collect();
let centre_y: Vec<f64> = row_cells.iter().map(|c| c.center().y).collect();
let rings = Rings::new(shape);
let mut boundary = vec![false; cols * rows];
let mut per_row = vec![0_usize; rows + 1];
let edges: usize = rings.rings.iter().map(|(r, _, _)| r.0.len()).sum();
let mut crossing_rows: Vec<(u32, Crossing)> = Vec::with_capacity(edges);
let mut hit_cols: Vec<u32> = Vec::new();
for (index, (ring, _, _)) in rings.rings.iter().enumerate() {
for line in ring.lines() {
let (x_lo, x_hi) = (line.start.x.min(line.end.x), line.start.x.max(line.end.x));
let (y_lo, y_hi) = (line.start.y.min(line.end.y), line.start.y.max(line.end.y));
let c_lo = clamped_index((x_lo - t.origin_x) / t.pixel_width - 1.0, col0, col1);
let c_hi = clamped_index((x_hi - t.origin_x) / t.pixel_width + 2.0, col0, col1);
let r_lo = clamped_index((t.origin_y - y_hi) / t.pixel_height - 1.0, row0, row1);
let r_hi = clamped_index((t.origin_y - y_lo) / t.pixel_height + 2.0, row0, row1);
hit_cols.clear();
hit_cols.extend((c_lo..c_hi).filter(|&c| {
let cell = &col_cells[(c - col0) as usize];
cell.min().x <= x_hi && cell.max().x >= x_lo
}));
for r in r_lo..r_hi {
let ri = (r - row0) as usize;
let cell = &row_cells[ri];
if cell.min().y <= y_hi && cell.max().y >= y_lo {
for &c in &hit_cols {
boundary[ri * cols + (c - col0) as usize] = true;
}
}
if y_lo <= centre_y[ri] && centre_y[ri] < y_hi {
let delta = if line.start.y < line.end.y { 1 } else { -1 };
let ring = u32::try_from(index).expect("fewer than 2^32 rings");
per_row[ri] += 1;
crossing_rows.push((
r,
Crossing {
x: x_lo,
delta,
ring,
},
));
}
}
}
}
let mut start = 0;
for count in &mut per_row {
let n = *count;
*count = start;
start += n;
}
let mut crossings = vec![
Crossing {
x: 0.0,
delta: 0,
ring: 0
};
crossing_rows.len()
];
let mut next = per_row.clone();
for (r, c) in crossing_rows {
let ri = (r - row0) as usize;
crossings[next[ri]] = c;
next[ri] += 1;
}
let planar_cell = t.pixel_width * t.pixel_height;
let window = cols * rows;
let mut weights = Vec::with_capacity(window);
let mut sweep = Sweep::new(&rings);
let mut inside = vec![false; cols];
for (ri, row) in (row0..row1).enumerate() {
let row_crossings = &mut crossings[per_row[ri]..per_row[ri + 1]];
row_crossings.sort_by(|a, b| b.x.total_cmp(&a.x));
let mut k = 0;
for ci in (0..cols).rev() {
while k < row_crossings.len() && row_crossings[k].x > centre_x[ci] {
sweep.apply(&row_crossings[k]);
k += 1;
}
inside[ci] = sweep.parts_inside > 0;
}
sweep.reset(row_crossings);
let area_m2 = grid.cell_area_m2(row);
for (ci, col) in (col0..col1).enumerate() {
let fraction = if boundary[ri * cols + ci] {
let cell = grid.cell_rect(col, row);
(clipped_area(shape, &cell) / planar_cell).min(1.0)
} else if inside[ci] {
1.0
} else {
0.0
};
if fraction > 0.0 {
weights.push(CellWeight {
col,
row,
fraction,
area_m2,
});
}
}
}
weights.shrink_to_fit();
weights
}
#[cfg(test)]
mod tests {
use super::*;
use geo::{Area, LineString, MultiPolygon, Polygon, polygon};
use geolith::terrain::crs::Crs;
use geolith::terrain::dem::{Dem, GeoTransform};
fn grid() -> Grid {
Grid {
width: 40,
height: 20,
transform: GeoTransform {
origin_x: 0.0,
origin_y: 1.0,
pixel_width: 0.05,
pixel_height: 0.05,
},
}
}
fn global() -> Grid {
Grid {
width: 7200,
height: 3600,
transform: GeoTransform {
origin_x: -180.0,
origin_y: 90.0,
pixel_width: 0.05,
pixel_height: 0.05,
},
}
}
fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> Polygon<f64> {
polygon![(x: x0, y: y0), (x: x1, y: y0), (x: x1, y: y1), (x: x0, y: y1), (x: x0, y: y0)]
}
fn total_fraction(weights: &[CellWeight]) -> f64 {
weights.iter().map(|w| w.fraction).sum()
}
fn boundary_index(
shape: &MultiPolygon<f64>,
) -> rstar::RTree<rstar::primitives::Rectangle<[f64; 2]>> {
let segments = shape
.iter()
.flat_map(|p| std::iter::once(p.exterior()).chain(p.interiors()))
.flat_map(LineString::lines)
.map(|l| {
rstar::primitives::Rectangle::from_corners(
[l.start.x, l.start.y],
[l.end.x, l.end.y],
)
})
.collect();
rstar::RTree::bulk_load(segments)
}
fn reference_cell_weights(shape: &MultiPolygon<f64>, grid: &Grid) -> Vec<CellWeight> {
use geo::{Contains, Point};
use rstar::AABB;
let Some(bbox) = shape.bounding_rect() else {
return Vec::new();
};
let t = &grid.transform;
let (col0, col1) = cell_range(
bbox.min().x,
bbox.max().x,
t.origin_x,
t.pixel_width,
grid.width,
);
let (row0, row1) = cell_range(
-bbox.max().y,
-bbox.min().y,
-t.origin_y,
t.pixel_height,
grid.height,
);
let boundary = boundary_index(shape);
let planar_cell = t.pixel_width * t.pixel_height;
let window = (col1 - col0) as usize * (row1 - row0) as usize;
let mut weights = Vec::with_capacity(window);
for row in row0..row1 {
let area_m2 = grid.cell_area_m2(row);
for col in col0..col1 {
let cell = grid.cell_rect(col, row);
let envelope =
AABB::from_corners([cell.min().x, cell.min().y], [cell.max().x, cell.max().y]);
let on_boundary = boundary
.locate_in_envelope_intersecting(envelope)
.next()
.is_some();
let fraction = if on_boundary {
(clipped_area(shape, &cell) / planar_cell).min(1.0)
} else if shape.contains(&Point::from(cell.center())) {
1.0
} else {
0.0
};
if fraction > 0.0 {
weights.push(CellWeight {
col,
row,
fraction,
area_m2,
});
}
}
}
weights
}
fn ndvi() -> Grid {
Grid {
width: 120_960,
height: 47_040,
transform: GeoTransform {
origin_x: -180.001_488_095_238_1,
origin_y: 80.001_488_095_238_09,
pixel_width: 0.002_976_190_476_204,
pixel_height: 0.002_976_190_476_204,
},
}
}
fn scanline_shapes(grid: &Grid, col: u32, row: u32) -> Vec<(&'static str, MultiPolygon<f64>)> {
let t = grid.transform;
let corner = grid.cell_rect(col, row);
let (x0, y0) = (corner.min().x, corner.max().y);
let at = |u: f64, v: f64| coord! { x: x0 + u * t.pixel_width, y: y0 - v * t.pixel_height };
let ring = |points: &[(f64, f64)]| {
let mut coords: Vec<Coord<f64>> = points.iter().map(|&(u, v)| at(u, v)).collect();
coords.push(coords[0]);
LineString::new(coords)
};
let boxed =
|u0: f64, v0: f64, u1: f64, v1: f64| ring(&[(u0, v0), (u1, v0), (u1, v1), (u0, v1)]);
let centre = |c: u32, r: u32| grid.cell_rect(col + c, row + r).center();
let on_centre = centre(10, 10);
let mut vertex_on_centre = vec![at(1.3, 2.2), on_centre, at(21.7, 3.4), at(12.2, 19.6)];
vertex_on_centre.push(vertex_on_centre[0]);
let centre_row = centre(0, 12).y;
let mut horizontal = vec![
coord! { x: at(3.1, 0.0).x, y: centre_row },
coord! { x: at(22.9, 0.0).x, y: centre_row },
at(18.4, 2.6),
at(9.7, 1.2),
];
horizontal.push(horizontal[0]);
let (nw, se) = (
grid.cell_rect(col + 3, row + 4),
grid.cell_rect(col + 17, row + 21),
);
let aligned = Rect::new(
coord! { x: nw.min().x, y: nw.max().y },
coord! { x: se.max().x, y: se.min().y },
);
vec![
(
"cell-aligned square",
MultiPolygon::new(vec![aligned.to_polygon()]),
),
(
"square",
MultiPolygon::new(vec![Polygon::new(boxed(2.3, 2.7, 20.6, 18.2), vec![])]),
),
(
"hole",
MultiPolygon::new(vec![Polygon::new(
boxed(1.1, 1.4, 25.9, 24.2),
vec![boxed(6.5, 7.25, 15.75, 16.1)],
)]),
),
(
"part in a hole",
MultiPolygon::new(vec![
Polygon::new(
boxed(1.1, 1.4, 25.9, 24.2),
vec![boxed(5.5, 6.25, 18.75, 19.1)],
),
Polygon::new(ring(&[(8.2, 9.1), (16.3, 8.4), (12.6, 17.7)]), vec![]),
]),
),
(
"sliver",
MultiPolygon::new(vec![Polygon::new(
ring(&[(0.2, 0.3), (28.7, 25.1), (28.75, 25.0), (0.25, 0.2)]),
vec![],
)]),
),
(
"vertex on a centre",
MultiPolygon::new(vec![Polygon::new(
LineString::new(vertex_on_centre),
vec![],
)]),
),
(
"edge on a centre row",
MultiPolygon::new(vec![Polygon::new(LineString::new(horizontal), vec![])]),
),
]
}
#[test]
fn scanline_and_point_in_polygon_agree() {
let ndvi = ndvi();
let ndvi_col = ((77.0 - ndvi.transform.origin_x) / ndvi.transform.pixel_width) as u32;
let ndvi_row = ((ndvi.transform.origin_y - 20.0) / ndvi.transform.pixel_height) as u32;
let coarse = Grid {
width: 40,
height: 40,
..grid()
};
for (grid, col, row) in [(coarse, 2, 2), (ndvi, ndvi_col, ndvi_row)] {
for (name, shape) in scanline_shapes(&grid, col, row) {
let expected = reference_cell_weights(&shape, &grid);
assert!(!expected.is_empty(), "{name}: the reference has cells");
assert_eq!(
expected.iter().any(|w| w.fraction == 1.0),
name != "sliver",
"{name}: whole cells"
);
assert!(
cell_weights(&shape, &grid) == expected,
"{name} on {grid:?}"
);
}
}
}
#[test]
fn a_cell_fully_inside_has_fraction_one() {
let shape = MultiPolygon::new(vec![rect(0.0, 0.9, 0.1, 1.0)]);
let weights = cell_weights(&shape, &grid());
assert_eq!(weights.len(), 4);
for w in &weights {
assert!((w.fraction - 1.0).abs() < 1e-12, "{w:?}");
}
}
#[test]
fn half_a_cell_has_fraction_one_half() {
let shape = MultiPolygon::new(vec![rect(0.0, 0.95, 0.025, 1.0)]);
let weights = cell_weights(&shape, &grid());
assert_eq!(weights.len(), 1);
let w = weights
.iter()
.find(|w| w.col == 0 && w.row == 0)
.expect("cell (0, 0) is covered");
assert!((w.fraction - 0.5).abs() < 1e-12, "{w:?}");
}
#[test]
fn a_polygon_smaller_than_a_cell_gets_one_cell() {
let shape = MultiPolygon::new(vec![rect(0.12, 0.82, 0.13, 0.83)]);
let weights = cell_weights(&shape, &grid());
assert_eq!(weights.len(), 1);
let w = weights
.iter()
.find(|w| w.col == 2 && w.row == 3)
.expect("cell (2, 3) is covered");
assert!((w.fraction - 0.04).abs() < 1e-12, "{w:?}");
}
#[test]
fn fractions_add_up_to_the_planar_area() {
let triangle = polygon![(x: 0.013, y: 0.31), (x: 0.71, y: 0.42), (x: 0.2, y: 0.97)];
let expected = triangle.unsigned_area();
let weights = cell_weights(&MultiPolygon::new(vec![triangle]), &grid());
let covered = total_fraction(&weights) * 0.0025;
assert!((covered - expected).abs() < 1e-9, "{covered} vs {expected}");
}
#[test]
fn holes_are_excluded() {
let outer = rect(0.0, 0.0, 0.2, 0.2).exterior().clone();
let hole: LineString<f64> = rect(0.05, 0.05, 0.15, 0.15).exterior().clone();
let shape = MultiPolygon::new(vec![Polygon::new(outer, vec![hole])]);
let weights = cell_weights(&shape, &grid());
let total = total_fraction(&weights);
assert!((total - 12.0).abs() < 1e-9, "{total}");
}
#[test]
fn cell_areas_cover_the_sphere() {
let g = global();
let sum: f64 = (0..g.height).map(|row| g.cell_area_m2(row) * 7200.0).sum();
let sphere = 4.0 * std::f64::consts::PI * EARTH_RADIUS_M * EARTH_RADIUS_M;
assert!(((sum - sphere) / sphere).abs() < 1e-9, "{sum} vs {sphere}");
}
#[test]
fn a_cell_at_sixty_degrees_is_half_the_equator_cell() {
let g = global();
let ratio = g.cell_area_m2(600) / g.cell_area_m2(1800);
assert!((ratio - 0.5).abs() < 0.001, "{ratio}");
}
#[test]
fn grid_match_tolerates_stored_pixel_rounding() {
let final_grid = global();
let mut prelim = global();
prelim.transform.pixel_width = 0.050_000_000_745_058;
prelim.transform.pixel_height = 0.050_000_000_745_058;
assert!(final_grid.matches(&prelim));
let mut shifted = global();
shifted.transform.origin_x += 0.05;
assert!(!final_grid.matches(&shifted));
let mut wider = global();
wider.width = 7201;
assert!(!final_grid.matches(&wider));
}
#[test]
fn grid_tolerance_scales_with_width() {
let base = global();
let mut rounded = global();
rounded.transform.pixel_width = 0.050_000_000_745_058;
assert!(
base.matches(&rounded),
"stored rounding moves the edge 5.4e-6°"
);
let mut drifted = global();
drifted.transform.pixel_width = 0.05 + 1e-6;
assert!(!base.matches(&drifted));
let mut drifted_y = global();
drifted_y.transform.pixel_height = 0.05 + 1e-6;
assert!(!base.matches(&drifted_y));
let small = |pixel: f64| Grid {
width: 2,
height: 1,
transform: GeoTransform {
origin_x: 70.0,
origin_y: 30.0,
pixel_width: pixel,
pixel_height: 0.05,
},
};
assert!(small(0.05).matches(&small(0.05 + 1e-6)));
let mut nudged = global();
nudged.transform.origin_y += 4e-5;
assert!(base.matches(&nudged));
nudged.transform.origin_y += 2e-5;
assert!(!base.matches(&nudged));
}
#[test]
fn a_non_wgs84_dem_is_rejected() {
let dem = Dem {
width: 2,
height: 2,
values: vec![0.0; 4],
transform: GeoTransform {
origin_x: 0.0,
origin_y: 0.0,
pixel_width: 10.0,
pixel_height: 10.0,
},
crs: Crs::WebMercator,
};
let err = Grid::from_dem(&dem).expect_err("web mercator is rejected");
assert!(format!("{err}").contains("EPSG:4326"), "{err}");
}
#[test]
fn a_non_finite_vertex_gives_no_cells() {
let square = rect(0.5, 0.2, 0.7, 0.4);
assert!(!cell_weights(&MultiPolygon::new(vec![square.clone()]), &grid()).is_empty());
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
let broken = polygon![
(x: 0.5, y: 0.2), (x: bad, y: 0.2), (x: 0.7, y: 0.4), (x: 0.5, y: 0.4), (x: 0.5, y: 0.2)
];
let shape = MultiPolygon::new(vec![square.clone(), broken]);
assert!(cell_weights(&shape, &grid()).is_empty(), "x = {bad}");
let flipped = polygon![
(x: 0.5, y: 0.2), (x: 0.7, y: bad), (x: 0.7, y: 0.4), (x: 0.5, y: 0.2)
];
let shape = MultiPolygon::new(vec![flipped]);
assert!(cell_weights(&shape, &grid()).is_empty(), "y = {bad}");
}
}
}