garage44.eu/jeroen/cartopolis

logclone: git clone https://garage44.eu/jeroen/cartopolis.git

.. /crates/atlas/src/pipeline/models.rs

raw

//! Building models for landmarks the survey gets wrong (`docs/notes/building-models.md`).
//!
//! 3DBAG reconstructs every building as a solid shell from a laser survey flown
//! overhead, and for most buildings that is the right shape. For a stadium it is
//! not: the Euroborg comes out as one flat-topped block 23 m high over its whole
//! 34,000 m² footprint, pitch included, because the register's outline has no
//! hole in it and the reconstruction fills whatever the outline encloses.
//!
//! This dataset writes the `lod3` tree the client already streams in place of a
//! shell (`systems::lod3`): per cell, model elements plus the BAG ids they
//! replace, and a `coverage.json`. The models are **generated, not surveyed** —
//! from the register's outline, the half-metre AHN surface model (which sees the
//! roof and the open pitch), and the pitch as OpenStreetMap maps it. What none of
//! those can see is under the roof: the stands are an assumption, and every
//! constant that makes one is named as one.
//!
//! The model is approximate by design: the right footprint, heights and bowl, not
//! the architecture. A modeller's file for the same building would replace it
//! through the same tree.

use cartopolis_geo::formats::lod22::{Element, File, Id, Tri};

use super::http;
use super::tile::{cell_path, lat_lng_to_cell, Cell};
use super::{Count, Ctx, DatasetResult, Outcome, PipelineError, Progress};
use crate::terrain::{HeightSource, Pdok};

/// What the client shows as the source of these models.
pub const ATTRIBUTION: &str =
    "Building model generated by Cartopolis from BAG, AHN and © OpenStreetMap contributors";

/// A stadium to generate: the building it replaces and its pitch.
pub struct Landmark {
    pub name: &'static str,
    /// The BAG identificatie of the building the model replaces.
    pub pand: &'static str,
    /// The pitch corners, `(lat, lng)`, in order round the rectangle.
    pub pitch: [(f64, f64); 4],
}

/// FC Groningen's stadium. The pitch is OpenStreetMap way 185043967.
///
/// Not a list this dataset reads: which buildings are overridden is the
/// override store's (`crate::overrides`). This is the one record a fresh atlas
/// is seeded with, so the stadium the football pack plays in is there from the
/// first run — and deleting it in the web UI deletes it for good.
pub const EUROBORG: Landmark = Landmark {
    name: "Euroborg",
    pand: "0014100010953806",
    pitch: [
        (53.206_624_2, 6.591_156_3),
        (53.205_667_6, 6.591_133_2),
        (53.205_658_7, 6.592_152_2),
        (53.206_615_3, 6.592_175_3),
    ],
};

// ── Assumptions: what the survey cannot see ──────────────────────────────────
//
// The surface model sees the roof and the grass. Under the roof there is a bowl
// of seating the laser never reached, so its shape is a stadium's ordinary
// proportions rather than this one's measurements.

/// Grass between the touchline and the front row.
const APRON_M: f64 = 7.0;
/// The wall in front of the first row.
const FRONT_WALL_M: f64 = 1.2;
/// Depth of one row of seats.
const ROW_DEPTH_M: f64 = 0.85;
/// Headroom between the back row and the underside of the roof.
const HEADROOM_M: f64 = 3.0;
/// The walkway behind the back row, inside the outer wall.
const CONCOURSE_M: f64 = 3.0;
/// How thick the roof is drawn.
const ROOF_THICKNESS_M: f64 = 1.2;
/// Half the width of the four corner gates — a way in for an avatar, cut
/// through the stand and the outer ring where the real stadium has stairs.
const GATE_HALF_WIDTH_M: f64 = 4.0;

// ── Measuring ────────────────────────────────────────────────────────────────

/// Sections round the bowl. One every 2.5°: at the back of the main stand,
/// 110 m out, that is a 4.8 m slice.
const RAYS: usize = 144;
/// A surface this far above the grass is the roof, not the pitch.
const ROOF_RISE_M: f32 = 6.0;
/// Past the roof, a surface below this is the lower ring round the outside.
const ROOF_END_M: f32 = 12.0;
/// The last surface above this, inside the register's outline, is the outside
/// of the building.
const BUILDING_M: f32 = 2.5;

/// Metres east and north of a point, in a tangent plane — millimetre-good across
/// one building.
#[derive(Debug, Clone, Copy)]
pub struct Plane {
    pub lat: f64,
    pub lng: f64,
    m_lat: f64,
    m_lng: f64,
}

impl Plane {
    #[must_use]
    pub fn at(lat: f64, lng: f64) -> Self {
        let (m_lat, m_lng) = cartopolis_core::degree_scale_m(lat);
        Self {
            lat,
            lng,
            m_lat,
            m_lng,
        }
    }

    #[must_use]
    pub fn to_en(&self, lat: f64, lng: f64) -> [f64; 2] {
        [(lng - self.lng) * self.m_lng, (lat - self.lat) * self.m_lat]
    }

    #[must_use]
    pub fn to_lat_lng(&self, en: [f64; 2]) -> (f64, f64) {
        (self.lat + en[1] / self.m_lat, self.lng + en[0] / self.m_lng)
    }
}

/// The pitch as a frame: centre, the unit vector toward one goal line
/// (`along`) and the one square to it (`across`), and the half sizes.
#[derive(Debug, Clone, Copy)]
pub struct Pitch {
    pub plane: Plane,
    pub along: [f64; 2],
    pub across: [f64; 2],
    pub half_length: f64,
    pub half_width: f64,
}

impl Pitch {
    #[must_use]
    pub fn of(corners: [(f64, f64); 4]) -> Self {
        let lat = corners.iter().map(|c| c.0).sum::<f64>() / 4.0;
        let lng = corners.iter().map(|c| c.1).sum::<f64>() / 4.0;
        let plane = Plane::at(lat, lng);
        let p: Vec<[f64; 2]> = corners.iter().map(|c| plane.to_en(c.0, c.1)).collect();
        let mid = |a: [f64; 2], b: [f64; 2]| [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0];
        // The two shorter sides are the goal lines.
        let (s01, s12) = (len(sub(p[1], p[0])), len(sub(p[2], p[1])));
        let (end_a, end_b, width) = if s01 < s12 {
            (mid(p[0], p[1]), mid(p[2], p[3]), s01)
        } else {
            (mid(p[1], p[2]), mid(p[3], p[0]), s12)
        };
        let axis = sub(end_b, end_a);
        let length = len(axis);
        let along = [axis[0] / length, axis[1] / length];
        Self {
            plane,
            along,
            across: [along[1], -along[0]],
            half_length: length / 2.0,
            half_width: width / 2.0,
        }
    }

