# `helix city import osm`

Turns a real place into a `helix.city-source/1` folder: OpenStreetMap (roads, buildings, land use, water, coastline, street
furniture) plus a Copernicus GLO-30 elevation window, normalised into HELIX plan metres. One command, no keys.

```bash
# a few km2: straight from Overpass (south,west,north,east)
helix city import osm --bbox 37.770,-122.430,37.806,-122.3845 --out ./sf-core --region us --cache-dir ./cache

# a metro area: read a Geofabrik/BBBike/osmium extract instead (and say which part of it)
helix city import osm --pbf ./SanFrancisco.osm.pbf --bbox 37.770,-122.430,37.806,-122.3845 --out ./sf-core

helix city import osm --bbox ... --out ./sf-core --no-dem      # offline: flat terrain, no elevations
```

Design: `coordinator/open-world/SCENE-PIPELINE-DESIGN.md` §2 (the format) and §3.4 (this importer). Code: `src/city/import/osm/`
(OSM side) and `src/city/dem/` (elevation). The folder format and its validator are `docs/city-source.md`.

## What you get

```
sf-core/
  city-source.json       roads.json   buildings.ndjson.gz   areas.json   pois.ndjson.gz
  terrain/dem.json + terrain/dem.r16
  import-report.json     what was read, kept, refused and defaulted, with counts and timings
  preview.png            north-up plan (streets, footprints, water, land use) over hillshade, at most 1000 px
  preview-terrain.png    the same over relief shading with the DEM's height range
```

`import-report.json` and the two previews are informational: they are not part of the source's identity and a generator
never reads them. The command prints the same report; refusals are counted, never silent.

## The frame

- Local transverse Mercator on the origin meridian (WGS84, k0 = 1), origin = the box centre snapped to about 1 m
  (`--origin lon,lat` overrides it, so adjacent tiles can share one frame). `x` = east, `z` = -north, `y` = up.
- `boundsXZ` is the box **rounded outward to the 256 m grid** (the size of a terrain tile and a building cell), so a 4 x 4 km
  request writes 4,096 m bounds. The OSM read and the DEM window cover the aligned bounds, not just the request.
- Roads, buildings and POIs lie inside the bounds; land use, water and the coastline may run on past them (up to 2 km) and are
  clipped there. Beyond 8 km from the origin float32 positions lose street precision, so the command refuses (`--allow-wide`
  to override); import tiles with a shared `--origin` instead.
- `fetchedAt` in provenance is the **data's** timestamp (Overpass `timestamp_osm_base`, the PBF header's replication timestamp), not
  the wall clock, so re-importing unchanged data produces byte-identical files.

## Overpass or PBF

Overpass is for small areas (up to about 150 km2; `--allow-large-overpass` lifts that, but the public instances will refuse).
The read is split into small cached queries (roads, buildings, areas, relations, nodes, coastline), each with
retry, back-off and mirror rotation (`--overpass <url...>` to choose endpoints). The public instances throttle by IP and are
slow at busy hours; with `--cache-dir` a re-run costs no requests. If they keep failing, a PBF extract always works.

