Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/facett

facett-map3d/tests/water_survives_altitude.rs

//! **THE GUARD: 1 084 built water triangles must not go undrawn because the camera is high.**
//!
//! ## The defect, as the product published it
//!
//! MEASURED on the shipped korp-ui against the live korp-server, 2026-08-04, RTX 4090
//! `[discrete/Vulkan]`, thin build with `map3d-gpu`, Stockholm z12, straight out of
//! `$KORP_STATE`:
//!
//! ```text
//! map.map3d.water_triangles        = 1084
//! map.map3d.water_active           = false
//! map.map3d.reflective_water       = false
//! map.map3d.metres_per_design_unit = 1875     (camera.distance 0.856 -> ~1.6 km up)
//! ```
//!
//! `Map3D::water_active` read `lod_tier().reflective_water()`, which is
//! `matches!(self, LodTier::Ground)` — camera altitude **under 300 m**. And
//! `SceneFlags::water_on` is exactly what `gpu.rs` gates the water draw on
//! (`let do_water = self.water_on && r.water_index_count > 0`). So above 300 m the
//! lakes were not degraded, they were **absent**: a thousand triangles tessellated,
//! uploaded and never drawn.
//!
//! [`LodTier`]'s own doc comments say what was meant, tier by tier — `Low` is *"water =
//! animated normal-map (no planar reflection pass)"*, `Mid` is *"water = flat Fresnel
//! tint"*, `High` is *"water = flat colour"*. Three of the four tiers describe water
//! that IS drawn and shaded more cheaply. The tier is a quality ladder and it was being
//! read as an on/off switch.
//!
//! ## Why this is not a hollow guard
//!
//! "`water_active` is true" alone would pass on a version that switched water on
//! everywhere and threw the altitude ladder away, which is the opposite mistake and
//! costs a full planar-reflection pass on a region camera. So both halves are asserted
//! at both altitudes: near, the expensive pass runs; far, the surface is still drawn and
//! the expensive pass is off. Only a real split of the two questions satisfies all four.
//!
//! Run: `cargo test -p facett-map3d --test water_survives_altitude -- --test-threads=1`

mod common;

use facett_core::Facet as _;
use facett_map::Way;
use facett_map3d::Map3D;

/// A town with a lake in it: enough building footprints to make a dense cluster (so
/// `densest_cluster_subset` has something to find and does not reshape the scene under
/// the test), plus one `natural=water` ring big enough to matter.
fn town_with_a_lake() -> Vec<Way> {
    let (lon, lat) = common::STOCKHOLM;
    let mk = |kv: &[(&str, &str)], r: Vec<(f64, f64)>| {
        Way::from_lonlat(1, &r, &common::tags(kv), &facett_core::Theme::default()).expect("way")
    };
    let mut ways = Vec::new();
    for i in 0..200i64 {
        let (dx, dy) = ((i % 20) as f64 * 0.0004, (i / 20) as f64 * 0.0004);
        let mut w = mk(&[("building", "yes"), ("building:levels", "4")], common::ring(lon + dx, lat + dy, 0.00012, 0.00006));
        w.osm_id = 1000 + i;
        ways.push(w);
    }
    let mut lake = mk(&[("natural", "water")], common::ring(lon + 0.004, lat + 0.002, 0.0025, 0.0015));
    lake.osm_id = 9001;
    ways.push(lake);
    ways
}

/// Dolly the camera until it is roughly `metres` up, then read back what the frame
/// would do — through `state_json()`, which is the SAME publication `$KORP_STATE`
/// carried when this defect was found, so the test asserts the field the evidence is in.
///
/// The camera is driven with the public `Msg::Dolly` the wheel sends, not by poking
/// `cam.distance`: a test that reaches past the message loop can hold an altitude the
/// product can never actually be at.
fn at_altitude(m: &mut Map3D, metres: f32) -> (bool, bool, String, f32) {
    use facett_map3d::Msg;
    for _ in 0..400 {
        let alt = m.altitude_m();
        if (alt - metres).abs() <= metres * 0.15 {
            break;
        }
        let scroll = if alt > metres { 25.0 } else { -25.0 };
        let _ = m.update(Msg::Dolly { scroll, cursor: None });
        let _ = m.update(Msg::Settle);
    }
    let j = m.state_json();
    (
        j["water_active"].as_bool().expect("water_active is published"),
        j["reflective_water"].as_bool().expect("reflective_water is published"),
        m.lod_tier().name().to_owned(),
        m.altitude_m(),
    )
}

