# `helix city roads build`

Turns the road graph of a `helix.city-source/1` folder into drivable, walkable road geometry: per fixed 1,024 m cell one
meshopt-compressed GLB (asphalt, kerb and sidewalk, lane markings), one welded and simplified collider, and the terrain cut and
fill under the roads. Deterministic: the same source and options give byte-identical files. Procedural, no per-road authoring.

```bash
helix city roads build ./sf-core --out ./sf-roads --report ./sf-roads/report.json
helix city roads build ./sf-core --out ./sf-roads --no-terrain      # cells and colliders only
helix city roads build ./sf-core --out ./sf-roads --no-markings
```

Design: `coordinator/open-world/SCENE-PIPELINE-DESIGN.md` §3.4. Code: `src/city/roads/` (generator) and `src/city/terrain/` (ground
model and conform). Input format and validator: `docs/city-source.md`. Importers: `docs/city-import-osm.md`.

## What you get

```
sf-roads/
  chunks/road/<sha256>.glb            one per 1,024 m cell that has roads
  chunks/road-collider/<sha256>.glb   the same cell, welded and simplified, at most 60,000 triangles
  terrain/dem.conformed.r16 + .json   the ground model with roads cut/filled into it (2 m default spacing)
  terrain/splat-roles.u8 + .json      0 ground, 1 asphalt, 2 pavement, 3 bank (the cut or fill slope beside a street)
  roads-manifest.json                 cells with cx, cz, file, sha256 and per-cell stats; the report; no wall-clock
```

Cell `(cx, cz)` covers plan x in `[cx*1024, (cx+1)*1024)` and plan z likewise (z is south, as in the city source). Cells are
clipped to `frame.boundsXZ`, so nothing is drawn outside the city.

## The cell GLB (the engine contract)

Three primitives, so three draws, in this order. Each carries a plain PBR base colour so a runtime that ignores the city
materials still draws plausible road; `HELIX_materials_city` is listed in `extensionsUsed`, never `extensionsRequired`.

| primitive | name | content | `_ROAD.x` kinds |
| --- | --- | --- | --- |
| 0 | `road-asphalt` | carriageways, junction patches, paths | ASPHALT 0, CONCRETE 1, SETT 2, GRAVEL 3 |
| 1 | `road-kerb` | kerb faces, sidewalks, medians, roundabout islands, deck fascia, undersides and barriers, piers, tunnel portals | KERB 4, SIDEWALK 5, MEDIAN 6, CONCRETE 1 |
| 2 | `road-markings` | thin quads lifted 6 cm off the surface, alpha-blended | ASPHALT 0 |

Vertex data, all through `EXT_meshopt_compression` with `KHR_mesh_quantization`:

- `POSITION` uint16 on a **global 1/60 m lattice**. The node scale is `1/60` and its translation the cell origin. Neighbouring
  cells snap every border vertex to the same lattice point (canonical plane crossings), so cell seams are exact, not
  approximate. The lattice step (1.67 cm) is why markings sit 6 cm up: the road and the paint snap separately, so a lift under
  three steps can land on the surface and z-fight at grazing angles.
- `NORMAL` int8 normalised, `_ROAD` uint8x4 normalised: x surface kind, y lateral position across the carriageway, z lanes/8,
  w wear and paint-age seed. These mirror the engine's `systems/scene/src/materials/city/params.ts` (`ROAD_SURFACE`, `packRoad`).
- Markings only: `COLOR_0` uint8 RGBA (paint colour, alpha is coverage) and `TEXCOORD_0` uint16, a rect of the 1,024 markings
  atlas (`MARKING_ATLAS`: line, zebra0-3, arrow, bus, stop, only). Asphalt and kerb primitives carry no UVs: patterns are
  world-space in the engine.

## How the geometry is made

1. **Network.** Edges are sorted, merged through degree-2 nodes when their attributes agree (a `ramp` flag counts), and given
   class widths, lanes and sidewalks. The class table (`CLASS_SPEC`, `constants.ts`) is CS2 data, measured from Ruben's Granit road
   cuts by lane road-canon: a city lane is 3 m and a highway lane 4 m, and a road's full corridor is a Small (16 m), Medium (24 m)
   or Large (32 m) reserve (`laneM`, `reserveM`). Source values win. Paths (footway, cycleway, path) are ribbons without kerbs.
