garage44.eu/jeroen/cartopolis

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

.. /docs/notes/terrain-relief.md

raw


triggers:


Terrain relief: what AHN actually holds, and the shape the field takes from it

systems::terrain turns the client's flat y = 0 plane into measured ground. The numbers below are why it is shaped the way it is; the code says what it does.

How much relief is there, really (measured 2026-07-31)

Method: PDOK's AHN WCS (dtm_05m, EPSG:28992 GeoTIFF) queried directly over a 6.4 km box — the field's own extent — at 128² (50 m/sample) and 256² (25 m). Statistics over the finite samples only.

Place (RD centre)relief (max−min)sdcoverage
Groningen centre (233500, 582000)37.9 m1.898 %
Groningen ring south (234000, 579500)21.7 m2.093 %
Dunes @ Bergen NH (105000, 517000)40.4 m7.279 %
Veluwe @ Posbank (197000, 449000)101.9 m25.2100 %
Vaals / Limburg (197500, 307500)182.2 m39.941 %
Flevoland polder (165000, 500000)20.9 m1.299 %

Three things follow, and all three are load-bearing:

The vertical datum is the anchor, not NAP

Samples are stored relative to the ground under the map anchor. Absolute metres above NAP was rejected: it would drop the whole world 322 m below the camera in Vaals and lift it in the polder, for a picture that is identical — what the eye reads as relief is the difference between here and there, never the offset both share. Keeping the anchor at y = 0 also means every existing placement in the client stays exactly right at the middle of the map, which is where the user is.

The field is finite, so it tapers rather than ends

6.4 km of measured ground sits inside a clipmap that runs to the horizon, and the world outside AHN is flat by definition. The samples are therefore multiplied by a smoothstep that reaches exactly zero at the boundary, baked in rather than applied at lookup, so at() outside the box returns 0 and the two meet with no step.

The cost, stated plainly: a hillside crossing the boundary is flattened toward the anchor's level over the last ~600 m. Alternatives considered and rejected:

Why the whole thing is one request, baked once, on a worker

A consumer asks for a height thousands of times per mesh build, so the field cannot be a cache of per-question patches like systems::height's. One HeightRequest per map anchor (2049², 12.3 MB, 4.5 s measured) is baked into a regular grid in the anchored world-XZ frame; after that every lookup is bilinear arithmetic with no I/O.

That WCS request is now the fallback, not the source. Where atlas's terrain/coverage.json lists the area, the field is assembled from atlas's z14 terrain tiles (terrain_tiles): graded on atlas where the manifest says graded for every tile under the field, so the client only resamples them, and raw tiles graded on the device with the same cartopolis_geo::terrain_grade elsewhere — one code path, two places it runs. A handset's field is 513² over the same box (12.5 m, quality::handset_guarded), and over graded ground the field follows the camera (terrain::FOLLOW_M, 1.6 km out, by whole 800 m lattice steps, keeping the anchor's datum) and grows to 9.6 km once it has moved. All of that is level-of-detail-tile-tree.md, steps 2–3 and "Atlas grades"; a teleport within geo_nav::SHORT_JUMP_M (3 km) of the anchor moves the camera and keeps the field rather than re-anchoring.

The bake runs on platform::workers and lands through terrain::apply_coarse_terrain. It did not used to: at 25 m the field was 65,536 samples and ran inline. At 3.125 m it is four million — a wgs84_to_rd polynomial each, a distance transform to close the holes, and a min pyramid over the result — which is a long frame, and a long frame is the documented way to lose the device on the hardware this has to run on.

Baking resamples through world → lat/lng → RD per grid point rather than mapping the RD box onto the world box directly. RD is rotated against Web Mercator by the meridian convergence (~1° over NL) and scaled slightly differently: the axis-aligned shortcut puts the corners of a 6.4 km field ~80 m out, which is a hill in the wrong place.