    /// Metres east/north of the centre, for a point `along`/`across` the pitch.
    #[must_use]
    pub fn en(&self, along: f64, across: f64) -> [f64; 2] {
        [
            along * self.along[0] + across * self.across[0],
            along * self.along[1] + across * self.across[1],
        ]
    }

    /// The unit direction at angle `theta` from the pitch's long axis.
    #[must_use]
    pub fn ray(&self, theta: f64) -> [f64; 2] {
        self.en(theta.cos(), theta.sin())
    }

    /// Distance from the centre to the pitch's edge along `theta`.
    #[must_use]
    pub fn edge(&self, theta: f64) -> f64 {
        self.edge_beyond(theta, 0.0)
    }

    /// Distance from the centre along `theta` to a line `margin` metres outside
    /// the pitch, square to its sides — so the margin is the same everywhere,
    /// rather than shrinking toward the corners as a distance along the ray would.
    #[must_use]
    pub fn edge_beyond(&self, theta: f64, margin: f64) -> f64 {
        let (c, s) = (theta.cos().abs(), theta.sin().abs());
        let a = if c > 1e-9 {
            (self.half_length + margin) / c
        } else {
            f64::INFINITY
        };
        let b = if s > 1e-9 {
            (self.half_width + margin) / s
        } else {
            f64::INFINITY
        };
        a.min(b)
    }

    /// The four directions from the centre spot to the corner flags.
    #[must_use]
    pub fn corners(&self) -> [f64; 4] {
        let c = self.half_width.atan2(self.half_length);
        [c, std::f64::consts::PI - c, std::f64::consts::PI + c, -c]
    }
}

fn sub(a: [f64; 2], b: [f64; 2]) -> [f64; 2] {
    [a[0] - b[0], a[1] - b[1]]
}

fn len(v: [f64; 2]) -> f64 {
    (v[0] * v[0] + v[1] * v[1]).sqrt()
}

/// Where a ray from the origin first leaves a ring (metres east/north), or
/// `None` if it never crosses it.
#[must_use]
pub fn ray_exit(ring: &[[f64; 2]], dir: [f64; 2]) -> Option<f64> {
    let mut best: Option<f64> = None;
    for i in 0..ring.len() {
        let a = ring[i];
        let b = ring[(i + 1) % ring.len()];
        let e = sub(b, a);
        let denom = dir[0] * e[1] - dir[1] * e[0];
        if denom.abs() < 1e-12 {
            continue;
        }
        let t = (a[0] * e[1] - a[1] * e[0]) / denom;
        let u = (a[0] * dir[1] - a[1] * dir[0]) / denom;
        if t > 0.0 && (0.0..=1.0).contains(&u) {
            best = Some(best.map_or(t, |b: f64| b.min(t)));
        }
    }
    best
}

/// AHN's surface model over a box, sampled by east/north metres.
pub struct Surface {
    plane: Plane,
    min: [f64; 2],
    step: f64,
    n: usize,
    h: Vec<f32>,
}

impl Surface {
    /// Fetch `half` metres either side of the plane's origin at half a metre.
    pub fn fetch(source: &dyn HeightSource, plane: Plane, half: f64) -> Result<Self, String> {
        let centre = cartopolis_geo::ahn::wgs84_to_rd(plane.lat, plane.lng);
        let min = [centre[0] - half, centre[1] - half];
        let max = [centre[0] + half, centre[1] + half];
        let n = ((2.0 * half) / 0.5).round() as usize;
        let h = source.raster(min, max, n)?;
        Ok(Self::from_raster(plane, min, (2.0 * half) / n as f64, n, h))
    }

    /// A surface from a raster already in hand, north row first.
    #[must_use]
    pub fn from_raster(plane: Plane, min: [f64; 2], step: f64, n: usize, h: Vec<f32>) -> Self {
        Self {
            plane,
            min,
            step,
            n,
            h,
        }
    }

    /// Height at a point (NAP metres), nearest sample; `None` outside or unmeasured.
    #[must_use]
    pub fn at(&self, en: [f64; 2]) -> Option<f32> {
        let (lat, lng) = self.plane.to_lat_lng(en);
        let rd = cartopolis_geo::ahn::wgs84_to_rd(lat, lng);
        let col = ((rd[0] - self.min[0]) / self.step).floor();
        let row = ((self.min[1] + self.step * self.n as f64 - rd[1]) / self.step).floor();
        if col < 0.0 || row < 0.0 || col >= self.n as f64 || row >= self.n as f64 {
            return None;
        }
        let v = self.h[row as usize * self.n + col as usize];
        v.is_finite().then_some(v)
    }
}

/// What one ray from the centre spot measured, in metres from the centre and
/// metres above the grass.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Section {
    pub theta: f64,
    /// To the pitch's edge.
    pub pitch: f64,
    /// To the front of the stand: [`APRON_M`] past the pitch, square to its side.
    pub front: f64,
    /// To the roof's inner edge, and the roof's height there.
    pub inner: f64,
    pub inner_h: f64,
    /// To where the roof ends — the stand's outer wall — and its height there.
    pub back: f64,
    pub back_h: f64,
    /// To the outside of the building, and the height of the lower ring between
    /// `back` and here (0 where there is none).
    pub outer: f64,
    pub ring_h: f64,
}

/// The bowl, measured: the grass's height (NAP) and a section per ray.
#[derive(Debug, Clone)]
pub struct Bowl {
    pub grass: f32,
    pub sections: Vec<Section>,
}

