garage44.eu/jeroen/cartopolis

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

.. /docs/adr/038-pluggable-terrain-elevation.md

raw

ADR-038: Pluggable Terrain Elevation (Height-Field Sources, AHN First)


Metadata:


Context

Problem: The map tier is flat. ADR-035 moved the basemap from raster photographs to tessellated vector geometry (systems/vector_tiles.rs, systems/map_geometry.rs), but every surface it produces sits at y = 0 with a millimetre stacking offset per SurfaceGroup to keep the layers from z-fighting. A canal is a blue polygon painted on a plane; a dijk is invisible; a grass verge has no camber. In a world whose point is being situated (G-04), the ground is the one surface that never behaves like ground.

Two smaller problems ride along:

  1. 3DBAG building heights are already absolute NAP (ADR-027). Drawing them on a plane at y = 0 is not merely "missing relief" — it is a latent datum inconsistency between two datasets that are meant to agree.
  2. Ground height is assumed, never queried. geo_nav::AVATAR_GROUND_Y, the gravity clamp in avatar::handle_avatar_movement and cartopolis_simulator::state's spawn y each hard-code a constant. Nothing in the codebase can answer "how high is the ground here?".

What resolution this needs. The features wanted — canal banks, ditch profiles, dijk slopes, the crown of a road — are 3–15 m wide. A global 30 m DEM cannot express them (a 6 m canal is a fifth of a pixel), and Copernicus GLO-30 is additionally a surface model containing trees and rooftops. Sub-metre bare-earth data is not a nicety here; it is the feature.

But sub-metre bare-earth data is national, not global. It exists because a country flew LiDAR over itself. The Netherlands has AHN; other regions have their own, with different formats, resolutions, licenses, vertical datums and update cadences — and most of the planet has nothing better than a coarse global DSM. Any design that treats "the DEM" as a singular thing will be wrong the first time we leave NL. The elevation source has to be a plug, and having no plug at all has to be the ordinary case, not the error case.

Requirements:

Decision

Terrain is a registry of interchangeable height-field sources, normalised at ingest to one canonical tile format and datum, sampled by the renderer into a single welded ground triangulation per cell. AHN is the first source; flat is the default.

The client knows nothing about AHN, PDOK, LiDAR or the Netherlands. It knows how to sample a height tile.

1. TerrainField — the runtime contract (ADR-030 substitutable provider)

One resource, two operations:

None means no data, and every consumer falls back to the flat plane by construction rather than by special case. None is not degraded mode; for most of the planet it is the answer.

2. TerrainSource — the descriptor, declared in configuration

A source is a config entry (ADR-014 layering), not a code path:

FieldPurpose
id, nameidentity
url_templatez/x/y into our own origin
coveragebboxes, or a low-zoom coverage bitmap for ragged extents
native_resolution_mdrives Steiner-point density (below) and max useful zoom
max_zoomdepth of that source's pyramid
prioritywhich wins where two sources overlap
kindbare-earth (DTM) vs surface (DSM) — affects whether buildings double up
attribution, licenserendered in the credits; non-optional

Per cell the client picks the highest-priority covering source, or none. Adding a region is a manifest entry plus an ingest run. No client release, no code.

3. Canonical encoding and datum — normalise at ingest, not at runtime

The runtime speaks exactly one format. Everything heterogeneous is absorbed by the offline step.

The ingest tool is a set of input adapters — COG GeoTIFF, ASCII grid, LAZ point cloud, or passthrough for a source already published as Terrarium — emitting the canonical pyramid. A new region needs an adapter only if it brings a format we haven't met.

4. The first source: AHN (Netherlands)

AHN is published by PDOK as CC0, bare-earth DTM at 0.5 m, in Cloud Optimized GeoTIFF tiles of 5 × 6.25 km, bulk-downloadable over ATOM (service.pdok.nl/rws/ahn/atom/dtm_05m.xml). AHN5 is the 2026 release and replaces AHN4 in place. We carry it to z16–z17, where a texel is ~0.5 m at NL latitudes — public Terrarium sets stop at z15, which is why we generate our own.

Served from garage44 behind the same Caddy as 3DBAG, Nominatim and the MVT tiles: the ADR-027 pattern again. We do not call PDOK per tile at runtime — same reasoning as ADR-035.

A coarse global source (Copernicus GLO-30 via Mapterhorn/AWS Terrarium) is an obvious second entry for mountains and coastlines. It is a manifest entry at lower priority, not a design change, and it is explicitly not what delivers this ADR's goal.

5. Water: enforced at ingest, not carved at runtime

LiDAR gets no return from water. In a DTM every canal, ditch and pond is a void filled by interpolation, so the sampled surface is roughly the water level, flat — banks real and sharp, channel a hole. This is true of every LiDAR-derived product.

The height field is therefore simply wrong over water, and the place to fix a wrong height field is the height field. At ingest we rasterise the water polygons into the DEM and lower them, leaving the banks — standard DEM hydro-enforcement. The runtime then does one thing: sample the field and displace the mesh. There is no water case in the renderer.

Two consequences to accept:

The one genuinely water-specific thing that remains is the water surface level — a single-valued height field cannot hold both bed and surface at the same point. That is one number per water body applied to the existing SurfaceGroup::Water mesh, which sits above the enforced bed. Small and contained.

6. One welded ground TIN per cell

This is the part that is not "sample a DEM per vertex", and the reason the ADR is R2.

Displacing each SurfaceGroup's tessellation independently cracks the map. Coincident vertices land at the same height; coincident edges do not. A road polygon's edge may be one long segment where the grass beside it has a vertex halfway along — identical on flat ground, and on a slope the straight edge and the two-segment edge diverge, opening a gap and a z-fighting seam along every land boundary in the scene.