What a bake actually cost, and the two loops it was (measured 2026-09-21)

worker_split in --dump-state put terrain_fine at 14.0 s for one job at 600 m over Groningen, and 31.4 s across four at 2,500 m — where it was why the capture sat out its whole --wait reporting busy=["terrain"] and never settled. Neither is the AHN fetch (4.7 s, measured against PDOK the same day) and neither is arithmetic the tier needs. Both were one helper.

WaterLevelField::level_at was a linear scan over every ring. The register yields 8,144 of them over this city and the fine tier samples 1024², so one bake asked ~8.5 billion bounding-box questions. The bounding-box reject was there and was doing its job; what it could not do is stop being asked. RingGrid buckets the rings into a uniform grid over their union box — a grid and not a tree, because the query is a point and canals are small, similar and evenly spread — and a sample now tests the handful near it. the_ring_index_answers_exactly_what_a_full_scan_does pins that this changed no answer, against the scan it replaced, including outside the indexed area where cell_of clamps to an edge bucket.

Worth knowing where that cost appeared, because it is two modules from its cause: it is the terrain stream that shows up busy, the cost is in water_levels, and nothing about the symptom says "water". It also scaled with the register rather than with the map, so it arrived gradually as the water extractor covered more of the country and never looked like a regression.

encode_slope's box blur re-summed its window per texel. 25 taps where a sliding window costs two, over 1024² texels, two channels, two passes — ~105 M loads against ~8 M — and the vertical pass walked columns over a 4 MB array, so every tap was its own cache line. It is a running sum now, and the vertical pass holds one accumulator per column and steps rows, so both the add and the subtract are sequential. the_running_box_blur_matches_summing_the_window_per_texel compares it against the direct form on a field with a cliff, a ripple and a plateau, and allows one unit of Rg8Snorm — a running sum carries float error the re-summation does not, and what has to hold is that it stays inside a quantisation step.

The coarse bake is start-up time, and it was the same helper again (measured 2026-09-26)

Over graded ground every surface and building cell waits for the coarse field (TerrainField::holds_builds), so its bake is on the critical path of every start and every re-anchor. On deck-1 (release build, Grote Markt) a pre-graded bake — no grading at all, only resampling atlas's tiles — took 4.3–5.1 s, one thread, and a warm start's waterfall was that bake, then the ground cells, then the settle.

terrain field bake timed / terrain field bake stages now log each part per bake. The first reading (container, dev profile, after the resample was already made separable and threaded) was 110 ms for resample and taper against 4,961 ms for bank_flags, four threads and all: a WaterLevelField::level_at point test per sample, 4.2 million of them. The grid index of 2026-09-21 made each test cheap; it could not make 4.2 million of them cheap. Three changes, each pinned against the code it replaced:

After: resample 91 ms, taper ~20 ms, banks 332 ms on the same container build.

The field arrives after the anchor, so every consumer needs a revision

at() returns 0 while the request is in flight, which is the same answer it gives outside the Netherlands and with the layer off — that uniformity is what lets a consumer add the lift unconditionally. The price is that every streamer builds its first cells on flat ground and must retear when the real field lands a second or two later. TerrainField::revision is that signal, and a consumer holds the revision it built against beside its cell keys.

The ground and building cells do it per cell (MapSurfaces::built_rev, Lod22Buildings::built_rev): a new field rebuilds only a cell whose TerrainField::cell_digest — the heights under it plus a 50 m margin, and for ground cells the water over it — changed. Everything else still retears by ring. And over graded ground those two cell streamers do not build flat first at all: TerrainField::holds_builds holds them until the field lands (they fetch meanwhile), because that field needs nothing from the cells and is seconds away. Ground graded on the device cannot be waited for — its bake needs the cells' roads.