/// Measure the bowl round `pitch`, inside `outline` (metres east/north).
#[must_use]
pub fn measure(pitch: &Pitch, outline: &[[f64; 2]], surface: &Surface) -> Option<Bowl> {
    let mut grass = Vec::new();
    for i in -20..=20 {
        for j in -12..=12 {
            let en = pitch.en(
                f64::from(i) / 20.0 * pitch.half_length * 0.9,
                f64::from(j) / 12.0 * pitch.half_width * 0.9,
            );
            grass.extend(surface.at(en));
        }
    }
    let ground = median(&mut grass)?;
    let mut raw = Vec::with_capacity(RAYS);
    for k in 0..RAYS {
        let theta = std::f64::consts::TAU * k as f64 / RAYS as f64;
        let dir = pitch.ray(theta);
        let edge = pitch.edge(theta);
        let bag = ray_exit(outline, dir)?;
        let above = |r: f64| surface.at([dir[0] * r, dir[1] * r]).map(|h| h - ground);
        let samples: Vec<(f64, f32)> = (0..)
            .map(|i| edge + f64::from(i) * 0.5)
            .take_while(|&r| r <= bag)
            .filter_map(|r| above(r).map(|h| (r, h)))
            .collect();
        let inner = samples.iter().find(|s| s.1 > ROOF_RISE_M)?.0;
        // The roof ends where the surface stays below `ROOF_END_M` for two metres.
        let back = samples
            .windows(4)
            .find(|w| w[0].0 > inner && w.iter().all(|s| s.1 < ROOF_END_M))
            .map_or(bag, |w| w[0].0);
        let outer = samples
            .iter()
            .rev()
            .find(|s| s.1 > BUILDING_M)
            .map_or(back, |s| s.0)
            .max(back);
        let mean_over = |a: f64, b: f64| {
            let mut v: Vec<f32> = samples
                .iter()
                .filter(|s| s.0 >= a && s.0 <= b)
                .map(|s| s.1)
                .collect();
            median(&mut v).map_or(0.0, f64::from)
        };
        let ring_h = if outer - back > 3.0 {
            mean_over(back + 1.0, outer - 1.0)
        } else {
            0.0
        };
        raw.push(Section {
            theta,
            pitch: edge,
            front: pitch.edge_beyond(theta, APRON_M),
            inner,
            inner_h: mean_over(inner + 0.5, inner + 3.0),
            back,
            back_h: mean_over(back - 4.0, back - 0.5),
            outer,
            ring_h,
        });
    }
    // A median of five neighbours, round the ring: one ray through a mast or a
    // floodlight should not put a spike in the roof.
    let smooth = |f: fn(&Section) -> f64, k: usize| {
        let mut v: Vec<f64> = (0..5).map(|d| f(&raw[(k + RAYS + d - 2) % RAYS])).collect();
        v.sort_by(f64::total_cmp);
        v[2]
    };
    let sections = (0..RAYS)
        .map(|k| Section {
            theta: raw[k].theta,
            pitch: raw[k].pitch,
            front: raw[k].front,
            inner: smooth(|s| s.inner, k),
            inner_h: smooth(|s| s.inner_h, k),
            back: smooth(|s| s.back, k),
            back_h: smooth(|s| s.back_h, k),
            outer: smooth(|s| s.outer, k),
            ring_h: smooth(|s| s.ring_h, k),
        })
        .collect();
    Some(Bowl {
        grass: ground,
        sections,
    })
}

fn median(v: &mut [f32]) -> Option<f32> {
    if v.is_empty() {
        return None;
    }
    v.sort_by(f32::total_cmp);
    Some(v[v.len() / 2])
}

// ── Building ─────────────────────────────────────────────────────────────────

/// Triangles in the pitch plane: points are `[east, north, height]`.
///
/// Corners are shared between the quads that meet at them — a row's tread and
/// the next row's riser have an edge in common — which halves the file. The
/// client expands every triangle itself, so sharing changes nothing it draws.
#[derive(Default)]
struct Mesh {
    p: Vec<[f64; 3]>,
    t: Vec<Tri>,
    index: std::collections::HashMap<[i64; 3], u32>,
}

impl Mesh {
    fn vertex(&mut self, q: [f64; 3]) -> u32 {
        // Keyed at a millimetre, finer than anything written out.
        let key = [
            (q[0] * 1000.0).round() as i64,
            (q[1] * 1000.0).round() as i64,
            (q[2] * 1000.0).round() as i64,
        ];
        let next = self.p.len() as u32;
        let p = &mut self.p;
        *self.index.entry(key).or_insert_with(|| {
            p.push(q);
            next
        })
    }

    fn quad(&mut self, a: [f64; 3], b: [f64; 3], c: [f64; 3], d: [f64; 3], roof: bool) {
        let [a, b, c, d] = [a, b, c, d].map(|q| self.vertex(q));
        let r = u8::from(roof);
        // A quad folded onto itself (a zero-height wall) draws nothing.
        if a != b && b != c && a != c {
            self.t.push(Tri(a, b, c, r));
        }
        if a != c && c != d && a != d {
            self.t.push(Tri(a, c, d, r));
        }
    }

    fn element(
        self,
        plane: &Plane,
        pand: &str,
        part: u32,
        class: &str,
        rgb: [u8; 3],
    ) -> Option<Element> {
        if self.t.is_empty() {
            return None;
        }
        let p = self
            .p
            .iter()
            .map(|q| {
                let (lat, lng) = plane.to_lat_lng([q[0], q[1]]);
                (round(lat, 7), round(lng, 7), round(q[2], 2) as f32)
            })
            .collect();
        Some(Element {
            class: class.into(),
            id: Id(pand.into()),
            p,
            part,
            rgb: Some(rgb),
            finish: None,
            t: self.t,
        })
    }

    /// A level rectangle in pitch coordinates (`along`, `across`), `h` up.
    fn rect(&mut self, pitch: &Pitch, a: [f64; 2], c: [f64; 2], h: f64) {
        let p = |al: f64, ac: f64| {
            let en = pitch.en(al, ac);
            [en[0], en[1], h]
        };
        self.quad(
            p(a[0], c[0]),
            p(a[1], c[0]),
            p(a[1], c[1]),
            p(a[0], c[1]),
            true,
        );
    }