/// The built water triangles, off the same published record.
fn water_tris(m: &Map3D) -> u64 {
    m.state_json()["water_triangles"].as_u64().expect("water_triangles is published")
}

#[test]
fn the_lake_is_drawn_from_a_region_camera_and_the_costly_pass_is_not() {
    let mut m = Map3D::from_geometry("water-altitude", &town_with_a_lake());
    let tris = water_tris(&m);
    assert!(
        tris > 0,
        "the fixture built NO water triangles ({tris}) — every assertion below would be \
         vacuously true, which is the shape this whole file exists to refuse"
    );

    // ── FAR: a region camera, roughly where korp's z12 pane sits (~1.6 km up) ──
    let (active_far, reflect_far, tier_far, alt_far) = at_altitude(&mut m, 1600.0);
    eprintln!("[water] far  {alt_far:.0} m: tier={tier_far} water_active={active_far} reflective={reflect_far} tris={tris}");
    assert!(
        active_far,
        "at {alt_far:.0} m the {tris} water triangles are NOT drawn (tier {tier_far}) — this is the \
         defect: `water_triangles = 1084` beside `water_active = false` in $KORP_STATE"
    );
    assert!(
        !reflect_far,
        "at {alt_far:.0} m the planar reflection pass is ON (tier {tier_far}) — the altitude ladder \
         has been thrown away instead of split, which costs a second scene render on a \
         region camera"
    );

    // ── NEAR: street level, where the expensive pass is earned ────────────────
    let (active_near, reflect_near, tier_near, alt_near) = at_altitude(&mut m, 150.0);
    eprintln!("[water] near {alt_near:.0} m: tier={tier_near} water_active={active_near} reflective={reflect_near}");
    assert!(active_near, "water must still be drawn at street level (tier {tier_near})");
    assert!(
        reflect_near,
        "at {alt_near:.0} m the planar reflection pass must RUN (tier {tier_near}) — that is what the \
         `LodTier::Ground` gate is for, and a fix that leaves it off everywhere is a \
         regression wearing this fix's clothes"
    );

    // The two altitudes must actually be different tiers, or the pair above is one
    // measurement written twice.
    assert_ne!(
        tier_far, tier_near,
        "both altitudes landed on the same LOD tier ({tier_far}) — the fixture's scale makes \
         this test unable to see the thing it asserts"
    );
}

#[test]
fn a_scene_with_no_water_draws_no_water_at_any_altitude() {
    // The other direction: `water_active` must still be FALSE when there is nothing to
    // draw. `unwrap_or(true)` on an empty grid would have every scene claim a water
    // surface, and `do_water` would then be gated only by the index count — which is a
    // working product by luck rather than by the flag meaning what it says.
    let (lon, lat) = common::STOCKHOLM;
    let ways: Vec<Way> = (0..80i64)
        .map(|i| {
            let (dx, dy) = ((i % 10) as f64 * 0.0004, (i / 10) as f64 * 0.0004);
            let mut w = Way::from_lonlat(
                1,
                &common::ring(lon + dx, lat + dy, 0.00012, 0.00006),
                &common::tags(&[("building", "yes")]),
                &facett_core::Theme::default(),
            )
            .expect("way");
            w.osm_id = 2000 + i;
            w
        })
        .collect();
    let mut m = Map3D::from_geometry("no-water", &ways);
    assert_eq!(water_tris(&m), 0, "this fixture must carry no water");
    for metres in [150.0, 1600.0, 20_000.0] {
        let (active, reflect, tier, _) = at_altitude(&mut m, metres);
        assert!(!active, "a scene with no water claimed a water surface at {metres} m (tier {tier})");
        assert!(!reflect, "a scene with no water claimed a reflection pass at {metres} m (tier {tier})");
    }
}