The failure is silent and one-sided, which is why this is written down: the consumers that were wired sink or rise together and look right, and the one that was not stays where it was while the ground moves under it. Street labels (2026-08-10) were exactly that — the road surfaces beneath them were displaced, the names were not, and with the Height layer on the text sank into the road. A new thing standing on the ground is not done until it carries the revision.

A re-anchor clears the field at once (2026-11-02). "at() returns 0 while the request is in flight" was true only for the first anchor. After a jump the old field stayed installed until the new one baked, and its samples are indexed by world metres from the old origin, so for those seconds every cell was built on the old place's hills at the new place. Groningen → Winsum (datum 7.2 m, relief −11…19 m, against Winsum's −2…4 m) left the buildings hanging in the air on a phone, and they stayed there after Winsum's field landed: some consumer built in that gap was not rebuilt by the bake's revision bump. Which one was not chased; update_terrain_field now clears a field answered for an older anchor generation, which bumps the revision and makes flat the ground in the gap, as it is at start-up. Seen in a --shot-mode avatar pair, Groningen then Winsum, against a fresh Winsum capture.

The physics stays flat; only the picture stands on the ground

simulator is authoritative for the avatar and holds no map data at all — the terrain streams only on the client, so the sim cannot know about it. Rather than teach it (a protocol change, for data it has no way to obtain), the terrain is added on the display side: AvatarState::position stays on the flat plane the sim simulates, display_position stands on the measured ground, and the difference is terrain_lift. The lift is stripped before each reconciliation — a lifted position easing toward a flat target is dragged back into the hillside every frame, and the two fight for as long as you stand on a slope.

Two consequences worth knowing:

Earcut's answer cannot follow a hill

MVT polygons are triangulated with as few triangles as the outline allows — a field or a lake is two. Two triangles cannot follow terrain, they can only be tilted by it, so ground surfaces are refined before displacement (refine_for_terrain).

The refinement is per edge, not per triangle: an edge longer than the threshold is split once, its midpoint is shared by both triangles that own it, and each triangle is re-cut by how many of its edges were split. Deciding per triangle ("this one is big, subdivide it") leaves a T-junction wherever a split triangle meets an unsplit neighbour — and a T-junction on a slope is a crack you can see the sky through.

Not everything is refined, and the exceptions are about kind, not cost:

A quad per level, not a quad per sample (changed 2026-09-13)

Every mesh that stands on the field used to size its subdivision off the field's own sampling: refine_for_terrain split edges longer than 24 m against a 25 m field, and map_stream::relief_divisions gave a basemap tile ceil(tile_m / 25) divisions. The rule read as obviously right — a vertex per measurement, no more and no less — and it had a second job nobody wrote down: relieved clipmap levels are stacked only 0.4 m apart, so a level that approximated the ground more crudely than the one above it would poke through it on any slope, and making every level exact was what made that impossible.

It is also what pinned the field at 25 m, and what kept Groningen flat. See the section below.

What replaced it. A clipmap level is twice the size and twice as far out as the one above it, so every level's tiles subtend about the same solid angle: a constant division count per tile is what puts a constant number of pixels on a quad. The world-space rule spent its triangles the other way round — at 25 m a 2,500 m tile got 100 divisions and 20k triangles for ground kilometres away, while the tile underfoot got 8. relief_divisions is now min(32, tile_m / TERRAIN_SAMPLE_M): constant on every level a city streams, and bounded below by the field so a small tile never invents vertices between measurements.

And the poke-through moved to where it belongs, into what the mesh samples. displaced_grid reads TerrainSnapshot::floor_at at its own quad size — a lower envelope of the field, min-filtered over ±2 quads, built as a 2× min-reduction pyramid in terrain::build_floors. The property, and it is exact rather than tuned: the interpolated value anywhere in a mesh cell is at most the largest of the cell's four corner values, and each of those is a minimum over a box containing everything that cell touches — so the drawn surface is everywhere at or below the measured ground, at any relief, and a coarse level can no more rise through a fine one than a flat plane could. The 0.4 m stacking is margin now instead of the whole guarantee. a_coarse_quad_never_draws_above_the_measured_ground pins it, checking between the vertices as well as on them, because linear interpolation is what a mesh actually draws.