    /// A painted line from one pitch point to another, `w` wide.
    fn line(&mut self, pitch: &Pitch, from: [f64; 2], to: [f64; 2], w: f64, h: f64) {
        let d = [to[0] - from[0], to[1] - from[1]];
        let l = len(d);
        if l < 1e-9 {
            return;
        }
        let n = [-d[1] / l * w / 2.0, d[0] / l * w / 2.0];
        let p = |q: [f64; 2], s: f64| {
            let en = pitch.en(q[0] + n[0] * s, q[1] + n[1] * s);
            [en[0], en[1], h]
        };
        self.quad(p(from, -1.0), p(to, -1.0), p(to, 1.0), p(from, 1.0), true);
    }

    /// A painted arc about `centre`, radius `r`, from angle `a0` to `a1`
    /// (radians, 0 along the pitch).
    fn arc(&mut self, pitch: &Pitch, centre: [f64; 2], r: f64, a0: f64, a1: f64, w: f64, h: f64) {
        let steps = ((a1 - a0).abs() * r / 0.6).ceil().max(2.0) as usize;
        let pt = |a: f64| [centre[0] + r * a.cos(), centre[1] + r * a.sin()];
        for i in 0..steps {
            let t0 = a0 + (a1 - a0) * i as f64 / steps as f64;
            let t1 = a0 + (a1 - a0) * (i + 1) as f64 / steps as f64;
            self.line(pitch, pt(t0), pt(t1), w, h);
        }
    }
}

// ── Colours: all sRGB, and all assumptions but the roof ──────────────────────

/// The roof, white as the aerial photograph shows it.
const ROOF_RGB: [u8; 3] = [232, 232, 226];
/// Concrete: the terraces, the aisles, the walls between the gates.
const CONCRETE_RGB: [u8; 3] = [150, 150, 146];
/// The outer wall.
const FACADE_RGB: [u8; 3] = [92, 96, 101];
/// The seats, in the club's green. Under the roof, so no survey has seen them.
const SEAT_RGB: [u8; 3] = [0, 122, 61];
/// The grass: mowing stripes, and the darker strip round the pitch.
const STRIPE_LIGHT_RGB: [u8; 3] = [92, 152, 64];
const STRIPE_DARK_RGB: [u8; 3] = [72, 130, 50];
const SURROUND_RGB: [u8; 3] = [62, 112, 46];
const LINE_RGB: [u8; 3] = [242, 242, 236];

// ── The pitch and the seats ──────────────────────────────────────────────────

/// Mowing stripes across the length of the pitch.
const STRIPES: usize = 18;
/// Painted lines: 12 cm, as the Laws of the Game allow.
const LINE_W: f64 = 0.12;
/// Heights of the grass, stripes and lines. Centimetres apart so no two of them
/// are ever the same depth; above the map's own ground so neither is the map.
const SURROUND_H: f64 = 0.04;
const STRIPE_H: f64 = 0.05;
const LINE_H: f64 = 0.07;
/// A seat: how far back on its row it starts, and how high it stands.
const SEAT_SET_BACK_M: f64 = 0.3;
const SEAT_HEIGHT_M: f64 = 0.45;
/// Every this-many slices is a stair instead of seats.
const AISLE_EVERY: usize = 6;

/// The pitch: a darker surround to the front of the stands, the playing area in
/// mowing stripes, and the markings — touchlines, goal lines, halfway line,
/// centre circle and spot, both penalty and goal areas, penalty spots and arcs,
/// and the corner arcs. Elements that nothing collides with (`IfcSlab`).
fn pitch_surface(pitch: &Pitch) -> Vec<(Mesh, [u8; 3])> {
    let (l, w) = (pitch.half_length, pitch.half_width);
    let (gl, gw) = (l + APRON_M, w + APRON_M);
    // The surround is a frame, not a sheet under the stripes: two surfaces
    // centimetres apart over the same ground is a depth fight at any range.
    let mut surround = Mesh::default();
    surround.rect(pitch, [-gl, gl], [-gw, -w], SURROUND_H);
    surround.rect(pitch, [-gl, gl], [w, gw], SURROUND_H);
    surround.rect(pitch, [-gl, -l], [-w, w], SURROUND_H);
    surround.rect(pitch, [l, gl], [-w, w], SURROUND_H);

    let (mut light, mut dark) = (Mesh::default(), Mesh::default());
    let band = 2.0 * l / STRIPES as f64;
    for i in 0..STRIPES {
        let a0 = -l + band * i as f64;
        let m = if i % 2 == 0 { &mut light } else { &mut dark };
        m.rect(pitch, [a0, a0 + band], [-w, w], STRIPE_H);
    }

    let mut lines = Mesh::default();
    let h = LINE_H;
    let corners = [[-l, -w], [l, -w], [l, w], [-l, w]];
    for i in 0..4 {
        lines.line(pitch, corners[i], corners[(i + 1) % 4], LINE_W, h);
    }
    lines.line(pitch, [0.0, -w], [0.0, w], LINE_W, h);
    lines.arc(
        pitch,
        [0.0, 0.0],
        9.15,
        0.0,
        std::f64::consts::TAU,
        LINE_W,
        h,
    );
    lines.arc(pitch, [0.0, 0.0], 0.15, 0.0, std::f64::consts::TAU, 0.3, h);
    for end in [-1.0, 1.0] {
        let line = end * l;
        // Penalty area 16.5 m deep, 40.32 m wide; goal area 5.5 m by 18.32 m.
        for (depth, half) in [(16.5, 20.16), (5.5, 9.16)] {
            let inner = line - end * depth;
            lines.line(pitch, [line, -half], [inner, -half], LINE_W, h);
            lines.line(pitch, [inner, -half], [inner, half], LINE_W, h);
            lines.line(pitch, [inner, half], [line, half], LINE_W, h);
        }
        // Penalty spot at 11 m; the arc is the part of a 9.15 m circle round it
        // outside the penalty area.
        let spot = [line - end * 11.0, 0.0];
        lines.arc(pitch, spot, 0.15, 0.0, std::f64::consts::TAU, 0.3, h);
        let half_angle = ((16.5 - 11.0) / 9.15f64).acos();
        let facing = if end > 0.0 { std::f64::consts::PI } else { 0.0 };
        lines.arc(
            pitch,
            spot,
            9.15,
            facing - half_angle,
            facing + half_angle,
            LINE_W,
            h,
        );
        // Corner arcs, 1 m, turning into the pitch.
        for side in [-1.0f64, 1.0] {
            // From the direction back along the goal line to the one back along
            // the touchline: the quarter that lies on the pitch.
            let along_in = 0.0f64.atan2(-end);
            let across_in = (-side).atan2(0.0);
            let (mut a0, mut a1) = (along_in.min(across_in), along_in.max(across_in));
            if a1 - a0 > std::f64::consts::PI {
                (a0, a1) = (a1, a0 + std::f64::consts::TAU);
            }
            lines.arc(pitch, [line, side * w], 1.0, a0, a1, LINE_W, h);
        }
    }
    vec![
        (surround, SURROUND_RGB),
        (light, STRIPE_LIGHT_RGB),
        (dark, STRIPE_DARK_RGB),
        (lines, LINE_RGB),
    ]
}

