crates/korp-map-quality/src/metrics.rs
//! **The metrics.** From the server replies ([`data_metrics`]) and from the rendered
//! pixels ([`pixel_metrics`]), each against the same land reference on the same pixel
//! grid, so a number from the data and a number from the screen mean the same thing.
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use crate::geo::{Grid, ring_area_km2};
use crate::raster::{self, Component, Rule};
use crate::wire::{Feature, Geom, Pt, Reply};
/// A fixed point that must be drawn: deep inside one of Sweden's large lakes (checked
/// against the data: each point lies in the lake's `natural=water` polygon).
#[derive(Clone, Copy, Debug, Serialize)]
pub struct Named {
pub name: &'static str,
pub lon: f64,
pub lat: f64,
}
/// Twelve of the largest lakes, a point well inside each.
pub const NAMED_LAKES: [Named; 12] = [
Named {
name: "Vänern",
lon: 13.30,
lat: 58.90,
},
Named {
name: "Vättern",
lon: 14.55,
lat: 58.35,
},
Named {
name: "Mälaren",
lon: 17.62,
lat: 59.38,
},
Named {
name: "Hjälmaren",
lon: 15.95,
lat: 59.25,
},
Named {
name: "Storsjön",
lon: 14.30,
lat: 63.22,
},
Named {
name: "Siljan",
lon: 14.78,
lat: 60.88,
},
Named {
name: "Torneträsk",
lon: 19.20,
lat: 68.35,
},
Named {
name: "Uddjaure",
lon: 17.80,
lat: 65.95,
},
Named {
name: "Akkajaure",
lon: 17.65,
lat: 67.65,
},
Named {
name: "Bolmen",
lon: 13.68,
lat: 56.95,
},
Named {
name: "Runn",
lon: 15.70,
lat: 60.55,
},
Named {
name: "Ringsjön",
lon: 13.55,
lat: 55.90,
},
];
/// What an area row is, by its tags — the classes facett-map fills (water, green,
/// building) and the rest.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
#[serde(rename_all = "snake_case")]
pub enum Class {
/// natural=water/lake/bay/wetland, any `water=*`, waterway=riverbank/dock/basin.
Water,
/// natural=wood/forest/scrub/grassland/heath, leisure=park/garden/nature_reserve/
/// recreation_ground (an outline tagged `boundary` too), any landuse.
Green,
/// building=*, amenity=* (facett-map fills both alike).
Building,
/// Bare ground: natural=bare_rock/glacier/scree/sand/beach/shingle/fell/… — the
/// mountains are made of it.
Bare,
/// Another surface (amenity, man_made, aeroway, other leisure, …).
Other,
/// Not a surface: an administrative or protected-area boundary, a place outline.
Boundary,
}
impl Class {
const fn bit(self) -> u8 {
match self {
Self::Water => 1,
Self::Green => 2,
Self::Building => 4,
Self::Bare => 8,
Self::Other => 16,
Self::Boundary => 32,
}
}
/// The surface classes facett-map fills today.
pub const FILLED: u8 = 1 | 2 | 4;
/// Every class that is a surface.
pub const SURFACE: u8 = 1 | 2 | 4 | 8 | 16;
}
/// Classify an area row's tags (the JSON object osm-katana writes).
#[must_use]
pub fn classify(tags: &str) -> Class {
let t: HashMap<String, serde_json::Value> = serde_json::from_str(tags).unwrap_or_default();
let get = |k: &str| t.get(k).and_then(|v| v.as_str());
let has = |k: &str| t.contains_key(k);
if matches!(get("natural"), Some("water" | "lake" | "bay" | "wetland"))
|| has("water")
|| matches!(get("waterway"), Some("riverbank" | "dock" | "basin"))
{
return Class::Water;
}
if matches!(
get("natural"),
Some("wood" | "forest" | "scrub" | "grassland" | "heath")
) || matches!(
get("leisure"),
Some("park" | "garden" | "nature_reserve" | "recreation_ground")
) || has("landuse")
{
return Class::Green;
}
if has("building") || has("amenity") {
return Class::Building;
}
if matches!(
get("natural"),
Some(
"bare_rock"
| "glacier"
| "scree"
| "sand"
| "beach"
| "shingle"
| "fell"
| "tundra"
| "mud"
| "rock"
| "stone"
| "shoal"
)
) {
return Class::Bare;
}
if has("boundary") || has("place") || has("admin_level") || t.is_empty() {
return Class::Boundary;
}
Class::Other
}
/// Gap rule: an enclosed component of uncovered land is a gap (a sliver or a hole
/// between neighbours) when it is tiny or thin.
pub const GAP_MAX_TINY_PX: usize = 16;
/// Mean thickness (pixels ÷ longest bbox side) at or under which an enclosed component
/// is a sliver.
pub const GAP_MAX_THICKNESS: f64 = 2.0;
/// Gaps among `comps`.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Gaps {
/// Enclosed tiny-or-thin components.
pub count: usize,
pub pixels: usize,
/// The largest gap's pixels.
pub largest: usize,
/// Every enclosed component of uncovered land, gap or not (holes of any size).
pub enclosed_count: usize,
pub enclosed_pixels: usize,
/// Tiny-or-thin enclosed components a line feature runs through — a road, rail or
/// stream corridor between two areas, not a gap between neighbours.
pub corridor_count: usize,
pub corridor_pixels: usize,
}
#[must_use]
pub fn gaps(comps: &[Component]) -> Gaps {
let mut g = Gaps::default();
for c in comps.iter().filter(|c| c.enclosed && !c.touches_edge) {
g.enclosed_count += 1;
g.enclosed_pixels += c.pixels;
let side = (c.bbox[2] - c.bbox[0] + 1).max(c.bbox[3] - c.bbox[1] + 1);
if c.pixels <= GAP_MAX_TINY_PX || (c.pixels as f64) / (side as f64) <= GAP_MAX_THICKNESS {
if c.marked {
g.corridor_count += 1;
g.corridor_pixels += c.pixels;
continue;
}
g.count += 1;
g.pixels += c.pixels;
g.largest = g.largest.max(c.pixels);
}
}
g
}
/// One large area of the reply and a pixel well inside it.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Largest {
pub class: Class,
pub id: i64,
pub name: Option<String>,
pub km2: f64,
/// A canvas pixel inside it (the inside pixel nearest its inside-pixel centroid).
pub px: Option<[u32; 2]>,
}
/// A named lake's presence.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct NamedHit {
pub name: String,
/// The point's canvas pixel, when it is on the canvas.
pub px: Option<[u32; 2]>,
/// The reply holds a water polygon around the point.
pub in_data: Option<bool>,
/// The pixel is drawn (not background) and blue-ish.
pub drawn: Option<bool>,
}
/// Everything measured from the replies of one view.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct DataMetrics {
pub view: String,
pub style: String,
pub server: String,
pub replies: Vec<serde_json::Value>,
pub bytes: usize,
/// The slowest kind's time to headers (the viewer asks every kind at once).
pub server_ms: f64,
/// The slowest kind, request → last byte.
pub fetch_ms: f64,
pub decode_ms: f64,
pub rows: usize,
pub vertices: usize,
/// Rows / vertices of features whose box meets the canvas (the request is padded).
pub rows_on_canvas: usize,
pub vertices_on_canvas: usize,
pub truncated: Vec<String>,
pub errors: Vec<String>,
/// Area rows by class.
pub area_rows: HashMap<Class, usize>,
pub area_vertices: HashMap<Class, usize>,
/// Land pixels on the canvas (from the land reference).
pub land_px: usize,
/// % of land covered by a filled class (water, green, building) in the data.
pub coverage_filled_pct: f64,
/// % of land covered by any surface class in the data (adds bare ground, other).
pub coverage_surface_pct: f64,
/// % of land covered by each class.
pub coverage_by_class_pct: HashMap<Class, f64>,
/// Gaps between filled areas, in the data rasterised at the view's resolution.
pub gaps: Gaps,
pub largest: Vec<Largest>,
pub named: Vec<NamedHit>,
pub points_rows: usize,
}
/// Measure one view's replies.
#[must_use]
pub fn data_metrics(view: &crate::view::View, replies: &[Reply], land: &[bool]) -> DataMetrics {
let grid = view.grid();
let (w, h) = (grid.width as usize, grid.height as usize);
let vb = grid.bbox();
let mut m = DataMetrics {
view: view.name.clone(),
..DataMetrics::default()
};
for r in replies {
m.bytes += r.bytes;
m.server_ms = m.server_ms.max(r.ttfb_ms);
m.fetch_ms = m.fetch_ms.max(r.total_ms);
m.decode_ms += r.decode_ms;
m.rows += r.rows;
m.vertices += r.vertices;
if r.meta.get("truncated").is_some_and(|t| t == "true") {
m.truncated.push(r.kind.clone());
}
if let Some(e) = &r.error {
m.errors.push(format!("{}: {e}", r.kind));
}
m.replies.push(serde_json::to_value(r).unwrap_or_default());
for f in &r.features {
if meets(&f.geom, &vb) {
m.rows_on_canvas += 1;
m.vertices_on_canvas += f.geom.vertices();
}
}
if r.kind == "points" {
m.points_rows += r.rows;
}
}
// Rasterise every area by class onto the canvas.
let mut cover = vec![0u8; w * h];
let mut big: Vec<(Class, f64, &Feature)> = Vec::new();
for f in replies
.iter()
.filter(|r| r.kind == "areas")
.flat_map(|r| &r.features)
{
let Geom::Areas(polys) = &f.geom else {
continue;
};
let class = classify(&f.tags);
*m.area_rows.entry(class).or_default() += 1;
*m.area_vertices.entry(class).or_default() += f.geom.vertices();
if class == Class::Boundary || !meets(&f.geom, &vb) {
continue;
}
let bit = class.bit();
for p in polys {
let rings: Vec<Vec<(f64, f64)>> = p
.iter()
.map(|r| r.iter().map(|q| grid.to_px(q[0], q[1])).collect())
.collect();
raster::fill(
grid.width,
grid.height,
rings.iter().map(Vec::as_slice),
Rule::EvenOdd,
|y, a, b| {
for c in &mut cover[y * w + a..y * w + b] {
*c |= bit;
}
},
);
}
if matches!(class, Class::Water | Class::Green) {
let km2: f64 = polys
.iter()
.map(|p| {
p.iter()
.enumerate()
.map(|(i, r)| {
if i == 0 {
ring_area_km2(r).abs()
} else {
-ring_area_km2(r).abs()
}
})
.sum::<f64>()
})
.sum();
big.push((class, km2, f));
}
}
m.land_px = land.iter().filter(|&&l| l).count();
if m.land_px > 0 {
let pct = |mask: u8| -> f64 {
let n = land
.iter()
.zip(&cover)
.filter(|&(&l, &c)| l && c & mask != 0)
.count();
100.0 * n as f64 / m.land_px as f64
};
m.coverage_filled_pct = pct(Class::FILLED);
m.coverage_surface_pct = pct(Class::SURFACE);
for c in [
Class::Water,
Class::Green,
Class::Building,
Class::Bare,
Class::Other,
] {
m.coverage_by_class_pct.insert(c, pct(c.bit()));
}
// Every line of the reply, 1 px thin: an unfilled strip a road, rail or stream
// runs through is a corridor, not a gap between neighbours.
let mut lines = vec![false; w * h];
for f in replies
.iter()
.filter(|r| r.kind == "lines")
.flat_map(|r| &r.features)
{
if let Geom::Lines(ls) = &f.geom {
for l in ls {
let p: Vec<(f64, f64)> = l.iter().map(|q| grid.to_px(q[0], q[1])).collect();
raster::polyline(grid.width, grid.height, &p, |i| lines[i] = true);
}
}
}
let comps = raster::components(
w,
h,
|i| land[i] && cover[i] & Class::FILLED == 0,
|i| cover[i] & Class::FILLED != 0,
|i| lines[i],
);
m.gaps = gaps(&comps);
}
// The largest water and green areas on the canvas, ten of each, with a pixel inside.
for class in [Class::Water, Class::Green] {
let mut v: Vec<_> = big.iter().filter(|b| b.0 == class).collect();
v.sort_by(|a, b| b.1.total_cmp(&a.1));
for (c, km2, f) in v.into_iter().take(10) {
m.largest.push(Largest {
class: *c,
id: f.id,
name: tag(&f.tags, "name"),
km2: *km2,
px: inside_pixel(&grid, &f.geom),
});
}
}
// Named lakes.
let water: Vec<&Feature> = replies
.iter()
.filter(|r| r.kind == "areas")
.flat_map(|r| &r.features)
.filter(|f| classify(&f.tags) == Class::Water)
.collect();
for n in NAMED_LAKES {
let px = on_canvas(&grid, n.lon, n.lat);
let in_data = px.map(|_| water.iter().any(|f| contains(&f.geom, [n.lon, n.lat])));
m.named.push(NamedHit {
name: n.name.into(),
px,
in_data,
drawn: None,
});
}
m
}
fn tag(tags: &str, k: &str) -> Option<String> {
let t: HashMap<String, serde_json::Value> = serde_json::from_str(tags).ok()?;
t.get(k)?.as_str().map(str::to_string)
}
/// The canvas pixel of a lon/lat, if on the canvas.
#[must_use]
pub fn on_canvas(grid: &Grid, lon: f64, lat: f64) -> Option<[u32; 2]> {
let (x, y) = grid.to_px(lon, lat);
(x >= 0.0 && y >= 0.0 && x < f64::from(grid.width) && y < f64::from(grid.height))
.then_some([x as u32, y as u32])
}
/// Does the geometry's box meet `b`?
#[must_use]
pub fn meets(g: &Geom, b: &[f64; 4]) -> bool {
let mut bb = [f64::MAX, f64::MAX, f64::MIN, f64::MIN];
let mut add = |p: &Pt| {
bb[0] = bb[0].min(p[0]);
bb[1] = bb[1].min(p[1]);
bb[2] = bb[2].max(p[0]);
bb[3] = bb[3].max(p[1]);
};
match g {
Geom::Point(p) => add(p),
Geom::Lines(l) => l.iter().flatten().for_each(&mut add),
Geom::Areas(a) => a.iter().flatten().flatten().for_each(&mut add),
}
bb[0] <= b[2] && bb[2] >= b[0] && bb[1] <= b[3] && bb[3] >= b[1]
}
/// Even-odd point in polygon over every polygon's rings.
#[must_use]
pub fn contains(g: &Geom, p: Pt) -> bool {
let Geom::Areas(polys) = g else { return false };
polys.iter().any(|rings| {
let mut inside = false;
for r in rings {
let n = r.len();
let mut j = n.wrapping_sub(1);
for i in 0..n {
let (a, b) = (r[i], r[j]);
if (a[1] > p[1]) != (b[1] > p[1])
&& p[0] < (b[0] - a[0]) * (p[1] - a[1]) / (b[1] - a[1]) + a[0]
{
inside = !inside;
}
j = i;
}
}
inside
})
}
/// A pixel inside an area on the canvas: the inside pixel nearest the mean of its inside
/// pixels.
#[must_use]
pub fn inside_pixel(grid: &Grid, g: &Geom) -> Option<[u32; 2]> {
let Geom::Areas(polys) = g else { return None };
let mut px: Vec<(usize, usize, usize)> = Vec::new();
for p in polys {
let rings: Vec<Vec<(f64, f64)>> = p
.iter()
.map(|r| r.iter().map(|q| grid.to_px(q[0], q[1])).collect())
.collect();
raster::fill(
grid.width,
grid.height,
rings.iter().map(Vec::as_slice),
Rule::EvenOdd,
|y, a, b| {
px.push((y, a, b));
},
);
}
let (mut sx, mut sy, mut n) = (0.0, 0.0, 0.0);
for &(y, a, b) in &px {
let k = (b - a) as f64;
sx += (a + b - 1) as f64 / 2.0 * k;
sy += y as f64 * k;
n += k;
}
if n == 0.0 {
return None;
}
let (cx, cy) = (sx / n, sy / n);
let mut best: Option<([u32; 2], f64)> = None;
for &(y, a, b) in &px {
let x = (cx.round() as usize).clamp(a, b - 1);
let d = (x as f64 - cx).powi(2) + (y as f64 - cy).powi(2);
if best.is_none_or(|(_, bd)| d < bd) {
best = Some(([x as u32, y as u32], d));
}
}
best.map(|b| b.0)
}
// ── pixels ───────────────────────────────────────────────────────────────────────────
/// The viewer's own overlay on the map area (a status strip at the bottom right, the
/// GPU badge at the top left; the title strip above the map area is cropped off by
/// `browser/render.py`): never measured.
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct Hud {
pub top: u32,
pub bottom: u32,
/// `[x0, y0, x1, y1]` of the badge.
pub badge: [u32; 4],
}
impl Default for Hud {
fn default() -> Self {
Self {
top: 0,
bottom: 26,
badge: [0, 0, 34, 22],
}
}
}
impl Hud {
#[must_use]
pub fn hides(&self, w: u32, h: u32, x: u32, y: u32) -> bool {
y < self.top
|| y >= h.saturating_sub(self.bottom)
|| (x >= self.badge[0] && x < self.badge[2] && y >= self.badge[1] && y < self.badge[3])
|| x >= w
}
}
/// An RGB image.
#[derive(Clone, Debug)]
pub struct Rgb {
pub width: u32,
pub height: u32,
pub px: Vec<[u8; 3]>,
}
/// Everything measured from one rendered view.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct PixelMetrics {
pub view: String,
pub width: u32,
pub height: u32,
pub background: String,
/// Land pixels measured (land reference minus the HUD).
pub land_px: usize,
/// % of land pixels drawn (not background): "no black land" is 100.
pub coverage_pct: f64,
/// % of land pixels that are background — black land.
pub black_land_pct: f64,
pub green_pct: f64,
pub blue_pct: f64,
/// Background pixels on land fully enclosed by drawn pixels (tiny or thin).
pub gaps: Gaps,
pub named: Vec<NamedHit>,
/// Of the data's largest water/green areas on the canvas: how many are drawn.
pub largest_drawn: usize,
pub largest_total: usize,
pub largest_missing: Vec<String>,
}
/// Background test: every channel within `tol` of `bg`.
#[must_use]
pub fn is_bg(p: [u8; 3], bg: [u8; 3], tol: u8) -> bool {
p.iter().zip(bg).all(|(&a, b)| a.abs_diff(b) <= tol)
}
fn blueish(p: [u8; 3]) -> bool {
i32::from(p[2]) > i32::from(p[0]) + 20 && p[2] >= p[1]
}
fn greenish(p: [u8; 3]) -> bool {
i32::from(p[1]) > i32::from(p[0]) + 12 && p[1] > p[2]
}
/// The background colour: the most common colour among off-land pixels (sea and abroad,
/// which the viewer leaves bare), when there are enough of them.
#[must_use]
pub fn background_of(img: &Rgb, land: &[bool], hud: &Hud) -> Option<[u8; 3]> {
let mut hist: HashMap<[u8; 3], usize> = HashMap::new();
let mut n = 0;
for (i, p) in img.px.iter().enumerate() {
let (x, y) = (
(i % img.width as usize) as u32,
(i / img.width as usize) as u32,
);
if land[i] || hud.hides(img.width, img.height, x, y) {
continue;
}
*hist.entry(*p).or_default() += 1;
n += 1;
}
let (c, k) = hist.into_iter().max_by_key(|e| e.1)?;
(n > img.px.len() / 100 && k * 4 > n).then_some(c)
}
/// Measure one rendered view against the land reference.
#[must_use]
pub fn pixel_metrics(
view: &crate::view::View,
img: &Rgb,
land: &[bool],
bg: [u8; 3],
tol: u8,
hud: &Hud,
data: Option<&DataMetrics>,
) -> PixelMetrics {
let (w, h) = (img.width as usize, img.height as usize);
let grid = view.grid();
let measured =
|i: usize| land[i] && !hud.hides(img.width, img.height, (i % w) as u32, (i / w) as u32);
let mut m = PixelMetrics {
view: view.name.clone(),
width: img.width,
height: img.height,
background: format!("#{:02x}{:02x}{:02x}", bg[0], bg[1], bg[2]),
..PixelMetrics::default()
};
let (mut drawn, mut green, mut blue) = (0usize, 0usize, 0usize);
for i in 0..w * h {
if !measured(i) {
continue;
}
m.land_px += 1;
let p = img.px[i];
if !is_bg(p, bg, tol) {
drawn += 1;
}
if greenish(p) {
green += 1;
}
if blueish(p) {
blue += 1;
}
}
if m.land_px > 0 {
let pct = |n: usize| 100.0 * n as f64 / m.land_px as f64;
m.coverage_pct = pct(drawn);
m.black_land_pct = 100.0 - m.coverage_pct;
m.green_pct = pct(green);
m.blue_pct = pct(blue);
let comps = raster::components(
w,
h,
|i| measured(i) && is_bg(img.px[i], bg, tol),
|i| measured(i) && !is_bg(img.px[i], bg, tol),
|_| false,
);
m.gaps = gaps(&comps);
}
let drawn_at = |px: [u32; 2], want_blue: bool| -> bool {
// 3×3 majority, so one anti-aliased line pixel decides nothing.
let mut yes = 0;
for dy in -1i64..=1 {
for dx in -1i64..=1 {
let (x, y) = (i64::from(px[0]) + dx, i64::from(px[1]) + dy);
if x < 0 || y < 0 || x >= w as i64 || y >= h as i64 {
continue;
}
let p = img.px[y as usize * w + x as usize];
if !is_bg(p, bg, tol) && (!want_blue || blueish(p)) {
yes += 1;
}
}
}
yes >= 5
};
for n in NAMED_LAKES {
let px = on_canvas(&grid, n.lon, n.lat)
.filter(|p| !hud.hides(img.width, img.height, p[0], p[1]));
let in_data = data
.and_then(|d| d.named.iter().find(|x| x.name == n.name))
.and_then(|x| x.in_data);
m.named.push(NamedHit {
name: n.name.into(),
px,
in_data,
drawn: px.map(|p| drawn_at(p, true)),
});
}
if let Some(d) = data {
for l in &d.largest {
let Some(px) = l.px else { continue };
if hud.hides(img.width, img.height, px[0], px[1]) {
continue;
}
m.largest_total += 1;
if drawn_at(px, false) {
m.largest_drawn += 1;
} else {
m.largest_missing.push(format!(
"{:?} {} ({:.1} km²)",
l.class,
l.name.clone().unwrap_or_else(|| format!("id {}", l.id)),
l.km2
));
}
}
}
m
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn classes_follow_the_viewer_rules() {
assert_eq!(
classify(r#"{"natural":"water","name":"Vänern"}"#),
Class::Water
);
assert_eq!(classify(r#"{"natural":"wetland"}"#), Class::Water);
assert_eq!(classify(r#"{"landuse":"farmland"}"#), Class::Green);
assert_eq!(classify(r#"{"natural":"wood"}"#), Class::Green);
assert_eq!(classify(r#"{"building":"yes"}"#), Class::Building);
assert_eq!(classify(r#"{"natural":"glacier"}"#), Class::Bare);
assert_eq!(
classify(r#"{"boundary":"administrative","admin_level":"7"}"#),
Class::Boundary
);
assert_eq!(
classify(r#"{"boundary":"protected_area","leisure":"nature_reserve"}"#),
Class::Green,
"the viewer paints a nature reserve green, outline or not"
);
assert_eq!(
classify(r#"{"amenity":"parking"}"#),
Class::Building,
"the viewer fills amenity like a building"
);
assert_eq!(classify(r#"{"aeroway":"apron"}"#), Class::Other);
}
#[test]
fn a_sliver_counts_and_a_clearing_does_not() {
let comp = |pixels, bbox: [usize; 4], marked| Component {
pixels,
bbox,
touches_edge: false,
enclosed: true,
marked,
};
let g = gaps(&[
comp(40, [10, 10, 49, 10], false),
comp(400, [0, 0, 19, 19], false),
comp(3, [5, 5, 6, 6], false),
comp(60, [0, 30, 59, 30], true),
]);
assert_eq!(g.count, 2);
assert_eq!(g.pixels, 43);
assert_eq!(g.enclosed_count, 4);
assert_eq!(
(g.corridor_count, g.corridor_pixels),
(1, 60),
"a road strip is a corridor"
);
}
#[test]
fn point_in_multipolygon_respects_holes() {
let outer = vec![
[0.0, 0.0],
[10.0, 0.0],
[10.0, 10.0],
[0.0, 10.0],
[0.0, 0.0],
];
let hole = vec![[4.0, 4.0], [6.0, 4.0], [6.0, 6.0], [4.0, 6.0], [4.0, 4.0]];
let g = Geom::Areas(vec![vec![outer, hole]]);
assert!(contains(&g, [1.0, 1.0]));
assert!(!contains(&g, [5.0, 5.0]));
assert!(!contains(&g, [11.0, 5.0]));
}
#[test]
fn pixels_black_land_and_a_gap() {
use crate::view::{PLACES, View};
let mut v = View::new(&PLACES[1], 16.0);
v.width = 40;
v.height = 20;
let bg = [11, 15, 26];
let green = [20, 54, 31];
// All land; left half drawn green except one pixel (a gap); right half bare.
let land = vec![true; 800];
let mut px = vec![bg; 800];
for y in 0..20 {
for x in 0..20 {
px[y * 40 + x] = green;
}
}
px[10 * 40 + 10] = bg;
let img = Rgb {
width: 40,
height: 20,
px,
};
let hud = Hud {
top: 0,
bottom: 0,
badge: [0, 0, 0, 0],
};
let m = pixel_metrics(&v, &img, &land, bg, 6, &hud, None);
assert!((m.coverage_pct - 100.0 * 399.0 / 800.0).abs() < 1e-9);
assert_eq!(m.gaps.count, 1);
assert_eq!(m.gaps.pixels, 1);
}
}