A fixed division count is still a trap, and the upper bound is what stands against it. It was tripped once (fixed 2026-07-31): RELIEF_DIVISIONS = 48 was chosen for a ~1.5 km tile, but the clipmap's finest zoom follows altitude — over a Dutch city it is z17, a 184 m tile — and the same constant went to all four levels under RELIEF_MAX_TILE_M. That put 4,608 triangles on a tile the field described with 7 samples across.

Measured on the Groningen anchor (--offline, settled, 60 m):

basemap trisshadow trisidle fps
flat (no --height)3 k1.07 M—
relief, fixed 48942 k2.96 M24–27, with 12 s bands at 10–11
relief, per-sample @ 25 m + no cast373 k0.79 M¹35–45, no slow bands

¹ excluding lod22, which loaded more cells in the second run.

373 k is the ceiling the constant is sized against: ~166 tiles qualify for relief over a Dutch city, and 2·32² triangles each is ~340 k.

The relief tiles are also NotShadowCaster: four levels of ground redrawn into every cascade measured as ~2.5× the mesh's own cost, for self-shadowing the field can barely express. The trade is deliberate — a hill no longer darkens the valley behind it at a low sun. Over Dutch relief (±2 m) that is invisible; if the Veluwe ever needs it, it belongs to the finest level alone, not to all four.

It was a UI bug as much as a rendering one while egui drew the UI (until 2026-11-26): a click cost three egui passes, and a press→release spanning more than 0.8 s was discarded, so at 10–11 fps panel checkboxes and close buttons stopped responding while the camera still felt fine. Whether the component library degrades the same way at a low frame rate is unmeasured.

25 m had no slopes in it, and that is why the field is 3.125 m (measured 2026-09-13)

The measurement at the top of this note says Groningen's relief is 38 m over the box with a standard deviation of 1.8 m, and concludes "a capture over a Dutch city will look almost identical with the layer on and off — that is the ground, not a bug". The conclusion was wrong, and the reason is that relief is a range and what the eye reads is a gradient.

The Hondsrug rises 7 m through the centre of the Groningen box and falls to −0.7 m a kilometre west. The 25 m field carried all of it, over 256 samples, so no facet ever tilted more than half a degree. Method: PDOK dtm_05m over the field's own 6.4 km box, resampled, then the Lambert term of each facet's normal against a 30° sun, relative to flat ground.

field spacingmedian slopep90 slopeshading, p05 – p95
25 m0.46°1.96°0.96 – 1.04
12.5 m0.72°3.50°0.92 – 1.07
6.25 m1.07°6.68°0.86 – 1.13
3.125 m1.34°10.98°0.77 – 1.19

±4 % is below what anyone can see, over textured map imagery, at any time of day. So the ground was measured, displaced, normal-mapped and lit correctly, and was indistinguishable from a plane. terrain_relief_m could not show it either — it is the range over the whole box, and it barely moves between those rows, which is why terrain_sample_m is now in --dump-state beside it (with terrain_ready). A gate on resolution asserts terrain_sample_m, never the range.

What 25 m cost, and what it bought. It bought one 220 kB request and a 65,536-sample bake cheap enough to run inline on the main thread. 3.125 m is 2049² — 12.3 MB on the wire in 4.5 s, 17 MB resident, four million samples — so the bake moved onto platform::workers (terrain::apply_coarse_terrain installs it), the hole fill became a distance in metres rather than a count of dilations, and MAX_GRID in height.rs went to 4096. 2049 and not 2048 so the intervals are a power of two and the floor pyramid halves exactly.

Three things were considered and are worth recording:

What decides whether a street has a gradient is MAX_GROUND_EDGE_M