fn round(v: f64, dp: i32) -> f64 {
    let m = 10f64.powi(dp);
    (v * m).round() / m
}

/// A point `r` metres out along a section's ray, `h` up.
fn at(pitch: &Pitch, s: &Section, r: f64, h: f64) -> [f64; 3] {
    let d = pitch.ray(s.theta);
    [d[0] * r, d[1] * r, h]
}

/// The stand's profile along one ray: `(r, h)` at the front of each row, from
/// the front wall's foot to the back row, then the walkway to the outer wall.
fn profile(s: &Section, rows: usize) -> Vec<(f64, f64)> {
    let front = s.front;
    let last = (s.back - CONCOURSE_M).max(front + 1.0);
    let top = (s.back_h - HEADROOM_M).max(FRONT_WALL_M + 1.0);
    let depth = (last - front) / rows as f64;
    let rise = (top - FRONT_WALL_M) / rows as f64;
    let mut out = vec![(front, 0.0)];
    for i in 0..rows {
        let h = FRONT_WALL_M + rise * i as f64;
        out.push((front + depth * i as f64, h));
        out.push((front + depth * (i + 1) as f64, h));
    }
    out.push((s.back, top));
    out
}

/// Whether the slice between two sections is one of the corner gates.
fn in_gate(pitch: &Pitch, a: &Section, b: &Section) -> bool {
    let mid = (a.theta + b.theta) / 2.0;
    let r = (a.front + b.front) / 2.0;
    pitch.corners().iter().any(|&c| {
        let d = (mid - c).rem_euclid(std::f64::consts::TAU);
        let d = d.min(std::f64::consts::TAU - d);
        d * r < GATE_HALF_WIDTH_M
    })
}

/// The model's elements, one per slice and kind, in the pitch plane.
#[must_use]
pub fn build(pitch: &Pitch, bowl: &Bowl, pand: &str) -> Vec<Element> {
    let s = &bowl.sections;
    let n = s.len();
    let gate: Vec<bool> = (0..n)
        .map(|k| in_gate(pitch, &s[k], &s[(k + 1) % n]))
        .collect();
    let mut out = Vec::new();
    let mut part = 0u32;
    let mut push = |out: &mut Vec<Element>, mesh: Mesh, class: &str, rgb: [u8; 3]| {
        if let Some(e) = mesh.element(&pitch.plane, pand, part, class, rgb) {
            out.push(e);
            part += 1;
        }
    };
    for (mesh, rgb) in pitch_surface(pitch) {
        push(&mut out, mesh, "IfcSlab", rgb);
    }
    for k in 0..n {
        let (a, b) = (&s[k], &s[(k + 1) % n]);
        // The roof runs over the gates too: it is overhead, and not solid.
        let mut roof = Mesh::default();
        let (ai, bi) = (a.inner, b.inner);
        let (ao, bo) = (a.back, b.back);
        let lift = |h: f64| h - ROOF_THICKNESS_M;
        roof.quad(
            at(pitch, a, ai, a.inner_h),
            at(pitch, b, bi, b.inner_h),
            at(pitch, b, bo, b.back_h),
            at(pitch, a, ao, a.back_h),
            true,
        );
        roof.quad(
            at(pitch, a, ai, lift(a.inner_h)),
            at(pitch, b, bi, lift(b.inner_h)),
            at(pitch, b, bo, lift(b.back_h)),
            at(pitch, a, ao, lift(a.back_h)),
            false,
        );
        roof.quad(
            at(pitch, a, ai, lift(a.inner_h)),
            at(pitch, b, bi, lift(b.inner_h)),
            at(pitch, b, bi, b.inner_h),
            at(pitch, a, ai, a.inner_h),
            false,
        );
        push(&mut out, roof, "IfcRoof", ROOF_RGB);
        if gate[k] {
            continue;
        }

        // The stand: a solid slice from the front wall to the outer wall, stepped
        // in rows. One collider per slice, so the pitch between them stays open.
        let rows = (((a.back + b.back) / 2.0 - CONCOURSE_M - (a.front + b.front) / 2.0)
            / ROW_DEPTH_M)
            .floor()
            .max(1.0) as usize;
        let (pa, pb) = (profile(a, rows), profile(b, rows));
        let mut stand = Mesh::default();
        for i in 0..pa.len() - 1 {
            // Alternately a riser (vertical) and a tread (level): the profile
            // already has both corners of each step.
            stand.quad(
                at(pitch, a, pa[i].0, pa[i].1),
                at(pitch, b, pb[i].0, pb[i].1),
                at(pitch, b, pb[i + 1].0, pb[i + 1].1),
                at(pitch, a, pa[i + 1].0, pa[i + 1].1),
                false,
            );
        }
        // The seats: a block on the back of every row, in the seat colour, except
        // where this slice is a stair. Nothing collides with them — the terrace
        // under them already does.
        let mut seats = Mesh::default();
        if k % AISLE_EVERY != 0 {
            // `pa[1 + 2i]` and `pa[2 + 2i]` are row i's tread, front and back.
            for i in 0..rows {
                let (fa, ba) = (pa[1 + 2 * i], pa[2 + 2 * i]);
                let (fb, bb) = (pb[1 + 2 * i], pb[2 + 2 * i]);
                let (sa, sb) = (fa.0 + SEAT_SET_BACK_M, fb.0 + SEAT_SET_BACK_M);
                let (ta, tb) = (fa.1 + SEAT_HEIGHT_M, fb.1 + SEAT_HEIGHT_M);
                seats.quad(
                    at(pitch, a, sa, fa.1),
                    at(pitch, b, sb, fb.1),
                    at(pitch, b, sb, tb),
                    at(pitch, a, sa, ta),
                    false,
                );
                seats.quad(
                    at(pitch, a, sa, ta),
                    at(pitch, b, sb, tb),
                    at(pitch, b, bb.0, tb),
                    at(pitch, a, ba.0, ta),
                    false,
                );
            }
        }
        push(&mut out, seats, "IfcFurnishingElement", SEAT_RGB);

        // The outer wall, ground to roof.
        let mut facade = Mesh::default();
        facade.quad(
            at(pitch, a, a.back, 0.0),
            at(pitch, b, b.back, 0.0),
            at(pitch, b, b.back, lift(b.back_h)),
            at(pitch, a, a.back, lift(a.back_h)),
            false,
        );
        push(&mut out, facade, "IfcWall", FACADE_RGB);
        // Beside a gate the slice's open side is closed, row by row.
        for (side, prof, other) in [(a, &pa, gate[(k + n - 1) % n]), (b, &pb, gate[(k + 1) % n])] {
            if !other {
                continue;
            }
            for w in prof.windows(2) {
                let h = w[0].1.max(w[1].1);
                stand.quad(
                    at(pitch, side, w[0].0, 0.0),
                    at(pitch, side, w[1].0, 0.0),
                    at(pitch, side, w[1].0, h),
                    at(pitch, side, w[0].0, h),
                    false,
                );
            }
            stand.quad(
                at(pitch, side, prof[prof.len() - 1].0, 0.0),
                at(pitch, side, side.back, 0.0),
                at(pitch, side, side.back, lift(side.back_h)),
                at(pitch, side, prof[prof.len() - 1].0, lift(side.back_h)),
                false,
            );
        }
        push(&mut out, stand, "IfcWall", CONCRETE_RGB);

        // The lower ring outside the outer wall, where the survey found one.
        let ring = (a.ring_h + b.ring_h) / 2.0;
        if ring > f64::from(BUILDING_M) && a.outer > a.back + 1.0 && b.outer > b.back + 1.0 {
            let mut m = Mesh::default();
            m.quad(
                at(pitch, a, a.back, ring),
                at(pitch, b, b.back, ring),
                at(pitch, b, b.outer, ring),
                at(pitch, a, a.outer, ring),
                true,
            );
            m.quad(
                at(pitch, a, a.outer, 0.0),
                at(pitch, b, b.outer, 0.0),
                at(pitch, b, b.outer, ring),
                at(pitch, a, a.outer, ring),
                false,
            );
            for (side, other) in [(a, gate[(k + n - 1) % n]), (b, gate[(k + 1) % n])] {
                if other {
                    m.quad(
                        at(pitch, side, side.back, 0.0),
                        at(pitch, side, side.outer, 0.0),
                        at(pitch, side, side.outer, ring),
                        at(pitch, side, side.back, ring),
                        false,
                    );
                }
            }
            push(&mut out, m, "IfcWall", FACADE_RGB);
        }
    }
    out
}