So tessellate_surfaces changes from N independent triangulations to one constrained Delaunay triangulation per cell over all ground polygons together, with height-field samples inserted as Steiner points, then split into per-SurfaceGroup meshes by which source polygon each triangle fell in. Watertight by construction.

Steiner density comes from the source descriptor, not a constant: a 0.5 m source earns dense sampling, a 30 m source must not generate 0.5 m grids, and a None cell generates no interior points at all and reduces exactly to today's flat tessellation. This is what keeps a mixed-coverage world inside one triangle budget.

Two things fall out, both good:

Roads are the awkward case: Shortbread serves them as lines, stroked into ribbons, and a ribbon is hard to weld into a TIN. Interim: displace the ribbon by the same field and accept a small mismatch at kerbs.

7. Seams between sources

Where a fine source meets a coarse one, or any source meets None, the height steps. Blend over a feather band at the coverage boundary, driven by the descriptor's declared accuracy. The None boundary is the sharpest case — real elevation dropping to a plane — and is the one to test first, because it is the boundary most users will actually see.

Downstream: better vector sources per region (noted, not decided)

The same pluggability question applies one layer up. PDOK serves BGT as MVT over an OGC API (https://api.pdok.nl/lv/bgt/ogc/v1): 20 cm national topography with roads as polygons (wegdeel) rather than lines, which would fix the road-ribbon problem properly. It is a natural fit for the TIN and for regional substitution generally.

Not decided here — it splits the vector source by region, doubles the styling surface (PAINT_ORDER is Shortbread-shaped), and lands mid-flight in ADR-035's workstream. Revisit once the TIN exists and can be judged against a real source.

Rationale

Primary Reasoning:

  1. Sub-metre bare-earth data is inherently national, so the source must be a plug and "no source" must be ordinary. Designing around a single DEM would be wrong the first time we leave the Netherlands.
  2. Normalising at ingest keeps the runtime small. One encoding, one datum, one sampling path. Format, projection and datum diversity is absorbed by an offline tool where it costs nothing per frame and nothing in wasm binary size.
  3. Cracks are the real engineering problem, not fetching a DEM. Any design that displaces polygon groups independently fails on the first slope; deciding the welded-TIN structure now avoids building the wrong version first.
  4. Water depth is a data defect, not a rendering feature. Fixing it at ingest removes a whole special case from the renderer, which is worth more than the uncovered-region case it gives up.
  5. It simplifies as much as it complicates: the tuned millimetre offset stack is replaced by a structural guarantee, and three hard-coded ground constants become one queryable function.
  6. It fixes an existing datum inconsistency between 3DBAG's absolute heights and a ground plane at zero.
  7. It follows the established shape — preprocess offline, serve static from garage44 behind the same Caddy, decode in pure Rust on the tile worker pool.

Alternatives Considered:

AlternativeProsConsRejected Because
Hard-code AHN as "the" DEMSimplest possible; ships fastestEvery other region is then a rewrite; NAP leaks into the runtime contractThe requirement is explicitly that other regions plug in their own or nothing
Global DEM only (GLO-30 / Mapterhorn / AWS Terrarium)Worldwide; no per-region ops; PMTiles ready-made30 m posts, and a DSM — trees and roofs, not bare earthCannot represent a 6 m canal or a verge slope at all. Kept as a low-priority registry entry, not the answer
Kadaster 3D Basisvoorziening — CityJSON terrain (BGT polygons already triangulated with AHN heights)Effectively this ADR's output, pre-built and classified; solves cracks and roads for usBulk download op aanvraag; current jaargang only; annual cadence; NL-only; license unconfirmed; a pipeline we don't control — and a per-region format the plug model exists to avoidA dependency to take on rather than a pipeline we own. Kept as the validation reference to diff our TIN against
3D Basisvoorziening — Quantized Mesh DTMReady-made LOD terrain pyramid, well-specifiedSame access constraints; a separate terrain surface our polygons must then be draped onto, reintroducing welding at another layerDoesn't remove the hard part; adds a second geometry source
PDOK WCS / COG reads at runtimeNo preprocessingThird party in the per-tile path; RD projection and COG range reads on the client; contradicts ADR-034/035Same reasons ADR-035 self-hosts the MVT tiles
Vertex-shader displacement from a height textureNo CPU tessellation change; cheapNeeds dense uniform subdivision anyway to have vertices to move; leaves cracks untouched; gives collision and geo-nav nothing (they need a CPU query)Solves the easy half and none of the hard half
Runtime water carving from vector polygonsWorks with no DEM, so canals appear worldwideA permanent water special case in the renderer, existing only for uncovered regions; duplicates what ingest already does where there is a DEMFix the height field at ingest instead; uncovered regions get flat water
Stay flatZero work, zero riskGround never behaves like ground; 3DBAG datum mismatch persistsThis is the request

Consequences

Positive:

Negative:

Phasing (each step independently shippable and visible):

PhaseContentDepends on
1TerrainField + TerrainSource registry with only the flat source — proves the no-data path and changes nothing visually—
2AHN ingest → canonical pyramid on garage44; displace existing per-group tessellations and building bases1
3Hydro-enforcement in ingest; water surface level per body2
4Welded CDT per cell; retire the y_offset/depth_bias stack2
5Ground-height query wired into collision, geo-nav, avatar spawn2
6 (optional)Coarse global source as a second registry entry; per-region vector sources (BGT)4

Phase 1 first is deliberate: the substitutable path is the one that must not rot, and building it before any real data exists is the only way to be sure the flat case is a first-class path rather than a fallback nobody exercises.

Related