Modern Apps git

← Modern-Apps.git

library:map: an on-device screenshot harness, and two host probes

Commit
cb5e85c7109bd9b49365ceab4eb4bcf7b44c8890
Author
vayun-mathur <[email protected]>
When
2026-08-27 23:04 UTC (3 months ago)
Parents
c3b42aa

Diff

library/map/build.gradle.kts
diff --git a/library/map/build.gradle.kts b/library/map/build.gradle.ktsindex 41c6df43b3..43cec3ea9c 100644--- a/library/map/build.gradle.kts+++ b/library/map/build.gradle.kts@@ -1,7 +1,11 @@ plugins {     id("common-conventions-library") }-+android {+    defaultConfig {+        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"+    }+} androidComponents {     onVariants { variant ->         variant.sources.jniLibs?.addStaticSourceDirectory(@@ -25,6 +29,20 @@ dependencies {      // :library:image is deliberately gone: it existed to fetch and decode CARTO raster     // PNGs, and there is no raster tile path any more.++    // The on-device screenshot harness (`src/androidTest`), which is the only way to see what+    // the renderer draws: Vulkan needs a real GPU, so the host probes can only measure the CPU+    // pipeline. Coordinates are literal rather than catalog aliases on purpose — these are the+    // only androidTest dependencies in the repo, and adding four aliases to the shared+    // `gradle/libs.versions.toml` for one module's diagnostic is a conflict waiting to happen.+    androidTestImplementation("androidx.test:runner:1.6.2")+    androidTestImplementation("androidx.test:core:1.6.1")+    androidTestImplementation("androidx.test.ext:junit:1.2.1")+    androidTestImplementation(platform(libs.androidx.compose.bom))+    androidTestImplementation(libs.androidx.activity.compose)+    androidTestImplementation(libs.androidx.compose.foundation)+    // Supplies the bare `ComponentActivity` the harness hosts the map in.+    androidTestImplementation("androidx.compose.ui:ui-test-manifest") }  // The Vulkan vector-tile renderer: `library/map/src/main/rust`, on ash.
library/map/src/androidTest/java/com/vayunmathur/library/map/BasemapScreenshotTest.kt
diff --git a/library/map/src/androidTest/java/com/vayunmathur/library/map/BasemapScreenshotTest.kt b/library/map/src/androidTest/java/com/vayunmathur/library/map/BasemapScreenshotTest.ktnew file mode 100644index 0000000000..afac07f721--- /dev/null+++ b/library/map/src/androidTest/java/com/vayunmathur/library/map/BasemapScreenshotTest.kt@@ -0,0 +1,92 @@+package com.vayunmathur.library.map++import android.graphics.Bitmap+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.ui.Modifier+import androidx.test.core.app.ActivityScenario+import androidx.test.platform.app.InstrumentationRegistry+import org.junit.Test+import java.io.File++/**+ * Renders the basemap on a real GPU at a chosen camera and writes a PNG.+ *+ * The renderer cannot be judged on a host: Vulkan needs a device, and the host-side probes+ * (`examples/probe_archive`, `examples/zoom_sweep`) only measure the CPU pipeline — they+ * report tessellated *area*, which is exactly the thing that can be right while the map still+ * looks wrong. This is the only harness that answers "what does it actually look like".+ *+ * It mounts [VectorMap] and nothing else, so the image is the basemap with no app chrome, and+ * it takes the camera from instrumentation arguments so one build can sweep many places:+ *+ * ```text+ * adb shell am instrument -w \+ *   -e class com.vayunmathur.library.map.BasemapScreenshotTest \+ *   -e lon -122.42 -e lat 37.77 -e zoom 11 -e name sf_bay -e dark false \+ *   com.vayunmathur.library.map.test/androidx.test.runner.AndroidJUnitRunner+ * ```+ *+ * The screenshot comes from [android.app.UiAutomation.takeScreenshot] rather than Compose's+ * `captureToImage`, because the map is a `SurfaceView`: its contents belong to SurfaceFlinger+ * and are simply absent from a view-hierarchy capture. A capture that silently returns the+ * background colour would make every one of these images look like the bug being chased.+ */+class BasemapScreenshotTest {++    /** How long to let tiles arrive before capturing. Fetches are network-bound. */+    private val settleMs = 25_000L++    @Test+    fun renders_the_basemap_at_the_requested_camera() {+        val args = InstrumentationRegistry.getArguments()+        val lon = args.getString("lon")?.toDoubleOrNull() ?: 0.0+        val lat = args.getString("lat")?.toDoubleOrNull() ?: 0.0+        val zoom = args.getString("zoom")?.toDoubleOrNull() ?: 2.0+        val dark = args.getString("dark")?.toBooleanStrictOrNull() ?: false+        val muted = args.getString("muted")?.toBooleanStrictOrNull() ?: false+        val name = args.getString("name") ?: "basemap"++        val camera = CameraState(CameraPosition(GeoPoint(lon, lat), zoom))+        var frames = 0++        val scenario = ActivityScenario.launch(ComponentActivity::class.java)+        scenario.onActivity { activity ->+            activity.setContent {+                VectorMap(+                    cameraState = camera,+                    modifier = Modifier.fillMaxSize(),+                    style = if (muted) MapStyle.Muted else MapStyle.Standard,+                    darkBasemap = dark,+                    // The camera is the point of the test, so nothing may move it: the+                    // viewport floor in `CameraState.setViewport` is allowed to raise the+                    // zoom, but a gesture would silently invalidate the file name.+                    onFrame = { frames++ },+                )+            }+        }++        // No `waitForIdle`: the map presents continuously, so an idling-resource wait either+        // never returns or returns before the first tile has arrived. Time is the only honest+        // signal available here, which is why the file records what it actually got.+        Thread.sleep(settleMs)++        val instrumentation = InstrumentationRegistry.getInstrumentation()+        val shot: Bitmap = instrumentation.uiAutomation.takeScreenshot()+            ?: error("takeScreenshot returned nothing; the screen may be off")++        val dir = File(instrumentation.targetContext.filesDir, "basemap-shots").apply { mkdirs() }+        val file = File(dir, "$name.png")+        file.outputStream().use { shot.compress(Bitmap.CompressFormat.PNG, 100, it) }++        println("BASEMAP_SHOT $name z$zoom @$lon,$lat frames=$frames -> ${file.absolutePath}")+        scenario.close()++        // A blank capture is the failure this test exists to make loud: if Vulkan never+        // initialised, or the surface was never composited, the image is one flat colour and+        // no amount of looking at it will say which.+        check(frames > 0) { "no frame was presented; check logcat under MapRenderer" }+        check(file.length() > 0) { "wrote an empty PNG" }+    }+}
library/map/src/main/rust/examples/nodrop_probe.rs
diff --git a/library/map/src/main/rust/examples/nodrop_probe.rs b/library/map/src/main/rust/examples/nodrop_probe.rsnew file mode 100644index 0000000000..0df35cc43f--- /dev/null+++ b/library/map/src/main/rust/examples/nodrop_probe.rs@@ -0,0 +1,410 @@+//! TEMPORARY. Answers one question: what does "keep the nesting regrouping but STOP DROPPING+//! rings" actually cost? Delete once lead has decided.+//!+//! ```text+//! cargo run --offline -q -p map_renderer --example nodrop_probe+//! ```+//!+//! The proposal on the table is to follow MapLibre and stop discarding rings for validity,+//! on the principle that a discarded ring loses real map content. The principle is right -+//! MapLibre's fill path (`src/mln/gfx/fill_generator.cpp:113-125`) is `classifyRings` ->+//! `limitHoles(_, 500)` -> `earcut`, with no validity repair at all - but the principle does+//! not say what the change costs *here*, and the archive's geometry is invalid enough that+//! the cost is not guessable. So this measures three arms against the same exact target+//! rather than arguing from any of them:+//!+//! * **maplibre** - every ring bridged into one earcut call, no regrouping, no drops. This is+//!   both what MapLibre does and what this code did before the sanitiser landed.+//! * **current** - nesting regroup, then drop a hole that straddles its exterior or overlaps a+//!   hole already taken.+//! * **nodrop** - nesting regroup, keep every ring. The proposal.+//!+//! Target is the even-odd region of the rings by scanline, which is what a rasteriser paints+//! and is quantisation-free - not `exterior - sum(holes)`, which double-counts the archive's+//! overlapping holes and reads low.++use map_renderer::tess::earcut;+use map_renderer::tess::fill;++/// Total triangle area from the REAL production tessellator, in tile-normalised units.+///+/// This exists so the `current` arm cannot go stale. `group_rings` below is a copy of+/// `fill::polygons`, and a copy silently stops matching the moment someone edits the original+/// - which happened repeatedly while this was being written. Comparing against the real+/// `fill::tessellate` on every run makes that drift impossible to miss instead of something+/// you have to remember to re-check.+fn production_area(rings: &[Vec<(i32, i32)>], extent: u32) -> f64 {+    let mut v = Vec::new();+    let mut idx = Vec::new();+    fill::tessellate(rings, extent, &mut v, &mut idx);+    let mut total = 0.0f64;+    for tri in idx.chunks_exact(3) {+        let p = |i: u32| {+            let b = i as usize * fill::FLOATS_PER_VERTEX;+            (v[b] as f64, v[b + 1] as f64)+        };+        let (ax, ay) = p(tri[0]);+        let (bx, by) = p(tri[1]);+        let (cx, cy) = p(tri[2]);+        total += ((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)).abs() / 2.0;+    }+    total+}++/// Twice the unsigned area of a ring.+fn ring_area2(ring: &[(i32, i32)]) -> i64 {+    let mut sum = 0i64;+    for i in 0..ring.len() {+        let (x1, y1) = ring[i];+        let (x2, y2) = ring[(i + 1) % ring.len()];+        sum += x1 as i64 * y2 as i64 - x2 as i64 * y1 as i64;+    }+    sum.abs()+}++fn bounds(ring: &[(i32, i32)]) -> (i32, i32, i32, i32) {+    let mut b = (ring[0].0, ring[0].1, ring[0].0, ring[0].1);+    for &(x, y) in &ring[1..] {+        b.0 = b.0.min(x);+        b.1 = b.1.min(y);+        b.2 = b.2.max(x);+        b.3 = b.3.max(y);+    }+    b+}++fn boxes_overlap(a: (i32, i32, i32, i32), b: (i32, i32, i32, i32)) -> bool {+    a.0 <= b.2 && a.2 >= b.0 && a.1 <= b.3 && a.3 >= b.1+}++fn box_area(b: (i32, i32, i32, i32)) -> i64 {+    (b.2 as i64 - b.0 as i64) * (b.3 as i64 - b.1 as i64)+}++/// Even-odd point-in-ring, integer cross product, as `fill.rs` does it.+fn point_in_ring(x: i32, y: i32, ring: &[(i32, i32)]) -> bool {+    let mut inside = false;+    for i in 0..ring.len() {+        let (x1, y1) = ring[i];+        let (x2, y2) = ring[(i + 1) % ring.len()];+        if (y1 > y) != (y2 > y) {+            let dy = y2 as i64 - y1 as i64;+            let along = (x as i64 - x1 as i64) * dy;+            let at = (y as i64 - y1 as i64) * (x2 as i64 - x1 as i64);+            if if dy > 0 { along < at } else { along > at } {+                inside = !inside;+            }+        }+    }+    inside+}++/// Is the point exactly on one of the ring's edges?+///+/// `point_in_ring` is an even-odd crossing test, so it answers inconsistently for a point that+/// lies *on* the boundary. Real coastline holes touch their exterior, so `fill.rs` resolves+/// that deliberately rather than leaving it to the crossing parity, and this copy has to do+/// the same or the `current` arm stops describing the renderer.+fn on_boundary(x: i32, y: i32, ring: &[(i32, i32)]) -> bool {+    for i in 0..ring.len() {+        let (x1, y1) = ring[i];+        let (x2, y2) = ring[(i + 1) % ring.len()];+        let cross = (x as i64 - x1 as i64) * (y2 as i64 - y1 as i64)+            - (y as i64 - y1 as i64) * (x2 as i64 - x1 as i64);+        if cross != 0 {+            continue;+        }+        if x >= x1.min(x2) && x <= x1.max(x2) && y >= y1.min(y2) && y <= y1.max(y2) {+            return true;+        }+    }+    false+}++/// The boundary counts as inside, as `fill::point_within_ring` does.+fn point_within_ring(x: i32, y: i32, ring: &[(i32, i32)]) -> bool {+    point_in_ring(x, y, ring) || on_boundary(x, y, ring)+}++fn rings_overlap(a: &[(i32, i32)], b: &[(i32, i32)]) -> bool {+    a.iter().any(|&(x, y)| point_in_ring(x, y, b))+        || b.iter().any(|&(x, y)| point_in_ring(x, y, a))+}++/// `fill.rs::polygons`, with the two drop tests behind a flag so both arms come from one+/// body and cannot drift apart.+fn group_rings(rings: &[&[(i32, i32)]], drop_conflicts: bool) -> Vec<Vec<usize>> {+    let count = rings.len();+    let boxes: Vec<_> = rings.iter().map(|r| bounds(r)).collect();++    let mut enclosing: Vec<Vec<(usize, usize)>> = vec![Vec::new(); count];+    for j in 0..count {+        for i in 0..count {+            if i == j+                || !boxes_overlap(boxes[i], boxes[j])+                || box_area(boxes[i]) < box_area(boxes[j])+            {+                continue;+            }+            let votes =+                rings[j].iter().filter(|&&(x, y)| point_within_ring(x, y, rings[i])).count();+            if votes * 2 > rings[j].len() {+                enclosing[j].push((i, votes));+            }+        }+    }+    let depth: Vec<usize> = enclosing.iter().map(|e| e.len()).collect();++    let mut groups = Vec::new();+    for exterior in 0..count {+        if depth[exterior] % 2 != 0 {+            continue;+        }+        let mut holes: Vec<(usize, usize)> = Vec::new();+        for j in 0..count {+            if depth[j] % 2 == 0 {+                continue;+            }+            let mut closest: Option<(usize, usize)> = None;+            for &(ring, votes) in &enclosing[j] {+                if closest.map_or(true, |(held, _)| depth[ring] > depth[held]) {+                    closest = Some((ring, votes));+                }+            }+            if closest.is_some_and(|(ring, _)| ring == exterior) {+                holes.push((j, closest.unwrap().1));+            }+        }+        holes.sort_by_cached_key(|&(j, _)| std::cmp::Reverse(ring_area2(rings[j])));++        let mut group = vec![exterior];+        for (j, votes) in holes {+            if drop_conflicts {+                let straddles = votes != rings[j].len();+                let overlaps = group[1..].iter().any(|&k| {+                    boxes_overlap(boxes[j], boxes[k]) && rings_overlap(rings[j], rings[k])+                });+                if straddles || overlaps {+                    continue;+                }+            }+            group.push(j);+        }+        groups.push(group);+    }+    groups+}++fn open_length(ring: &[(i32, i32)]) -> usize {+    let mut n = ring.len();+    while n >= 2 && ring[0] == ring[n - 1] {+        n -= 1;+    }+    n+}++/// Tessellate via `groups`, returning the total triangle area in tile-normalised units.+fn area_of(extent: u32, groups: &[Vec<usize>], open: &[&[(i32, i32)]]) -> f64 {+    let scale = 1.0 / extent as f64;+    let mut total = 0.0f64;+    let mut coords: Vec<i32> = Vec::new();+    let mut hole_starts: Vec<usize> = Vec::new();+    for group in groups {+        coords.clear();+        hole_starts.clear();+        for (position, &r) in group.iter().enumerate() {+            if position > 0 {+                hole_starts.push(coords.len() / 2);+            }+            for &(x, y) in open[r].iter() {+                coords.push(x);+                coords.push(y);+            }+        }+        for tri in earcut::triangulate(&coords, &hole_starts).chunks_exact(3) {+            let p = |i: u32| {+                let b = i as usize * 2;+                (coords[b] as f64 * scale, coords[b + 1] as f64 * scale)+            };+            let (ax, ay) = p(tri[0]);+            let (bx, by) = p(tri[1]);+            let (cx, cy) = p(tri[2]);+            total += ((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)).abs() / 2.0;+        }+    }+    total+}++/// The even-odd region of every ring, by scanline. Quantisation-free.+fn even_odd_area(rings: &[Vec<(i32, i32)>], extent: u32) -> f64 {+    let mut edges: Vec<((i32, i32), (i32, i32))> = Vec::new();+    for ring in rings {+        let n = open_length(ring);+        if n < 3 {+            continue;+        }+        for i in 0..n {+            let (a, b) = (ring[i], ring[(i + 1) % n]);+            if a.1 != b.1 {+                edges.push((a, b));+            }+        }+    }+    if edges.is_empty() {+        return 0.0;+    }+    let lo = edges.iter().map(|e| e.0 .1.min(e.1 .1)).min().unwrap();+    let hi = edges.iter().map(|e| e.0 .1.max(e.1 .1)).max().unwrap();+    let mut xs: Vec<f64> = Vec::new();+    let mut total = 0.0f64;+    for row in lo..hi {+        let y = row as f64 + 0.5;+        xs.clear();+        for &((x1, y1), (x2, y2)) in &edges {+            if (y1 as f64 > y) != (y2 as f64 > y) {+                let t = (y - y1 as f64) / (y2 as f64 - y1 as f64);+                xs.push(x1 as f64 + t * (x2 as f64 - x1 as f64));+            }+        }+        xs.sort_by(|a, b| a.partial_cmp(b).unwrap());+        let mut i = 0;+        while i + 1 < xs.len() {+            total += xs[i + 1] - xs[i];+            i += 2;+        }+    }+    let s = 1.0 / extent as f64;+    total * s * s+}++struct Arm {+    name: &'static str,+    worst: f64,+    lost: f64,+    surplus: f64,+}++fn scan(label: &str, bytes: &[u8], only_big: bool) {+    let tile = tilecodec::mvt::Tile::decode(bytes).expect("tile decodes");+    for layer in &tile.layers {+        let mut arms = [+            Arm { name: "maplibre", worst: 1.0, lost: 0.0, surplus: 0.0 },+            Arm { name: "current", worst: 1.0, lost: 0.0, surplus: 0.0 },+            Arm { name: "nodrop", worst: 1.0, lost: 0.0, surplus: 0.0 },+            Arm { name: "ml+area", worst: 1.0, lost: 0.0, surplus: 0.0 },+            Arm { name: "ml+revsd", worst: 1.0, lost: 0.0, surplus: 0.0 },+            Arm { name: "PROD", worst: 1.0, lost: 0.0, surplus: 0.0 },+        ];+        // Set if the `current` copy ever stops agreeing with the real tessellator.+        let mut drift = 0.0f64;+        let mut groups_seen = 0usize;++        for feature in &layer.features {+            if feature.geom_type != tilecodec::mvt::GeomType::Polygon {+                continue;+            }+            let Some(polys) = tilecodec::mvt::decode_polygons(&feature.geometry) else { continue };+            for rings in &polys {+                if only_big && rings.len() < 50 {+                    continue;+                }+                let want = even_odd_area(rings, layer.extent);+                if want <= 1e-9 {+                    continue;+                }+                groups_seen += 1;++                let mut open: Vec<&[(i32, i32)]> = Vec::new();+                let mut degenerate_exterior = false;+                for (r, ring) in rings.iter().enumerate() {+                    let n = open_length(ring);+                    // `fill::tessellate`'s MIN_RING_COORDS gate, reproduced exactly: a ring+                    // under three vertices encloses nothing, and if it is the EXTERIOR the+                    // whole polygon goes, because a hole with nothing around it would render+                    // as solid fill.+                    if n < 3 {+                        if r == 0 {+                            degenerate_exterior = true;+                            break;+                        }+                        continue;+                    }+                    open.push(&ring[..n]);+                }+                if degenerate_exterior || open.is_empty() {+                    continue;+                }++                // Arm 1: everything bridged into one earcut call, ring order as decoded.+                let flat: Vec<Vec<usize>> = vec![(0..open.len()).collect()];+                let got_ml = area_of(layer.extent, &flat, &open);+                let got_cur = area_of(layer.extent, &group_rings(&open, true), &open);+                let got_nd = area_of(layer.extent, &group_rings(&open, false), &open);++                // Arms 4 and 5: the same rings, holes presented in a different order.+                // `limitHoles` sorts holes by descending area, so if hole order reached+                // earcut's bridging it could explain MapLibre doing better on the same+                // geometry. Exterior stays at index 0; only the holes are permuted.+                let mut by_area: Vec<usize> = (1..open.len()).collect();+                by_area.sort_by_key(|&i| std::cmp::Reverse(ring_area2(open[i])));+                let area_first: Vec<Vec<usize>> =+                    vec![std::iter::once(0).chain(by_area).collect()];+                let got_area = area_of(layer.extent, &area_first, &open);++                let reversed: Vec<Vec<usize>> =+                    vec![std::iter::once(0).chain((1..open.len()).rev()).collect()];+                let got_rev = area_of(layer.extent, &reversed, &open);++                let got_prod = production_area(rings, layer.extent);+                drift = drift.max((got_prod - got_cur).abs());++                for (arm, got) in arms+                    .iter_mut()+                    .zip([got_ml, got_cur, got_nd, got_area, got_rev, got_prod])+                {+                    let ratio = got / want;+                    if (ratio - 1.0).abs() > (arm.worst - 1.0).abs() {+                        arm.worst = ratio;+                    }+                    if got < want {+                        arm.lost += want - got;+                    } else {+                        arm.surplus += got - want;+                    }+                }+            }+        }++        if groups_seen == 0 {+            continue;+        }+        println!("{label} {:<11} {groups_seen:>4} groups", layer.name);+        for arm in &arms {+            println!(+                "    {:<9} worst ratio {:>6.3}   surplus {:>8.5}   LOST {:>8.5}",+                arm.name, arm.worst, arm.surplus, arm.lost,+            );+        }+        // `current` is a copy of `fill::polygons`; PROD is the real thing. They must agree.+        if drift > 1e-9 {+            println!(+                "    !!! STALE: the `current` copy disagrees with fill::tessellate by {drift:.8} \+                 of a tile. `group_rings` no longer matches `fill::polygons` \u{2014} every `current` \+                 figure above is describing code that is not in the renderer.",+            );+        } else {+            println!("    (current == fill::tessellate to 1e-9, so the copy is faithful)");+        }+    }+}++fn main() {+    const Z0: &[u8] = include_bytes!("../tests/fixtures/v4_z0_tile.mvt");+    const Z11: &[u8] = include_bytes!("../tests/fixtures/v5ca_z11_tile.mvt");++    println!("=== the z0 ocean alone: the polygon the sanitiser was built for ===");+    scan("z0 ", Z0, true);+    println!("\n=== every polygon of both fixtures ===");+    scan("z0 ", Z0, false);+    scan("z11", Z11, false);+}
library/map/src/main/rust/examples/zoom_sweep.rs
diff --git a/library/map/src/main/rust/examples/zoom_sweep.rs b/library/map/src/main/rust/examples/zoom_sweep.rsnew file mode 100644index 0000000000..a783d74c4c--- /dev/null+++ b/library/map/src/main/rust/examples/zoom_sweep.rs@@ -0,0 +1,238 @@+//! TEMPORARY diagnostic for the "landmass missing at low zoom" report. Delete after measuring.+//!+//! ```text+//! cargo run --offline -q -p map_renderer --example zoom_sweep+//! GRID=512 cargo run --offline -q -p map_renderer --example zoom_sweep+//! ```+//!+//! Sweeps the camera across the archive's whole zoom range at three places, and reports per+//! zoom what no existing probe measures.+//!+//! # Which columns to trust+//!+//! **`DROPD` and the absent-tile lines are sound.** `decode_polygons` returns `Option` and+//! `geometry::build` silently skips the feature on `None`, so a whole continent can vanish+//! there with every area-conservation check still passing - `loss_probe` cannot see it at all,+//! because it `continue`s on `None` too. Measured: zero, at every zoom, for `earth` and+//! `water`, at all three places, with no tile absent. That is a real result.+//!+//! **The `earth`/`water`/`VISIBLE`/`kept` columns are NOT trustworthy, and this is recorded+//! here so nobody builds on them.** They rasterise each layer to a grid and composite water+//! over earth, which sounds like it measures the thing the user reported. It does not: along+//! every coastline a cell can fall inside both layers, so the apparent overlap scales with+//! coastline length times cell size - and coastline length per tile is largest at exactly the+//! low zooms under suspicion. So the metric manufactures a clean monotonic "land is eaten at+//! low zoom" trend out of nothing but its own resolution. Quadrupling `GRID` from 128 to 512+//! moved z0 `kept` from 0.461 to 0.686, which is the tell. Use `GRID` to re-check any+//! conclusion drawn from these columns before believing it.+//!+//! The quantisation-free way to ask this question is the even-odd scanline integral already in+//! `fill.rs`'s tests and in `probe_archive`, which puts both layers within 0.5% of their true+//! area at z0 with zero area lost.++use map_renderer::camera::Camera;+use map_renderer::tess::fill;+use map_renderer::tile::select;+use std::process::Command;+use tilecodec::mvt::{GeomType, Tile};+use tilecodec::proto::{err, Result};+use tilecodec::stream::{RangeReader, StreamArchive};++const URL: &str = "https://data.vayunmathur.com/v4.pmtiles";++struct CurlReader;++impl RangeReader for CurlReader {+    fn read(&self, offset: u64, length: u32) -> Result<Vec<u8>> {+        let range = format!("{}-{}", offset, offset + length as u64 - 1);+        let out = match Command::new("curl").args(["-s", "-f", "--range", &range, URL]).output() {+            Ok(out) => out,+            Err(e) => return err(format!("curl failed to start: {e}")),+        };+        if !out.status.success() {+            return err(format!("curl exited {:?} for range {range}", out.status.code()));+        }+        Ok(out.stdout)+    }+}++/// Side of the coverage GRID() laid over one tile.+static GRID_CELLS: std::sync::OnceLock<usize> = std::sync::OnceLock::new();+#[allow(non_snake_case)]+fn GRID() -> usize {+    *GRID_CELLS.get_or_init(|| {+        std::env::var("GRID()").ok().and_then(|v| v.parse().ok()).unwrap_or(128)+    })+}++/// Rasterise the emitted triangles into a coverage mask over the tile's own 0..1 box.+///+/// Area sums cannot answer this question: a tile that is wholly land carries one ring that+/// spans the tile *plus its buffer*, so every corner of every triangle sits outside 0..1 and+/// any "is this triangle outside the tile" test misfiles it as overspill. Rasterising asks+/// the only question that matters instead - which parts of the tile end up painted - and it+/// composites layers in draw order the way the GPU does.+fn rasterise(vertices: &[f32], indices: &[u32], mask: &mut [bool]) {+    for tri in indices.chunks_exact(3) {+        let p = |i: u32| {+            let b = i as usize * fill::FLOATS_PER_VERTEX;+            (vertices[b] as f64, vertices[b + 1] as f64)+        };+        let (ax, ay) = p(tri[0]);+        let (bx, by) = p(tri[1]);+        let (cx, cy) = p(tri[2]);++        // Only the part of the triangle that lands on the tile can be painted.+        let lo_x = ax.min(bx).min(cx).max(0.0);+        let hi_x = ax.max(bx).max(cx).min(1.0);+        let lo_y = ay.min(by).min(cy).max(0.0);+        let hi_y = ay.max(by).max(cy).min(1.0);+        if lo_x > hi_x || lo_y > hi_y {+            continue;+        }+        let area2 = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay);+        if area2.abs() < 1e-18 {+            continue;+        }++        let col0 = (lo_x * GRID() as f64).floor().max(0.0) as usize;+        let col1 = ((hi_x * GRID() as f64).ceil() as usize).min(GRID());+        let row0 = (lo_y * GRID() as f64).floor().max(0.0) as usize;+        let row1 = ((hi_y * GRID() as f64).ceil() as usize).min(GRID());+        for row in row0..row1 {+            let y = (row as f64 + 0.5) / GRID() as f64;+            for col in col0..col1 {+                let x = (col as f64 + 0.5) / GRID() as f64;+                // Barycentric sign test, normalised so winding does not matter.+                let w0 = ((bx - ax) * (y - ay) - (x - ax) * (by - ay)) / area2;+                let w1 = ((cx - bx) * (y - by) - (x - bx) * (cy - by)) / area2;+                let w2 = ((ax - cx) * (y - cy) - (x - cx) * (ay - cy)) / area2;+                if w0 >= 0.0 && w1 >= 0.0 && w2 >= 0.0 {+                    mask[row * GRID() + col] = true;+                }+            }+        }+    }+}++fn main() {+    let mut archive = match StreamArchive::open(CurlReader) {+        Ok(a) => a,+        Err(e) => {+            eprintln!("could not open the archive: {e}");+            std::process::exit(1);+        }+    };+    let (min_zoom, max_zoom) = (archive.header.min_zoom, archive.header.max_zoom);+    println!("archive zoom {min_zoom}..{max_zoom}\n");++    println!(+        "{:<5} {:<9} {:>5} {:>6} {:>8} {:>8} {:>8} {:>6}",+        "zoom", "place", "tiles", "DROPD", "earth", "water", "VISIBLE", "kept",+    );++    // A spread of places rather than one, so a single odd tile cannot carry the conclusion:+    // mid-Atlantic (mostly ocean with coasts), Europe, and the Americas.+    let places: [(f64, f64, &str); 3] =+        [(0.0, 20.0, "atlantic"), (10.0, 50.0, "europe"), (-80.0, 10.0, "americas")];++    for zoom in [0.0f64, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0] {+        for (lon, lat, place) in places {+            let camera = Camera {+                center_lon: lon,+                center_lat: lat,+                zoom,+                width_dp: 448.0,+                height_dp: 867.0,+                density: 3.0,+            };+            let tiles = select::visible(&camera, min_zoom, max_zoom);+            let mut absent = 0;+            let mut dropped = 0usize;+            // Summed over tiles, in units of one tile, so they read as fractions of a tile.+            let (mut earth_sum, mut water_sum, mut visible_sum) = (0.0f64, 0.0f64, 0.0f64);+            let mut counted = 0usize;++            for tile in &tiles {+                let body = match archive.tile(tile.z, tile.x, tile.y) {+                    Ok(Some(b)) => b,+                    _ => {+                        absent += 1;+                        continue;+                    }+                };+                let Ok(decoded) = Tile::decode(&body) else {+                    absent += 1;+                    continue;+                };++                let mut earth = vec![false; GRID() * GRID()];+                let mut water = vec![false; GRID() * GRID()];+                for source in &decoded.layers {+                    let mask = match source.name.as_str() {+                        "earth" => &mut earth,+                        "water" => &mut water,+                        _ => continue,+                    };+                    for feature in &source.features {+                        if feature.geom_type != GeomType::Polygon {+                            continue;+                        }+                        let Some(polygons) = tilecodec::mvt::decode_polygons(&feature.geometry)+                        else {+                            // Exactly the path `geometry::build` takes silently.+                            dropped += 1;+                            continue;+                        };+                        for rings in &polygons {+                            let mut v = Vec::new();+                            let mut idx = Vec::new();+                            fill::tessellate(rings, source.extent, &mut v, &mut idx);+                            rasterise(&v, &idx, mask);+                        }+                    }+                }++                // Water is drawn over earth, so land is only visible where earth is painted+                // and water is not.+                let cells = (GRID() * GRID()) as f64;+                earth_sum += earth.iter().filter(|c| **c).count() as f64 / cells;+                water_sum += water.iter().filter(|c| **c).count() as f64 / cells;+                visible_sum += earth+                    .iter()+                    .zip(&water)+                    .filter(|(e, w)| **e && !**w)+                    .count() as f64+                    / cells;+                counted += 1;+            }++            if counted == 0 {+                continue;+            }+            let n = counted as f64;+            let earth = earth_sum / n;+            let visible = visible_sum / n;+            // How much of the land the tile's own `earth` layer describes still reads as land+            // once `water` has been drawn over it. Water and earth should very nearly+            // complement each other, so this should sit close to 1; well below it means the+            // ocean is painted over ground the same tile calls land.+            let kept = if earth > 1e-6 { visible / earth } else { 1.0 };+            println!(+                "z{:<4} {:<9} {:>5} {:>6} {:>8.3} {:>8.3} {:>8.3} {:>6.3}{}",+                zoom as u32,+                place,+                counted,+                dropped,+                earth,+                water_sum / n,+                visible,+                kept,+                if dropped > 0 { "  <<< GEOMETRY DISCARDED" } else { "" },+            );+            if absent > 0 {+                println!("z{:<4} {place:<9} {absent} of {} tiles absent", zoom as u32, tiles.len());+            }+        }+    }+}