Worth separating from the field's own resolution, because they are different questions with different costs. In a city the ground you look at is vector surfaces — paving, carriageways, verges, squares — and the basemap tile under them is covered almost everywhere. So MAX_GROUND_EDGE_M is what the street's shading comes from, and TERRAIN_SAMPLE_M only has to be fine enough that those vertices land on measurements rather than between them.

It is 12.5 m, four field samples per edge, and the number was chosen against a measured upload burst rather than against the picture. Two samples per edge (6.25 m) is what the field can carry and is what the finest clipmap quad already is, so it looked obvious. Measured over Groningen 2026-09-13, --height on against off at the same settled viewpoint (53.2194, 6.5665, 260 m):

upload_peak_asset_kbgpu_resident_kbpixels differing >16/255
height off8 MB1,244 MB—
height on, 6.25 m edges37 MB1,666 MB36.9 %

37 MB is one mesh handed to the driver in a single frame. A map_geometry cell is a z14 tile, ~1471 m across, and a fully covered one refined to 6.25 m is a six-figure triangle count merged into one asset per group. That is exactly the burst lod22::MAX_CELL_MESH_BYTES exists to cut up, and the ground groups have no equivalent — bevy's upload budget writes one whole asset per frame, so Budget::upload_bytes_per_frame cannot spread a single huge one however low it is set.

So the geometry stops at 12.5 m and everything below belongs to the layer that costs no triangles (see below). Splitting the surface meshes by byte budget the way lod22 does is what would buy the finer half back, and is the thing to do first if this number is ever wanted lower.

One related saving fell out of the same rule: TerrainSnapshot::ground_edge_m returns infinity when the field is absent, so refine_for_terrain returns after one scan. With the Height layer off the old constant still cut every ground polygon in the city at 24 m, for a displacement of exactly zero.

MAX_REFINE_PASSES is still 5, so one enormous polygon stops at 1500/32 ≈ 46 m rather than tessellating the frame away — a big park is still coarse, and that is the other bound to raise if it ever matters.

A wall inside one quad: the crease rule (added 2026-09-16)

12.5 m is what a whole cell can afford, and over the flat nine tenths of a Dutch cell it is more than the ground needs. The tenth that matters is where the field holds a step — a quay wall, the lip of an embankment, a dyke crest, a road cut through a bank — and there a 12.5 m chord can only average across it. Measured at the study pond quay wall in Groningen (53.2226 N, 6.5820 E), through all three stages:

face heightsteepest facet
AHN, 0.5 m native1.86 m74.8°
the coarse field, 3.125 m1.66 m27.4°
what was drawn, 12.5 m edges0.65 m5.9°

The field keeps about 90 % of the height; the mesh threw away two thirds of it. Across that 610 × 700 m block, 34.6 % of 12.5 m ground quads held more than half a metre of relief they had no vertex to express.

So refine_for_terrain has a second rule, and the two compose — an edge splits if either asks. max_edge is uniform and priced against the cell; Crease splits where the mesh disagrees with the field: the ground under an edge's midpoint departing from the chord between its ends by more than CREASE_SAG_M (0.15 m). Stated that way it is the refinement error itself, so it goes to zero on flat ground by construction, and — this is the part worth knowing — it goes to zero on an even slope too. A chord across a plane is the plane. It is "where the ground is not straight", never "where the ground is not flat".

Measured on one 12.5 m quad straddling that wall: the drawn surface went from 0.567 m off the measured ground to 0.027 m, for 4 → 16 triangles on that quad and none anywhere flat.

Three bounds, and none is optional:

It does not reach the real 74.8°, and it cannot: the coarse field does not hold it, and sampling the half-metre tier from a mesh is forbidden for its own reason (that tier re-centres as the camera walks, so the mesh would change shape underneath you). A true vertical face is a job for geometry that knows it is a wall — which is what walls-have-a-measured-height.md is about.