`--pbf` streams the file in four passes (relations, their nodes, ways, the ways' nodes), keeps full geometry for ways that
cross the box (a road running out of the box still ends at the edge in the right place), and reads coastline ways 2.3 km past
the box so a coast chain closes. A 4 x 4 km box from a city extract takes tens of seconds, most of it writing and rendering the preview.

## What is imported, and what is refused

| Layer | Kept | Refused or defaulted (counted in the report) |
|---|---|---|
| roads | motorway to residential, living street, service, pedestrian, cycleway, footway, rail, tram; class, lanes, width, oneway (`-1` reversed), bridge/tunnel/layer, name, speed, sidewalks | parking aisles, driveways and private service roads (`--keep-service`), mapped sidewalks and crossings (derived from the road's sidewalk widths; `--keep-sidewalks`), construction and other unsupported classes (counted by tag, e.g. `road_class_unsupported:highway=construction`), ways laid exactly over another (`road_duplicate_geometry`), loops with no body |
| graph | split at junctions and control nodes, merged across degree-2 nodes with equal attributes, nodes closer than 0.5 m snapped, ways clipped to the bounds with a node at the cut | `lanes_defaulted_by_class`, `width_from_class_table`, `sidewalk_defaulted_by_class` |
| buildings | footprints with `height`, `building:levels`, `min_height`, roof shape/height/direction/colour, use, facade colour/material, `building:part` merged into their building, multipolygons with courtyards | under 6 m2, `building=no`, proposed, underground, outside the bounds, **crossing the bounds** (`building_crosses_bounds`: a generator cell owns its buildings whole), overlaps (the smaller footprint is dropped when half of it lies under another), self-intersections repaired by union, holes that overlap or touch repaired or dropped |
| areas | park, grass, forest, scrub, farmland, residential, commercial, industrial, parking, plaza, pitch, beach, cemetery, construction, rail | unsupported `landuse`/`leisure`/`natural` values are counted by tag |
| water | lakes, ponds, rivers (polygon) and river/canal lines with a width, the sea derived from the coastline | culverts and underground waterways, drains and ditches |
| coastline | polygonised into land rings (land on the left of the way), sea = bounds minus land | an unclosable chain is counted |
| POIs | street lamps, signals, stops, hydrants, trees, benches, bollards, shops, bus stops, ... | crossings are a road-node attribute, not points |

Buildings without a height are **not** given one: `heightM` and `levels` stay absent and the generator decides, so the report
can say how many were mapped. Defaults for region, drive side and style are written as `unspecified`/`right`/`generic` and
listed under `assumed` in the report until you pass `--region`, `--drive-side` and `--style`.

## Elevation

Copernicus GLO-30 (30 m, EGM2008 orthometric heights) is read straight from the public AWS bucket by HTTP range, so only
the window's blocks are fetched. It is a **surface** model, not bare earth: it records building roofs, tree canopy and, in
dense cities, pits where tall buildings shadow the radar. The importer therefore **despikes** the window (a 7 x 7 median;
clusters of up to 40 samples more than 8 m below their surroundings are filled and counted as `demPitSamplesFilled`) before
anything uses it. Expect street-level relief with building-sized noise removed, not centimetre terrain.

- `terrain/dem.r16` is the window as little-endian uint16, row 0 north, encoded over `heightRangeM = [0, span]` metres above
  the manifest's `originAltitudeM`. `originAltitudeM` is `floor(lowest ground)`, so Y = 0 is at or below the lowest street, and
  a coastal city's sea level is close to Y = 0 but not exactly.
- Every road node gets a `y` from the DEM. **Bridge and tunnel decks are a straight line** between the ground at the two ends of
  the whole structure (per-point `ys` on those edges), never the valley or hill under them. The sea sits at altitude 0 (scene
  Y `-originAltitudeM`, floored at 0); a lake, pond or river polygon sits at the lowest DEM height on its outline.
- `--dem-resolution <m>` resamples (5 to 500 m); the default is the dataset's 30 m posting.
- `--no-dem` writes `{"kind":"flat","y":0}` and no `y` values; it needs no network apart from Overpass.

## Checking the result

`helix city source validate <dir>` (from `docs/city-source.md`) must report no errors; `helix city source inspect <dir>` gives
counts and lengths. Look at `preview.png`: streets should follow the footprints' blocks, water should sit where water is, and
`preview-terrain.png` should show the real relief registered to the same frame.

## Limits to know

- One import is one frame: very large cities are imported as several tiles that share `--origin`.
- OSM tags are what mappers wrote. Many buildings have no height; some roads have no lanes; the report counts these so you
  can decide what the generator should assume.
- The importer reads, it never edits: hand fixes belong in the city source's `overrides.json`.