2. **Elevation.** The ground model (DEM with building footprints masked and inpainted) is sampled along each edge, smoothed
   longitudinally, and held to a class grade cap (highways 4 %, arterials 12 %, local streets 10 %, ramps 7 %). Junction nodes carry one height shared by every edge.
   A bridge deck, or any freeway edge that stands more than 2.5 m above the ground, is a *deck*: it must clear every lower road
   under it by 4.5 m (5.5 m over a motorway) plus its own thickness. A deck that cannot reach that inside the grade cap pulls
   its approach chain up with it: the abutment nodes get a floor (at most 3 m over a road at grade, 20 m over another deck), the relaxation runs again, and so on for up to 14 passes
   (`computeElevation`, report fields `crossingPairs*`, `abutmentsRaised`, `headroomRemainder`). CS2 sources (`ys`) are
   authoritative and followed as given.
3. **Junctions.** Legs are sorted by angle; kerb lines of neighbouring legs are intersected; each corner becomes a quadratic
   Bezier fillet (radius by class, 3 to 9 m), a straight chord, an outer corner or a bevel; sidewalk returns are ear-clipped.
   Setbacks are shared between the two ends of an edge (fillets give way first). A junction that cannot be solved falls back to
   the convex hull of its mouths and is listed in the report. A junction whose legs are all decks gets an underside, a fascia
   and a barrier along each corner path, so a freeway interchange is one continuous slab.
4. **Ramps and gores** (`gore.ts`). Where a `ramp` edge meets a freeway at a three-leg node, the junction solver is skipped and
   a gore is built: an asphalt wedge from the point where the ramp's edge parts from the freeway's to the nose (3.6 m wide),
   solid white edge lines on both sides, V chevrons pointing with traffic, and, at grade, an auxiliary lane (3.6 m, tapering over
   up to 200 m) on the far side of the node so the freeway keeps its lane count through the merge. On a deck the wedge has an
   underside and a Jersey barrier on its outer edge and no aux lane. Seven of the 19 three-leg freeway nodes in SF stay on the
   ordinary junction code because the ramp never parts from the freeway within the sampled length or the wedge never opens.
5. **Decks** (`ribbons.ts`, `DECK`). A deck edge has a girder of visible thickness (highway 1.25 m, arterial 1 m, local 0.8 m,
   path 0.5 m), a fascia, an underside spanning the barrier feet, and a barrier on each outer edge: a New Jersey profile
   (1.07 m high, 0.54 m at the foot, CS2 kit) on highways, a 0.9 m parapet elsewhere. Piers (two columns and a bent cap) every 30 m.
6. **Tunnels** (`portals.ts`). A source tunnel is not drawn, but where a drawn road runs into one the mouth is: a 12 m concrete
   box with 5.2 m clear height, a headwall with wings and a lintel, the road's own asphalt inside, a back wall. Nothing is drawn
   between the mouths. Tunnels whose ends meet only paths, rail or nothing drawn get no portal.
7. **Dual carriageways.** Two opposite one-way edges with the same name, 1.2 to 32 m apart and parallel within 3 m, stay two
   edges; each takes half the gap, measured at five stations along it, as a raised median on the side facing its partner, so
   converging carriageways never overlap their medians.
8. **Roundabouts.** The ring is drawn by the ordinary edge and junction code; its raised island is built from the ring's inner
   kerbs joined round each ring node by that junction's corner path.
9. **Markings.** A locale table (`us`, `eu`) sets centre-line colour and dash rhythm. Lane dividers and centre lines (15 cm;
   two-way local streets of 5.9 m and wider get one too), edge lines (20 cm), stop lines at signals and stop signs (40 cm),
   zebras at crossings, and lane turn arrows on signalised arterial approaches of two or more lanes (from the source's `turn:lanes`
   when present, else from the legs the junction has). The widths are the Granit restyle's real-world table
   (`MARKING_WIDTH_M`, `docs/city-roads-restyle-cs2.md` "Paint at real widths"; `markingWidths.spec.ts` pins them to each other).
   A line quad is mapped onto the solid core of the atlas `line` tile (`MARKING_LINE_CORE`, texels 12 to 55 of 64), because an
   edge-to-edge mapping painted only 69 % of the width (the 16 cm lines read 11 cm). Paint is fresh (`_ROAD.w` 0.04, the restyle's
   `MARKING_AGE`), where a per-edge wear seed used to fade some lines out at 60 m.