// ── Generating and filing ────────────────────────────────────────────────────

/// The register's outline of one building, `(lat, lng)`, from PDOK's BAG WFS,
/// looked up by its number alone. `Err` says why, in words for the web UI.
pub fn bag_outline(pand: &str) -> Result<Vec<(f64, f64)>, String> {
    let filter = format!(
        "<Filter><PropertyIsEqualTo><PropertyName>identificatie</PropertyName>\
         <Literal>{pand}</Literal></PropertyIsEqualTo></Filter>"
    );
    let url = format!(
        "https://service.pdok.nl/lv/bag/wfs/v2_0?service=WFS&version=2.0.0&request=GetFeature\
         &typeNames=bag:pand&outputFormat=application/json&srsName=EPSG:4326&count=1&{}",
        http::query(&[("filter", &filter)])
    );
    let mut last = String::new();
    for attempt in 0..3 {
        match ureq::get(&url)
            .timeout(std::time::Duration::from_secs(30))
            .call()
            .map_err(|e| e.to_string())
            .and_then(|r| {
                serde_json::from_reader::<_, serde_json::Value>(r.into_reader())
                    .map_err(|e| e.to_string())
            }) {
            Ok(doc) => return outline_of(&doc, pand),
            Err(e) => {
                last = e;
                if attempt < 2 {
                    std::thread::sleep(std::time::Duration::from_secs(2));
                }
            }
        }
    }
    Err(format!("could not ask the BAG about {pand}: {last}"))
}

/// The outer ring of the feature with this identificatie, from a WFS answer.
pub fn outline_of(doc: &serde_json::Value, pand: &str) -> Result<Vec<(f64, f64)>, String> {
    let feature = doc["features"]
        .as_array()
        .into_iter()
        .flatten()
        .find(|f| f["properties"]["identificatie"].as_str() == Some(pand))
        .ok_or_else(|| format!("the BAG has no building {pand}"))?;
    let ring = match feature["geometry"]["type"].as_str() {
        Some("Polygon") => &feature["geometry"]["coordinates"][0],
        Some("MultiPolygon") => &feature["geometry"]["coordinates"][0][0],
        other => return Err(format!("building {pand} has a {other:?} outline")),
    };
    // GeoJSON is (lng, lat) even when the CRS is EPSG:4326.
    let ring: Vec<(f64, f64)> = ring
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(|p| Some((p[1].as_f64()?, p[0].as_f64()?)))
        .collect();
    if ring.len() < 3 {
        return Err(format!("building {pand} has no outline"));
    }
    Ok(ring)
}