A capture can photograph flat ground and call itself settled (fixed 2026-09-13)

The relief meshes are built MAX_RELIEF_BUILDS_PER_FRAME (2) at a time — the documented guard against an upload burst — and ~166 tiles qualify over a city, so a cold clipmap is about 83 frames from being shaped. Nothing in the settle test knew that. terrain_ready said true, every tile stream went quiet, and the shutter fired on a plane.

Measured on the Posbank at --wait 20: settled=false, ktris_total=15k, and a photograph of flat ground over 98 m of measured relief. The same viewpoint at --settle 6 --wait 200 settles with busy=[] and draws the Veluwezoom's slopes.

map_stream::ReliefBacklog counts the tiles still owed a relief mesh and relief is in the harness's busy list beside terrain. The two are different questions — "has the field arrived" and "is the ground drawn with it yet" — and only the second decides what the picture shows.

Sub-metre is a shading problem, not a geometry one (built 2026-09-13)

3.125 m is what gives a street a gradient. It is not what gives it a kerb, and the two are different problems with different answers.

AHN's own grid is half a metre and the fine tier already fetches it — 1024² over a 512 m box following the camera. What cannot follow is the geometry: map_geometry builds its ground surfaces per z14 cell, ~1471 m across, so half-metre vertices over one cell is about nine million quads, rebuilt on every re-anchor. Raising the clipmap instead does not help either, because in a city the vector surfaces cover the basemap tile almost everywhere — a 40 m capture over the Groningen centre is entirely rooftops, with no basemap visible at all.

What sub-metre relief is, though, is 5–30 cm of amplitude: a kerb, the camber of a carriageway, the lip of a quay, a rut across a verge. All of that is shading, not silhouette — the same observation water.wesl is built on, where a canal is two triangles and every wave lives in the normal.

So systems::ground_detail puts it in the normal:

Measured over the Veluwe at 45 m, settled, the same viewpoint with the switch on and off: ground_detail_ready true / false, ground_detail_sample_m 0.50 / 0.00, and 14.0 % of pixels differ (5.7 % by more than 4/255).

Everything flat on the ground carries it: the clipmap tiles, the vector surface groups, and the roads. The roads reach it a different way and it is worth knowing why — they need a vertex stage of their own for the depth ladder, so they cannot share the material type, but they declare the same three bindings at the same numbers and name shaders/ground_detail.wesl as their fragment shader. Two material types, two vertex stages, one description of what the ground looks like up close.

The volumetric groups — canopy, trunk, street furniture — are deliberately out of it. A tree's normals describe the tree, and giving a canopy the ground's sub-metre slope is the same mistake stand_on_terrain refuses to make when it keeps their normals instead of re-deriving them from the field. They are created with a negative params.w, which refresh_ground_detail treats as a permanent opt-out.

Two details that are easy to get wrong. refresh_ground_detail keys its already-applied test on the material count as well as the box and the origin, because a cell that streams in after the last write would otherwise keep the zero strength it was built with until the box next moved; wet_surfaces::DrySurfaces guards itself the same way. And the ground materials must share one Image handle, rewritten in place on each re-centre — handing out a new handle would rebuild hundreds of bind groups for a buffer whose size never changes.

Still flat, deliberately or otherwise

It is on, and there is no switch

Worth stating plainly, because a stale comment next to the aerial toggle said the opposite and was believed on 2026-09-20: the measured ground has no toggle. update_terrain_field carries no run condition and reads no layer flag; the only gate is HeightLayer::covers. Over the Netherlands it bakes, and everywhere else it does not, which is the same thing as being off where there is nothing to fetch. The --height flag that once opted a scripted capture in went with the toggle (2026-09-16, 4b1eec6e): every capture over the Netherlands has relief, and "flat (no --height)" in the tables above is a measurement from before then.

The aerial basemap is opt-in, and for its own reason — it replaces the drawn ground rather than adding to it. That reason does not transfer.