10. **Ribbons never fold.** Where a bend is tighter than the strip is wide, the inner side would run backwards and be drawn
    twice at one height. Stations that would fold are dropped (`unfold` in `ribbons.ts`).
11. **Collider.** Surface triangles only (no markings), welded by position, then `MeshoptSimplifier.simplify` with an absolute
    error of 5 cm, doubled until the cell fits 60,000 triangles.
12. **Terrain.** Under finished road surfaces the ground model is cut or filled to the road height; the cut or fill then fades to
    the natural ground over 3 m, or over 1.5 m per metre of cut up to 6 m, so a deep cut gets a gentler bank. Splat roles 1
    (asphalt) and 2 (pavement) are painted under the road and role 3 (bank) on the slope beside it, which `scene create city` paints
    as ground cover instead of bare earth.


### The game's own roads (CS2): plan `roads.baked`

A CS2 capture does not need this generator for its streets. CS2 nodes carry no position (the importer guesses one by tangent intersection and
extends the edges to it), so the junction solver meets edge ends that do not line up and falls back to a convex hull with no sidewalk
(`degenerateJunctions`: 198 of Leonida's 1,873). The capture also carries every composition the game drew; `helix city roads bake-cs2`
([city-roads-restyle-cs2.md](city-roads-restyle-cs2.md)) bakes them, and `scene create city` with plan `roads.baked: <that folder>/roads`
uses those cells, paint and colliders in place of `generateRoads`, with the same terrain conform, far layer and LOD carve fed from their top
surfaces (`src/city/roads/baked.ts`). The report says `roads.source: "cs2-baked"`. Tree placement keeps off the road the scene draws in
either mode (`src/city/vegetation/roadMask.ts`).

### What `scene create city` adds around the cells

`helix scene create city` composes these cells and, from the same road geometry, does three things the cells alone do not
([scene-create.md](scene-create.md)); the CS2 restyle does the same for Granit's baked roads ([city-roads-restyle-cs2.md](city-roads-restyle-cs2.md)):

13. **Far road layer** (`roads.far`, default on; `src/city/roads/far.ts`). The near cells stream by distance, so beyond the stream radius a
    camera (a flight over the city) used to see only the terrain splat's painted streets. The layer is the carriageway primitive of every
    cell (up-facing triangles of `road-asphalt`: no kerb, sidewalk, paint, deck fascia or pier), welded across the cell borders (the 1/60 m
    lattice makes the borders exact), simplified to `roads.farErrorM` (default 0.3 m, under a pixel at 900 m), merged into 2,048 m cells
    and written as one asphalt primitive each, 3 cm under the near road so the near road and its paint win where both are mounted. It is
    one eager group, `roadlod.far`, nodes `roadlod.cell.<x>.<z>`, a few hundred KiB for a 14 km map. The same `buildFarLayer` writes
    the restyle's layer (`src/cs2/restyle/far.ts`).
14. **Terrain carve at every LOD** (`roads.carve`, default on over a DEM). The conform clears a road at the height field's own
    posting. The engine draws that field at sample strides 1, 2, 4 and 8, and the coarse layer is the stride-8 lattice, where a
    cell's chord rises through a road between its corners. `carveRoadCorridors` (`src/cs2/restyle/terrainCarve.ts`) holds the corners of
    every lattice cell a road surface crosses below the surface, coarse to fine, never raising a sample, over the generator's up-facing
    carriageway and pavement tops (decks more than 3 m over the ground and tunnels more than 3 m under it are left out). Tiles, the
    coarse layer and their normal maps are cut from the carved grid, and trees and props stand on it. The create report
    (`terrain.carve`) carries `measureRoadSink`: the share of road vertices under the drawn terrain at each stride, before and after.
15. **Calibrated asphalt** (`materials.asphalt`). A CS2 source gets the Granit-calibrated asphalt albedo in the packaged library.

Measured on the Leonida land source (CS2 import, 14.3 km square, 116 road cells, 4 m terrain; `scene create city --skip-perf`, then `scene validate --perf --tier desktop,mobile`):

| | before (`roads.far` and `roads.carve` off, engine asphalt) | after |
|---|---|---|
| far road layer | none | 41 cells of 2,048 m, 58,175 triangles from 213,747 carriageway triangles, 0.43 MiB, worst simplifier error 0.2999 m |
| road vertices under the drawn terrain, stride 1 (4 m) | 0.17 % | 0.14 % |
| stride 2 (8 m) | 0.48 % | 0.22 % |
| stride 4 (16 m) | 1.75 % | 0.44 % |
| stride 8 (32 m and the coarse layer) | 3.97 % | 0.82 % |
| same, under by 50 cm or more, stride 8 | 2.16 % | 0.64 % |
| samples lowered | | 54,430 of 12.8 M (p99 3.0 m, at most 8.1 m); 8,135 by 1 m or more |
| perf P01-P14, both tiers | pass | pass (P06 draws at the worst cell 17 to 58, mobile limit 150; first playable 4.5 to 5.0 MB) |

Counted: 668,833 road-surface vertices, 1,680 of them more than 3 m under the ground and left out (tunnels and trenches). What stays under at stride 8 is 5,450 vertices: 5,420 at ground level on slopes where the road lies more than 3 m from the lattice corner that would have to be held, and 30 on decks. The 3 m reach is the fine conform's own and the Granit carve's; a longer one buys pits (see `docs/city-roads-restyle-cs2.md`).

## Ramps, bridges, curves, junctions: what works for any OSM import

Fixtures: `src/city/roads/fixtures/gallery` (T, X, Y, 5-way, roundabout, dual carriageway, bridge) and
`src/city/roads/fixtures/interchange` (freeway with off-ramp diverge and on-ramp merge, a ramp viaduct over a street, a trunk
road on a bridge over a street it does not join, a hairpin, a skewed signalised crossing). Both are committed as city-source
folders and checked byte for byte against their builders; `roads.spec.ts` and `quality.spec.ts` assert the properties below on them.

| topic | what the generator does | what OSM does not give it |
| --- | --- | --- |
| Grade separation | Edges join only at shared nodes, never because they come close in plan. A way that crosses another at a different `layer` or `bridge` therefore never forms a junction. A deck is lifted to clear the finished profile of every lower-layer road under it (4.5 m, 5.5 m over a motorway, plus its girder), and when the grade cap stops it the approach chain climbs with it (abutment floors, up to 14 relaxation passes). The report carries `crossingPairs`, `crossingPairsBelow4m`, `crossingPairsBelowTarget`, `abutmentsRaised` and the worst `headroomRemainder` (up to 40 pairs, each with deck, road below, headroom, target, deck length). | `layer` on a non-bridge way (footway `layer=4`, pedestrian plazas `layer=1`) is treated as ground: only `structure: bridge` is lifted. |
| Ramps | The OSM importer flags every `highway=*_link` way `ramp: true` (one 4 m lane, one-way, 2 m shoulder), and `merge` never joins a ramp to the freeway. The generator gives ramps the 7 % grade cap, a 6 m fillet and highway markings, and builds a gore (wedge, edge lines, chevrons, aux lane at grade) where a ramp meets a freeway. A source without the flag (CS2, hand-made) falls back to recognising a ramp by what it is: one-way, highway class, one lane or no wider than 7.5 m. | Lane widths and ramp geometry. OSM ramps are single centrelines starting on the freeway's own centreline, so the wedge is placed where the ramp's edge parts from the freeway's; where it never does (ramp hugging the carriageway) the ordinary junction code runs and a hull fallback is possible. |
| Cuts under decks | A road at grade that a deck cannot clear by climbing (a short flyover in a dense grid, a freeway the DEM does not resolve as a trench) goes into a cut instead: at most 9 m deep, flat for 10 m either side of the crossing and running in and out at about 10 %, steeper than the road's own cap by design (`elevation.trenches`, `maxTrenchM`, `maxTrenchGrade`; `maxGrade` is the steepest of the other edges). Without it every street joining the deck was lifted by the abutment chain: Los Angeles had 762 street edges over 3 m above the ground (50 km, up to 30 m), now 166 (18 km, up to 12 m). | The cut is a road-profile change only: the junction nodes at its ends keep their height. |
| Bridges and viaducts | Straight or vertical-curve deck between abutments with a visible girder, fascia, underside and Jersey barrier (parapet on city decks), a bent-cap pier every 30 m, deck collider in the cell collider. Chains of bridge ways merge into one smooth profile. A highway edge that stands over 2.5 m above ground without a bridge tag is drawn as a deck too. | Abutment embankments. A deck can still stay under its headroom where the approach is pinned by another deck or by the grade cap (see the remainder below). |
| Tunnels | Not drawn, but each mouth where a drawn road meets one is: concrete box, headwall with wings, lintel, back wall. | Tunnel depth and shape. |
| Curves | Stations follow every bend, 3 m on curves, 20 m on straights (6 m on decks), plus vertical-curve samples. A bend tighter than the strip is wide would fold the inner side over itself; stations that would fold are dropped (`unfold`), so the hairpin fixture (13 m centreline radius) has no overlapping triangles. | Radius is only as good as the way's node density. |
| Intersections | T, X, Y, skewed, 5-way (kerb-line intersections and Bezier fillets), signalised with zebras, stop lines and lane arrows, roundabouts with islands, dual-carriageway crossings with per-station half-gap medians. | A roundabout whose ring is not a closed cycle of one-way ways is drawn as ordinary junctions. |

## Measured on the San Francisco OSM source (16 cells)

15,686 source edges, 9,231 rendered (5,522 merged chains; rail, tram and 53 tunnels not drawn as roads), 3,181 junctions
(175 fell back to a hull, 39 of them with a highway-family leg), 437 dual-carriageway edges, 165 bridges, 243 deck edges, 12 gores
(diverges and merges), 28 tunnel portals, 1 roundabout built and 1 skipped. Headroom: 366 crossing pairs of a deck over a lower
road, 10 under 4 m (3 decks: two viaduct spans of the Central Freeway and one ramp over a trunk road), 15 under their 4.5 or
5.5 m target, 68 abutments raised by the propagation.

| per cell | dense cells | worst |
| --- | --- | --- |
| render triangles | about 55,000 | 76,500 (limit 80,000) |
| collider triangles | about 26,000 | 27,900 (limit 60,000) |
| GLB bytes | about 450 KB | 710 KB |

7.0 MB of cell GLBs in total. The whole build costs about 5 s of CPU (the first generator: 8.5 s; the grade relaxation now revisits
only edges whose nodes moved); two builds are byte-identical (`diff -r`). `helix scene create city` on the same source composes these cells, and its perf gate
passes (densest cell 76,672 triangles).

## Known limits (next steps)

- Three decks stay under 4 m of headroom: their abutments are pinned by the grade cap or by a neighbouring deck, so the profile
  cannot climb further (the report lists each pair in `elevation.headroomRemainder`).
- 39 junctions with a highway-family leg still fall back to a hull. 22 are surface trunk roads (Van Ness, Mission and their
  cross streets) where a 4 m-lane trunk is wider than a short side street leaves room for; 17 touch a motorway. Of those, about
  six are ramps that hug the carriageway for more than the gore search reaches (a ramp starting on the freeway's centreline at
  5 to 9 degrees needs over 100 m to part from the edge), so the wedge cannot open and the hull is kept.
- Ramp junction patches overlap the neighbouring ribbon's end at one height in a few places (about 5 m2 in the interchange
  fixture, none in the junction gallery).
- Tunnels draw their portals only. Tunnel depth and shape are not drawn and no road is built between the mouths.
- Grade caps flatten SF's steepest streets (real grades reach 30 %); 3 edges stay over their cap after relaxation.
- A roundabout whose ring is not a closed cycle of one-way edges is drawn as ordinary junctions without an island.
- Turn arrows are placed from `lanes.turn` at signalised arterial junctions; bus and "only" text exist in the atlas contract but
  are not placed yet. The marking atlas the engine ships is a plain texture, so a marking is a flat colour and its sharpness
  depends on the 6 cm lift and the 15 to 20 cm line widths chosen here.
- Cut and fill banks get a grass splat role (role 3) and a shallow bank reach; a steep cut still shows a bank, not a retaining wall.