/// The cell whose LoD2.2 file draws this building's shell, and whether that was
/// found in a published cell (`false`: filed by its outline instead).
///
/// **It has to be that one.** The client skips a shell only when the lod3 file
/// of the cell drawing it lists the pand, and a cell draws a building when the
/// building's first vertex is inside it — so a model filed under any other cell
/// is drawn *inside* the shell it was meant to replace. The Euroborg sits on a
/// cell boundary, which is how this was found.
#[must_use]
pub fn owner_cell(site: &std::path::Path, pand: &str, outline: &[(f64, f64)]) -> (Cell, bool) {
    let mut candidates: Vec<Cell> = outline.iter().map(|p| lat_lng_to_cell(p.0, p.1)).collect();
    candidates.sort_unstable();
    candidates.dedup();
    for cell in candidates {
        let Ok(bytes) = std::fs::read(site.join(cell_path("lod22", cell))) else {
            continue;
        };
        let Ok(file) = serde_json::from_slice::<File>(&bytes) else {
            continue;
        };
        if let Some(first) = file
            .elements
            .iter()
            .find(|e| e.id.0 == pand)
            .and_then(|e| e.p.first())
        {
            return (lat_lng_to_cell(first.0, first.1), true);
        }
    }
    (lat_lng_to_cell(outline[0].0, outline[0].1), false)
}

/// Generate a stadium over `pitch`, inside the building `pand` with this
/// outline: measure the bowl from AHN's surface model and build it.
pub fn stadium(
    pand: &str,
    pitch: [(f64, f64); 4],
    outline: &[(f64, f64)],
) -> Result<Vec<Element>, String> {
    let pitch = Pitch::of(pitch);
    let ring: Vec<[f64; 2]> = outline
        .iter()
        .map(|&(la, lo)| pitch.plane.to_en(la, lo))
        .collect();
    let reach = ring.iter().map(|p| len(*p)).fold(0.0, f64::max) + 10.0;
    let source = Pdok::surface();
    let mut last = String::new();
    let mut surface = None;
    for attempt in 0..3 {
        match Surface::fetch(&source, pitch.plane, reach) {
            Ok(s) => {
                surface = Some(s);
                break;
            }
            Err(e) => {
                last = e;
                if attempt < 2 {
                    std::thread::sleep(std::time::Duration::from_secs(3));
                }
            }
        }
    }
    let surface = surface.ok_or_else(|| format!("could not fetch the AHN surface: {last}"))?;
    let bowl = measure(&pitch, &ring, &surface)
        .ok_or("the AHN surface model does not show a bowl round that pitch")?;
    Ok(build(&pitch, &bowl, pand))
}

// ── The dataset ──────────────────────────────────────────────────────────────

/// Republish every building override (`crate::overrides`): recompile each one
/// and refile it, which is what a fresh LoD2.2 extract needs — a building's
/// owning cell can move when its shell is re-cut. A fresh atlas is seeded with
/// the Euroborg ([`EUROBORG`]) the first time this runs.
pub fn run(ctx: &Ctx) -> Outcome<DatasetResult> {
    let store = crate::overrides::Overrides::new(ctx.data_dir()?, ctx.site_root());
    if store.seed_once(&EUROBORG).map_err(PipelineError::Failed)? {
        ctx.log(format!("seeded the {} stadium", EUROBORG.name));
    }
    let all = store.list();
    let total = all.len();
    let mut triangles = 0usize;
    let mut failed = 0usize;
    for (i, record) in all.into_iter().enumerate() {
        ctx.check()?;
        ctx.progress(Progress {
            phase: Some("models".into()),
            done: Some(i as u64),
            total: Some(Some(total as u64)),
        });
        match store.recompile(&record.pand) {
            Ok(summary) => {
                triangles += summary.triangles;
                ctx.log(format!(
                    "{} ({}): {} elements, {} triangles → cell {}/{}{}",
                    record.name,
                    record.pand,
                    summary.elements,
                    summary.triangles,
                    summary.cell.0,
                    summary.cell.1,
                    if summary.cell_found {
                        ""
                    } else {
                        " (not in a published LoD2.2 cell; filed by its outline)"
                    }
                ));
            }
            Err(e) => {
                failed += 1;
                ctx.log(format!("{} ({}): {e}", record.name, record.pand));
            }
        }
    }
    if failed > 0 && failed == total {
        return Err(PipelineError::Failed(format!(
            "none of the {total} overrides could be built"
        )));
    }
    Ok(DatasetResult {
        cells: store.cells().len(),
        counts: vec![
            Count::new("models", total - failed),
            Count::new("triangles", triangles),
        ],
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_euroborg_pitch_is_a_football_pitch() {
        let p = Pitch::of(EUROBORG.pitch);
        assert!(
            (p.half_length * 2.0 - 106.5).abs() < 1.0,
            "{}",
            p.half_length
        );
        assert!((p.half_width * 2.0 - 68.0).abs() < 1.0, "{}", p.half_width);
        // It runs (nearly) north–south.
        assert!(p.along[1].abs() > 0.99, "{:?}", p.along);
    }

    #[test]
    fn a_ray_leaves_a_square_at_its_edge() {
        let ring = [[-5.0, -5.0], [5.0, -5.0], [5.0, 5.0], [-5.0, 5.0]];
        assert!((ray_exit(&ring, [1.0, 0.0]).unwrap() - 5.0).abs() < 1e-9);
        let d = std::f64::consts::FRAC_1_SQRT_2;
        assert!((ray_exit(&ring, [d, d]).unwrap() - 50f64.sqrt()).abs() < 1e-9);
    }

    /// A synthetic stadium: grass at 1 m NAP, a roof 20 m up from 10 m past the
    /// pitch to 40 m past it, a 6 m ring for 10 m beyond that.
    fn synthetic() -> (Pitch, Vec<[f64; 2]>, Surface) {
        let pitch = Pitch::of(EUROBORG.pitch);
        let plane = pitch.plane;
        let half = 170.0;
        let step = 0.5;
        let n = (2.0 * half / step) as usize;
        let centre = cartopolis_geo::ahn::wgs84_to_rd(plane.lat, plane.lng);
        let min = [centre[0] - half, centre[1] - half];
        // Measure in pitch coordinates by inverting each sample's position.
        let mut h = vec![f32::NAN; n * n];
        for row in 0..n {
            for col in 0..n {
                let rd = [
                    min[0] + (col as f64 + 0.5) * step,
                    min[1] + half * 2.0 - (row as f64 + 0.5) * step,
                ];
                // RD and the tangent plane agree to a few centimetres over this
                // box, which is far finer than anything asserted.
                let en = [rd[0] - centre[0], rd[1] - centre[1]];
                let along = en[0] * pitch.along[0] + en[1] * pitch.along[1];
                let across = en[0] * pitch.across[0] + en[1] * pitch.across[1];
                // Distance past the pitch, in a rectangle-shaped band.
                let past = (along.abs() - pitch.half_length).max(across.abs() - pitch.half_width);
                h[row * n + col] = if past < 10.0 {
                    1.0
                } else if past < 40.0 {
                    21.0
                } else if past < 50.0 {
                    7.0
                } else {
                    1.0
                };
            }
        }
        let outline = vec![
            pitch.en(-pitch.half_length - 60.0, -pitch.half_width - 60.0),
            pitch.en(pitch.half_length + 60.0, -pitch.half_width - 60.0),
            pitch.en(pitch.half_length + 60.0, pitch.half_width + 60.0),
            pitch.en(-pitch.half_length - 60.0, pitch.half_width + 60.0),
        ];
        (pitch, outline, Surface::from_raster(plane, min, step, n, h))
    }

    #[test]
    fn a_bowl_is_measured_where_it_stands() {
        let (pitch, outline, surface) = synthetic();
        let bowl = measure(&pitch, &outline, &surface).expect("a bowl");
        assert!((bowl.grass - 1.0).abs() < 0.01);
        // Straight out from the long side (θ = 90°).
        let s = bowl.sections[RAYS / 4];
        let side = pitch.half_width;
        assert!((s.inner - (side + 10.0)).abs() < 1.5, "{s:?}");
        assert!((s.back - (side + 40.0)).abs() < 1.5, "{s:?}");
        assert!((s.outer - (side + 50.0)).abs() < 1.5, "{s:?}");
        assert!(
            (s.inner_h - 20.0).abs() < 0.1 && (s.back_h - 20.0).abs() < 0.1,
            "{s:?}"
        );
        assert!((s.ring_h - 6.0).abs() < 0.1, "{s:?}");
    }

    #[test]
    fn the_model_leaves_the_pitch_open_and_four_gates() {
        let (pitch, outline, surface) = synthetic();
        let bowl = measure(&pitch, &outline, &surface).unwrap();
        let elements = build(&pitch, &bowl, EUROBORG.pand);
        assert!(elements.iter().all(|e| e.id.0 == EUROBORG.pand));
        // Nothing solid stands on the pitch or its apron.
        for e in elements.iter().filter(|e| e.class == "IfcWall") {
            for &(lat, lng, _) in &e.p {
                let en = pitch.plane.to_en(lat, lng);
                let along = en[0] * pitch.along[0] + en[1] * pitch.along[1];
                let across = en[0] * pitch.across[0] + en[1] * pitch.across[1];
                assert!(
                    along.abs() > pitch.half_length + APRON_M - 0.5
                        || across.abs() > pitch.half_width + APRON_M - 0.5,
                    "a solid vertex on the pitch at {along:.1}, {across:.1}"
                );
            }
        }
        // Four runs of slices have no stand: the gates.
        let s = &bowl.sections;
        let gates: Vec<bool> = (0..s.len())
            .map(|k| in_gate(&pitch, &s[k], &s[(k + 1) % s.len()]))
            .collect();
        let runs = (0..gates.len())
            .filter(|&k| gates[k] && !gates[(k + gates.len() - 1) % gates.len()])
            .count();
        assert_eq!(runs, 4);
        // Every roof slice is there, gates or not.
        assert_eq!(
            elements.iter().filter(|e| e.class == "IfcRoof").count(),
            RAYS
        );
    }

    #[test]
    fn the_stand_rises_from_the_front_wall_to_under_the_roof() {
        let (pitch, outline, surface) = synthetic();
        let bowl = measure(&pitch, &outline, &surface).unwrap();
        let s = bowl.sections[RAYS / 4];
        let rows = 30;
        let p = profile(&s, rows);
        assert_eq!(p[0], (s.front, 0.0));
        assert!((p[1].1 - FRONT_WALL_M).abs() < 1e-9);
        let top = p[p.len() - 2].1;
        assert!(top < s.back_h - HEADROOM_M + 1.0 && top > s.back_h - HEADROOM_M - 1.0);
        // Never downhill.
        assert!(p.windows(2).all(|w| w[1].1 >= w[0].1 - 1e-9));
    }

    /// Prints the measured Euroborg. Network: `cargo test -p cartopolis_atlas
    /// euroborg_profile -- --ignored --nocapture`.
    #[test]
    #[ignore = "fetches PDOK"]
    fn euroborg_profile() {
        let pitch = Pitch::of(EUROBORG.pitch);
        let url = "https://service.pdok.nl/lv/bag/wfs/v2_0?service=WFS&version=2.0.0&request=GetFeature&typeNames=bag:pand&outputFormat=application/json&srsName=EPSG:4326&count=20&bbox=53.2058,6.5912,53.2064,6.5920,EPSG:4326";
        let doc: serde_json::Value =
            serde_json::from_str(&ureq::get(url).call().unwrap().into_string().unwrap()).unwrap();
        let ring: Vec<[f64; 2]> = doc["features"][0]["geometry"]["coordinates"][0]
            .as_array()
            .unwrap()
            .iter()
            .map(|p| {
                pitch
                    .plane
                    .to_en(p[1].as_f64().unwrap(), p[0].as_f64().unwrap())
            })
            .collect();
        let surface = Surface::fetch(&Pdok::surface(), pitch.plane, 160.0).unwrap();
        let bowl = measure(&pitch, &ring, &surface).unwrap();
        println!("grass at {:.2} m NAP", bowl.grass);
        for s in bowl.sections.iter().step_by(4) {
            println!(
                "{:5.0}°  pitch {:5.1}  roof {:5.1}–{:5.1} at {:4.1}–{:4.1} m  ring to {:5.1} at {:4.1} m",
                s.theta.to_degrees(),
                s.pitch,
                s.inner,
                s.back,
                s.inner_h,
                s.back_h,
                s.outer,
                s.ring_h
            );
        }
        let elements = build(&pitch, &bowl, EUROBORG.pand);
        let tris: usize = elements.iter().map(|e| e.t.len()).sum();
        println!("{} elements, {tris} triangles", elements.len());
    }
}