maps: add a roads layer with lanes and speed, retiring maxspeed
- Commit
61a48a4db378fdd090a62e128cf8e3b8930ec217- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-25 03:00 UTC (3 months ago)
- Parents
8ab9459
Diff
maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.ktindex 5658fce9f7..522a8cbb86 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MapPage.kt@@ -178,7 +178,8 @@ fun MapPage( NavigationCameraFollow(camera, chrome, navProgress, isNavigating) - // Poll the posted limit under the puck. Inert until the maxspeed tileset is hosted.+ // Poll the posted limit under the puck, off the `roads` overlay's probe layer.+ // Null when there is no road there, or none of its tags is a speed limit. LaunchedEffect(navProgress) { val progress = navProgress val projection = camera.projection
maps/src/main/java/com/vayunmathur/maps/ui/MaxspeedOverlay.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MaxspeedOverlay.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MaxspeedOverlay.ktdeleted file mode 100644index fc6b6ccf00..0000000000--- a/maps/src/main/java/com/vayunmathur/maps/ui/MaxspeedOverlay.kt+++ /dev/null@@ -1,73 +0,0 @@-package com.vayunmathur.maps.ui--import androidx.compose.runtime.Composable-import androidx.compose.ui.unit.dp-import com.vayunmathur.maps.data.PostedLimit-import com.vayunmathur.maps.data.parseMaxspeed-import kotlinx.serialization.json.JsonPrimitive-import org.maplibre.compose.camera.CameraProjection-import org.maplibre.compose.expressions.dsl.const-import org.maplibre.compose.layers.LineLayer-import org.maplibre.compose.sources.rememberVectorSource-import org.maplibre.compose.util.MaplibreComposable-import org.maplibre.spatialk.geojson.Position--/**- * Posted-speed-limit data source (Decision D4), ported from Vela's maxspeed- * PMTiles overlay (`VelaMapView.kt:967-1003` + `OsmMaxspeed.kt`).- *- * A vector overlay whose features carry the OSM `maxspeed` tag is mounted as an- * invisible probe layer; the driving UI queries it with `queryRenderedFeatures`- * under the puck (see [queryPostedLimit]) and shows the parsed value on the- * speed widget.- *- * The maxspeed data is baked into our overlay PMTiles archive (P13), so the probe- * reads [MaxspeedSource.PMTILES_URL], which delegates to the single- * [com.vayunmathur.maps.util.MapTileCache.OVERLAY_PMTILES_URL] source of truth- * (source-layer [SOURCE_LAYER], feature property [PROP]). Switching to the global- * overlay file is therefore a one-line change in [MapTileCache].- */-object MaxspeedSource {- /** Baked into the overlay PMTiles — read from the shared overlay URL. */- val PMTILES_URL: String get() = com.vayunmathur.maps.util.MapTileCache.OVERLAY_PMTILES_URL- const val LAYER_ID: String = "maxspeed-probe"- const val SOURCE_LAYER: String = "maxspeed"- const val PROP: String = "maxspeed"-- val enabled: Boolean get() = PMTILES_URL.isNotBlank()-}--/**- * Mount the maxspeed probe overlay. No-op (renders nothing) while the tileset- * is unhosted, so it is always safe to include in the layer tree.- */-@Composable-@MaplibreComposable-fun MaxspeedLayer() {- if (!MaxspeedSource.enabled) return- val source = rememberVectorSource(MaxspeedSource.PMTILES_URL)- // Invisible, but rendered so queryRenderedFeatures can hit it under the puck.- LineLayer(- MaxspeedSource.LAYER_ID,- source,- sourceLayer = MaxspeedSource.SOURCE_LAYER,- opacity = const(0f),- width = const(2.dp),- )-}--/**- * Query the posted speed limit at [puck] (the snapped nav position) by- * projecting it to screen and hit-testing the maxspeed probe layer. Returns- * `null` when the overlay is unhosted, off-network, or the road has no- * concrete `maxspeed` tag.- */-fun queryPostedLimit(projection: CameraProjection, puck: Position): PostedLimit? {- if (!MaxspeedSource.enabled) return null- val offset = projection.screenLocationFromPosition(puck)- val features = projection.queryRenderedFeatures(offset, setOf(MaxspeedSource.LAYER_ID))- val raw = features.firstNotNullOfOrNull { f ->- (f.properties?.get(MaxspeedSource.PROP) as? JsonPrimitive)?.content- }- return parseMaxspeed(raw)-}
maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt b/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.ktindex 9cb4f2b28d..d6b7ea2c1f 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/MyMapLayers.kt@@ -133,6 +133,14 @@ fun MyMapLayers( // the overlays. SatelliteLayer(satelliteEnabled) + // Our own road rendering, from the baked `roads` source-layer. Drawn FIRST+ // among the vector overlays so every pin, line and highlight below sits on+ // top of the roads. Above z11 this is the only thing drawing a road: the base+ // style's own road surfaces are capped there (see StylePatcher), because ours+ // carries the lanes, width and speed theirs has no attributes for. It also+ // holds the probe the posted-limit query hit-tests during navigation.+ RoadsLayer(overlaySource, tokens)+ // P21: live Google traffic congestion overlay (keyless raster tiles from // Google's mapstiles hosts), replacing the removed OfflineRouter loopback // vector-traffic tile server. Drawn above the basemap but below the POI@@ -185,10 +193,6 @@ fun MyMapLayers( TransitStopsLayer(overlaySource) } - // Posted-speed-limit probe overlay (Decision D4). Invisible; queried- // under the puck during navigation. No-op until the tileset is hosted.- MaxspeedLayer()- // Search-result pins (Vela MARKERS_LAYER analog) — drawn above the // ambient POI overlay so a query's hits stand out; tap re-selects. SearchResultLayer(searchResults)
maps/src/main/java/com/vayunmathur/maps/ui/RoadsLayer.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/RoadsLayer.kt b/maps/src/main/java/com/vayunmathur/maps/ui/RoadsLayer.ktnew file mode 100644index 0000000000..df808e6c3b--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/ui/RoadsLayer.kt@@ -0,0 +1,217 @@+package com.vayunmathur.maps.ui++import androidx.compose.runtime.Composable+import androidx.compose.ui.unit.dp+import com.vayunmathur.maps.data.Feature1+import com.vayunmathur.maps.data.PostedLimit+import com.vayunmathur.maps.data.parseMaxspeed+import com.vayunmathur.maps.ui.theme.MapTokens+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.intOrNull+import org.maplibre.compose.camera.CameraProjection+import org.maplibre.compose.expressions.ast.Expression+import org.maplibre.compose.expressions.dsl.case+import org.maplibre.compose.expressions.dsl.const+import org.maplibre.compose.expressions.dsl.feature+import org.maplibre.compose.expressions.dsl.gte+import org.maplibre.compose.expressions.dsl.interpolate+import org.maplibre.compose.expressions.dsl.linear+import org.maplibre.compose.expressions.dsl.switch+import org.maplibre.compose.expressions.dsl.zoom+import org.maplibre.compose.expressions.value.DpValue+import org.maplibre.compose.expressions.value.IntValue+import org.maplibre.compose.expressions.value.LineCap+import org.maplibre.compose.expressions.value.LineJoin+import org.maplibre.compose.expressions.value.NumberValue+import org.maplibre.compose.layers.Anchor+import org.maplibre.compose.layers.LineLayer+import org.maplibre.compose.sources.VectorSource+import org.maplibre.compose.util.MaplibreComposable+import org.maplibre.spatialk.geojson.Position++/** The drawn road surface. */+const val ROADS_LAYER_ID = "roads-lines"+private const val ROADS_CASING_LAYER_ID = "roads-casing"+private const val ROADS_PROBE_LAYER_ID = "roads-probe"++/**+ * The base style layer our road surfaces are anchored below.+ *+ * Composition order puts a composable layer above every layer in the style, and the base's road+ * labels, shields and oneway arrows are near the end of it — deliberately left uncapped by+ * `StylePatcher`, since the `roads` overlay carries no `name`. An opaque road surface drawn above+ * them would paint over the labels it exists to keep. `roads_labels_minor` is the first label+ * layer after the base's road surfaces, so anchoring below its z0-7 variant puts us above every+ * base road and below every base label. `StylePatcherTest` pins that this id survives the patch.+ */+private const val ROADS_ANCHOR_BELOW = "roads_labels_minor_base"++/**+ * Our baked road layer, replacing the separate `maxspeed` layer.+ *+ * `maxspeed` existed to answer one question — what is the limit under the puck — and carried a+ * copy of every road's geometry to hang the answer on. This layer carries that geometry once and+ * also has what it takes to draw the road: `class`, `lanes`, `turn_lanes_*`, `width`, `oneway`+ * and the `bridge`/`tunnel`/`layer` flags. See `scripts/maps/build_roads_layer.sh` for the full+ * schema.+ */+object RoadsSource {+ const val SOURCE_LAYER: String = "roads"++ /** The OSM tag verbatim. `maxspeed_kmh` beside it is the parsed number, when there is one. */+ const val PROP_MAXSPEED: String = "maxspeed"++ /** `tags::get_hw_id`'s road type, 1-15. Also the routing graph's own numbering. */+ const val PROP_CLASS: String = "class"+}++/**+ * `class` values, in the four buckets a width and a fill can tell apart. The numbers are+ * `osm_ingest::tags::get_hw_id`'s, which the routing graph uses for the same roads. A `*_link`+ * ramp carries its parent's class, so it is drawn as the road it joins.+ */+private val MOTORWAY_CLASSES = listOf(1, 2)+private val MAJOR_CLASSES = listOf(3, 4, 5)+private val MINOR_CLASSES = listOf(6, 7, 8, 9, 10)++/**+ * The zoom each road class starts drawing at, and therefore the zoom the base style stops drawing+ * it at.+ *+ * Two values, not fifteen, and they are the ones `StylePatcher`'s `BASE_ROADS_HANDOVER_ZOOM` uses:+ * the base groups its road layers into the same two families, so a third threshold here would+ * open a zoom range where neither layer draws that class.+ *+ * The staggering itself is the per-feature zoom gating the tiler cannot do — it drops features by+ * density, blind to class, so at z11 a long suburban collector can outrank a motorway stretch.+ * Holding the minor streets back is what keeps z11-12 a picture of the through network. Same+ * pattern as [MaPoisLayer] and [TransitStopsLayer].+ */+private const val THROUGH_MIN_ZOOM = 11+private const val MINOR_MIN_ZOOM = 13++/** Our layer's floor: no `roads` tiles exist below this. */+private const val ROADS_MIN_ZOOM = THROUGH_MIN_ZOOM++/**+ * Draw the `roads` source-layer: a casing, the surface on top of it, and an invisible probe the+ * posted-limit query hit-tests. Takes the shared overlay [VectorSource] the admin, POI and+ * transit overlays also read, since they are all layers of the same archive.+ *+ * The two drawn layers are anchored below the base's road labels ([ROADS_ANCHOR_BELOW]); the+ * probe is not drawn at all, so its position does not matter.+ */+@Composable+@MaplibreComposable+fun RoadsLayer(source: VectorSource, tokens: MapTokens) {+ // Per-class min-zoom, compared against `zoom()` (a NumberValue), so the Int threshold is+ // cast to the same value type for `gte` to resolve to the numeric overload.+ val minZoomForClass = switch(+ feature[RoadsSource.PROP_CLASS].cast<IntValue>(),+ *(MOTORWAY_CLASSES + MAJOR_CLASSES)+ .map { case(it, const(THROUGH_MIN_ZOOM)) }.toTypedArray(),+ fallback = const(MINOR_MIN_ZOOM),+ )+ val drawn = zoom() gte minZoomForClass.cast<NumberValue<Number>>()++ Anchor.Below(ROADS_ANCHOR_BELOW) {+ LineLayer(+ ROADS_CASING_LAYER_ID,+ source,+ sourceLayer = RoadsSource.SOURCE_LAYER,+ minZoom = ROADS_MIN_ZOOM.toFloat(),+ filter = drawn,+ color = const(tokens.roads.casing),+ width = roadWidth(casing = true),+ cap = const(LineCap.Round),+ join = const(LineJoin.Round),+ )++ LineLayer(+ ROADS_LAYER_ID,+ source,+ sourceLayer = RoadsSource.SOURCE_LAYER,+ minZoom = ROADS_MIN_ZOOM.toFloat(),+ filter = drawn,+ color = switch(+ feature[RoadsSource.PROP_CLASS].cast<IntValue>(),+ *MOTORWAY_CLASSES.map { case(it, const(tokens.roads.motorway)) }.toTypedArray(),+ *MAJOR_CLASSES.map { case(it, const(tokens.roads.major)) }.toTypedArray(),+ *MINOR_CLASSES.map { case(it, const(tokens.roads.minor)) }.toTypedArray(),+ fallback = const(tokens.roads.path),+ ),+ width = roadWidth(casing = false),+ cap = const(LineCap.Round),+ join = const(LineJoin.Round),+ )+ }++ // Deliberately NOT filtered by [drawn], and deliberately a fixed width: the posted limit+ // under the puck is a fact about the road the user is on, whether or not the style has+ // decided to draw that road at this zoom, and it must not change with the render width.+ LineLayer(+ ROADS_PROBE_LAYER_ID,+ source,+ sourceLayer = RoadsSource.SOURCE_LAYER,+ opacity = const(0f),+ width = const(2.dp),+ )+}++/**+ * Road width, ramped over zoom and stepped by class.+ *+ * MapLibre allows an `interpolate` over `zoom()` whose outputs are themselves property+ * expressions, which is what lets one layer hold the whole ramp for all four buckets instead of+ * four layers holding a quarter of it each. The casing is the same ramp, wider, so a road and+ * its outline cannot drift apart.+ */+private fun roadWidth(casing: Boolean): Expression<DpValue> {+ val extra = if (casing) 1.4f else 0f+ fun byClass(motorway: Float, major: Float, minor: Float, path: Float): Expression<DpValue> =+ switch(+ feature[RoadsSource.PROP_CLASS].cast<IntValue>(),+ *MOTORWAY_CLASSES.map { case(it, const((motorway + extra).dp)) }.toTypedArray(),+ *MAJOR_CLASSES.map { case(it, const((major + extra).dp)) }.toTypedArray(),+ *MINOR_CLASSES.map { case(it, const((minor + extra).dp)) }.toTypedArray(),+ // Paths and tracks get no casing: an outline would be wider than the path.+ fallback = const(path.dp),+ )+ return interpolate(+ linear(), zoom(),+ 11 to byClass(1.2f, 0.9f, 0.5f, 0.4f),+ 14 to byClass(3f, 2.2f, 1.4f, 0.8f),+ 16 to byClass(6f, 4.5f, 3f, 1.2f),+ 18 to byClass(12f, 9f, 6.5f, 2f),+ )+}++/**+ * Query the posted speed limit at [puck] (the snapped nav position) by projecting it to screen+ * and hit-testing the roads probe layer. Returns `null` when there is no road there, or no road+ * there carries a limit worth showing.+ *+ * Reads the RAW `maxspeed` string, not `maxspeed_kmh`. The number is the layer's styling+ * attribute and is absent for every value that is not a plain speed; the string is the only+ * thing that still carries `DE:urban` (which is 50 km/h) and the only record of whether the+ * limit was authored in mph, which decides the unit the badge renders in. [parseMaxspeed] owns+ * both of those judgements.+ */+fun queryPostedLimit(projection: CameraProjection, puck: Position): PostedLimit? {+ val offset = projection.screenLocationFromPosition(puck)+ val features = projection.queryRenderedFeatures(offset, setOf(ROADS_PROBE_LAYER_ID))+ // The MOST MAJOR road wins, not the first hit. `roads` is every road, where the layer it+ // replaced held only ways with a posted limit — so a service road or a cycleway running+ // alongside the carriageway is now also under the puck, and its 10 km/h is not the limit+ // the driver is subject to.+ return features+ .filter { it.maxspeed() != null }+ .minByOrNull { it.roadClass() ?: Int.MAX_VALUE }+ ?.let { parseMaxspeed(it.maxspeed()) }+}++private fun Feature1.maxspeed(): String? =+ (properties?.get(RoadsSource.PROP_MAXSPEED) as? JsonPrimitive)?.content?.ifBlank { null }++private fun Feature1.roadClass(): Int? =+ (properties?.get(RoadsSource.PROP_CLASS) as? JsonPrimitive)?.intOrNull
maps/src/main/java/com/vayunmathur/maps/ui/map/style/StylePatcher.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/map/style/StylePatcher.kt b/maps/src/main/java/com/vayunmathur/maps/ui/map/style/StylePatcher.ktindex 26646a0962..cfc8daa0df 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/map/style/StylePatcher.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/map/style/StylePatcher.kt@@ -5,6 +5,7 @@ import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.buildJsonArray import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.intOrNull import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive@@ -21,6 +22,25 @@ import kotlinx.serialization.json.putJsonObject */ private val SUPPRESSED_LAYERS = setOf("pois") +/**+ * The zoom at which the base style stops drawing each road family and our own `roads` overlay+ * takes over. Must match `RoadsLayer`'s per-class table.+ *+ * A cap rather than an outright suppression, because the two layers cover different ranges: the+ * baked `roads` archive starts at z11 (a planet-wide all-classes roads layer below that is not+ * something the tiler can build -- see scripts/maps/README.md), so lower down the base is the+ * only thing that has roads at all. MapLibre renders a layer for `minzoom <= z < maxzoom`, so+ * each handover is exact and nothing draws twice.+ *+ * Two zooms, not one, because `RoadsLayer` holds the minor streets back: capping the base's+ * minor layers at the through-network zoom would leave z11-12 with nobody drawing a residential+ * street.+ */+private val BASE_ROADS_HANDOVER_ZOOM = mapOf(+ BasemapPalette.RoadFamily.Through to 11,+ BasemapPalette.RoadFamily.Minor to 13,+)+ /** * Marks a style as already patched. *@@ -40,6 +60,10 @@ private const val PATCHED_MARKER = "ma:patched" * colour keys are swapped for [BasemapPalette] values, so we do not carry a second copy of a * 3544-line style file. *+ * The base's road surfaces are additionally capped at their family's handover zoom, because+ * above it `RoadsLayer` draws them from our own `roads` overlay instead. See+ * [BASE_ROADS_HANDOVER_ZOOM].+ * * Neither source declares a `maxzoom`. It used to: the merged v5 archive unioned its inputs' * zoom ranges, so it advertised the overlays' z16 while its base tiles stopped at z15, and base * layers vanished at max zoom. The overlays now live in their own archive, so the base@@ -86,6 +110,18 @@ fun patchStyleForHybrid( // _base/_hybrid variants. if (id in SUPPRESSED_LAYERS) return@forEach + // Above its family's handover zoom the roads come from our own `roads`+ // overlay, which carries lanes, width and speed the base layer has no+ // attributes for. Capping the base copy is what stops every street being+ // drawn twice.+ val roadHandoverMaxZoom = BasemapPalette.roadSurfaceFamilies[id]+ ?.let { family -> BASE_ROADS_HANDOVER_ZOOM.getValue(family) }+ ?.let { handover ->+ // Never RAISE an existing cap: a layer the style already stops earlier+ // was meant to stop there.+ minOf(layer["maxzoom"]?.jsonPrimitive?.intOrNull ?: handover, handover)+ }+ // Dark palette (P14): recolor the base Protomaps paint at runtime so // we don't duplicate the 3544-line style.json. Only colour keys are // swapped; width/opacity/dasharray expressions are preserved.@@ -112,6 +148,7 @@ fun patchStyleForHybrid( put("id", "${id}_hybrid") put("source", "protomaps_hybrid") put("minzoom", 7)+ if (roadHandoverMaxZoom != null) put("maxzoom", roadHandoverMaxZoom) }) } }
maps/src/main/java/com/vayunmathur/maps/ui/theme/BasemapPalette.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/theme/BasemapPalette.kt b/maps/src/main/java/com/vayunmathur/maps/ui/theme/BasemapPalette.ktindex 01c9b2e1ef..11c8a2d3ff 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/theme/BasemapPalette.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/theme/BasemapPalette.kt@@ -208,6 +208,70 @@ object BasemapPalette { /** Layer ids the palette knows about. Used by the test that keeps it in step with the asset. */ val knownLayerIds: Set<String> get() = fillRoles.keys + /** The [Fill] roles that are a road surface or the casing under one. */+ private val ROAD_SURFACE_FILLS =+ setOf(Fill.RoadCasing, Fill.RoadTunnel, Fill.RoadMajor, Fill.RoadMinor)++ /**+ * Which half of the road network a base road layer draws.+ *+ * `StylePatcher` stops each base road layer at the zoom our own `roads` overlay starts+ * drawing the same roads, and `RoadsLayer` does not start every class at once — the through+ * network comes in at the handover zoom and minor streets later, because drawing every+ * service road and footway in a metro at z11 is what the staggering exists to avoid. Two+ * families is exactly what the base style can express, since it groups its road layers the+ * same way, and it is what keeps the two halves from leaving a zoom where NEITHER draws a+ * road.+ */+ enum class RoadFamily {+ /** motorway, trunk, primary, secondary, tertiary, and their `*_link` ramps. */+ Through,++ /** unclassified, residential, service, living_street, pedestrian, tracks and paths. */+ Minor,+ }++ private val roadFamilies: Map<String, RoadFamily> = buildMap {+ for (id in listOf(+ "roads_highway", "roads_major", "roads_link",+ "roads_bridges_highway", "roads_bridges_major", "roads_bridges_link",+ "roads_tunnels_highway", "roads_tunnels_major", "roads_tunnels_link",+ "roads_highway_casing_early", "roads_highway_casing_late",+ "roads_major_casing_early", "roads_major_casing_late",+ "roads_link_casing",+ "roads_bridges_highway_casing", "roads_bridges_major_casing",+ "roads_bridges_link_casing",+ "roads_tunnels_highway_casing", "roads_tunnels_major_casing",+ "roads_tunnels_link_casing",+ )) put(id, RoadFamily.Through)++ for (id in listOf(+ "roads_minor", "roads_minor_service", "roads_other",+ "roads_bridges_minor", "roads_bridges_other",+ "roads_tunnels_minor", "roads_tunnels_other",+ "roads_minor_casing", "roads_minor_service_casing",+ "roads_bridges_minor_casing", "roads_bridges_other_casing",+ "roads_tunnels_minor_casing", "roads_tunnels_other_casing",+ )) put(id, RoadFamily.Minor)+ }++ /**+ * Every base style layer that draws a road surface or its casing, and which family it draws.+ *+ * The membership is derived from [fillRoles] rather than listed again, because a second copy+ * of thirty-odd ids is a second copy to forget: `StylePatcher` uses this to stop the base+ * drawing roads above the zoom where our own `roads` overlay takes over, and a layer missing+ * from the set would draw underneath ours forever with nothing to indicate it. A test pins+ * that every derived id has a family.+ *+ * Surfaces and casings only. Road LABELS, shields, oneway arrows and address points stay+ * with the base at every zoom — the `roads` overlay carries no `name`, so suppressing them+ * would leave an unlabelled city. `RoadsLayer` anchors itself below them for the same reason.+ */+ val roadSurfaceFamilies: Map<String, RoadFamily> get() =+ fillRoles.filterValues { it in ROAD_SURFACE_FILLS }+ .mapValues { (id, _) -> roadFamilies[id] ?: RoadFamily.Through }+ /** * Which [Fill] a style layer id denotes. *
maps/src/main/java/com/vayunmathur/maps/ui/theme/MapTokens.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/ui/theme/MapTokens.kt b/maps/src/main/java/com/vayunmathur/maps/ui/theme/MapTokens.ktindex 23dc23dd16..784f0175ce 100644--- a/maps/src/main/java/com/vayunmathur/maps/ui/theme/MapTokens.kt+++ b/maps/src/main/java/com/vayunmathur/maps/ui/theme/MapTokens.kt@@ -24,12 +24,35 @@ data class MapTokens( val traffic: TrafficColors, val transitMode: TransitModeColors, val speedSign: SpeedSignColors,+ val roads: RoadColors, /** Walking and cycling routes, which carry no congestion data to colour by. */ val routeInert: Color, /** A transit line that reported no colour of its own. */ val routeTransitFallback: Color, ) +/**+ * Road surfaces, for the roads we draw ourselves from the baked `roads` layer.+ *+ * Unlike everything else here these are not a convention being preserved -- they are basemap+ * cartography, and they exist because above the handover zoom the base style's own road layers+ * are suppressed (see `StylePatcher`) and there is nothing else drawing a road. The dark values+ * come from [BasemapPalette] rather than being chosen again, so a road looks the same whether+ * the base drew it below the handover or we drew it above.+ *+ * Four buckets, not fifteen classes: motorway/trunk, the primary-to-tertiary network, the minor+ * streets, and unpaved or foot-only ways. That is the granularity a width and a fill can+ * actually distinguish at the zooms this layer covers.+ */+@Immutable+data class RoadColors(+ val casing: Color,+ val motorway: Color,+ val major: Color,+ val minor: Color,+ val path: Color,+)+ /** * The driving-route congestion ramp. *@@ -97,6 +120,15 @@ private val LightMapTokens = MapTokens( train = Color(0xFF455A64), ), speedSign = SpeedSign,+ // A light basemap draws its roads as white ribbons on a grey casing, with the motorway+ // network warmed so it reads as the through route at a glance.+ roads = RoadColors(+ casing = Color(0xFFD5D7DB),+ motorway = Color(0xFFFFCE8A),+ major = Color(0xFFFFFFFF),+ minor = Color(0xFFFFFFFF),+ path = Color(0xFFCFC8BE),+ ), routeInert = Color(0xFF1710F1), routeTransitFallback = Color(0xFFFF0000), )@@ -125,6 +157,16 @@ private val DarkMapTokens = MapTokens( ), // Unchanged: a road sign does not have a dark variant. speedSign = SpeedSign,+ roads = RoadColors(+ casing = BasemapPalette.fill(BasemapPalette.Fill.RoadCasing),+ // One step lighter than RoadMajor, which is the only distinction the dark palette has+ // room for: the motorway must separate from the primary network without becoming a+ // label-bright line across the whole viewport.+ motorway = Color(0xFF5A6068),+ major = BasemapPalette.fill(BasemapPalette.Fill.RoadMajor),+ minor = BasemapPalette.fill(BasemapPalette.Fill.RoadMinor),+ path = Color(0xFF3E434B),+ ), routeInert = Color(0xFF7C8CFF), routeTransitFallback = Color(0xFFFF6E6E), )
maps/src/main/java/com/vayunmathur/maps/util/MapTileCache.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/MapTileCache.kt b/maps/src/main/java/com/vayunmathur/maps/util/MapTileCache.ktindex e3d851fc77..a80c788ca2 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/MapTileCache.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/MapTileCache.kt@@ -67,12 +67,13 @@ object MapTileCache { "pmtiles://https://data.vayunmathur.com/v4.pmtiles" /**- * Our overlay archive: `safety`, `maxspeed`, `transit_lines`, `ma_pois`,+ * Our overlay archive: `safety`, `roads`, `transit_lines`, `ma_pois`, * `transit_stops` and the three `admin_*` levels, with no base layers. *- * Read by the maxspeed probe ([com.vayunmathur.maps.ui.MaxspeedSource]), the- * safety overlay ([com.vayunmathur.maps.ui.SafetyLayersSource]), the ambient POI- * layer, the transit line/stop overlays and the admin search-highlight.+ * Read by the road overlay and its posted-limit probe+ * ([com.vayunmathur.maps.ui.RoadsSource]), the safety overlay+ * ([com.vayunmathur.maps.ui.SafetyLayersSource]), the ambient POI layer, the+ * transit line/stop overlays and the admin search-highlight. * * Planet-wide: 36.8 M tiles over z0-16, built by * `build_v5_pmtiles.sh --no-base` and streamed by range request like the base.
maps/src/test/java/com/vayunmathur/maps/ui/map/style/StylePatcherTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/map/style/StylePatcherTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/map/style/StylePatcherTest.ktindex cb98be1626..083e90b07b 100644--- a/maps/src/test/java/com/vayunmathur/maps/ui/map/style/StylePatcherTest.kt+++ b/maps/src/test/java/com/vayunmathur/maps/ui/map/style/StylePatcherTest.kt@@ -7,6 +7,7 @@ import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive+import java.io.File import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull@@ -126,6 +127,71 @@ class StylePatcherTest { assertTrue(ids.none { it.startsWith("pois") }, "pois survived: $ids") } + @Test+ fun `base road surfaces stop where our own roads layer takes over`() {+ val root = patch()+ // The hybrid copy runs z7 up to its family's handover, and no further: above it+ // RoadsLayer draws the same roads from the baked `roads` overlay, and both+ // drawing would double every street. roads_highway is the through network.+ val hybrid = layer(root, "roads_highway_hybrid")!!+ assertEquals(7, hybrid["minzoom"]!!.jsonPrimitive.content.toInt())+ assertEquals(11, hybrid["maxzoom"]!!.jsonPrimitive.content.toInt())+ // The base copy already stops at 7, so it needs no cap of its own.+ assertEquals(7, layer(root, "roads_highway_base")!!["maxzoom"]!!.jsonPrimitive.content.toInt())+ }++ /**+ * The minor family is held back in `RoadsLayer` until z13, so capping it at the through+ * network's z11 would leave z11-12 with nobody drawing a residential street.+ */+ @Test+ fun `minor roads are capped later than the through network`() {+ val minorStyle = style.replace(+ """{ "id": "roads_highway", "type": "line",""",+ """{ "id": "roads_minor", "type": "line",""",+ )+ val hybrid = layer(patch(input = minorStyle), "roads_minor_hybrid")!!+ assertEquals(13, hybrid["maxzoom"]!!.jsonPrimitive.content.toInt())+ }++ @Test+ fun `only road surfaces are capped, and a lower cap of their own is respected`() {+ // Labels, arrows and everything that is not a road surface keep every zoom:+ // the `roads` overlay carries no `name`, so capping them would leave an+ // unlabelled city.+ for (id in listOf("water_hybrid", "places_locality_hybrid", "roads_oneway_hybrid")) {+ assertNull(layer(patch(), id)!!["maxzoom"], "$id must not be capped")+ }++ // A road layer the style already stops earlier than the handover must not be+ // raised to it — that would newly show a layer the style meant to hide.+ val capped = style.replace(+ """{ "id": "roads_highway", "type": "line",""",+ """{ "id": "roads_highway", "type": "line", "maxzoom": 9,""",+ )+ val hybrid = layer(patch(input = capped), "roads_highway_hybrid")!!+ assertEquals(9, hybrid["maxzoom"]!!.jsonPrimitive.content.toInt())+ }++ /**+ * `RoadsLayer` anchors its opaque road surfaces below a specific patched layer id so the+ * base's road labels stay on top. That id is a string, so nothing but a test connects it to+ * the style the patcher actually produces — and if it stops existing, the anchor has nothing+ * to attach to.+ */+ @Test+ fun `the roads anchor target survives the patch of the real style`() {+ val styleFile = File("src/main/assets/style.json")+ assertTrue(styleFile.isFile, "style.json not found at ${styleFile.absolutePath}")+ val patched = json.parseToJsonElement(+ patchStyleForHybrid(styleFile.readText(), "pmtiles://base", "pmtiles://hybrid", false)+ ).jsonObject+ assertTrue(+ "roads_labels_minor_base" in layerIds(patched),+ "RoadsLayer's anchor target is not in the patched style",+ )+ }+ @Test fun `light mode leaves paint untouched`() { val water = layer(patch(dark = false), "water_base")!!["paint"]!!.jsonObject
maps/src/test/java/com/vayunmathur/maps/ui/theme/BasemapPaletteTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/ui/theme/BasemapPaletteTest.kt b/maps/src/test/java/com/vayunmathur/maps/ui/theme/BasemapPaletteTest.ktindex 8943a35d0c..7acb5308b5 100644--- a/maps/src/test/java/com/vayunmathur/maps/ui/theme/BasemapPaletteTest.kt+++ b/maps/src/test/java/com/vayunmathur/maps/ui/theme/BasemapPaletteTest.kt@@ -129,6 +129,70 @@ class BasemapPaletteTest { assertEquals(BasemapPalette.Label.Other, BasemapPalette.labelRole("roads_oneway")) } + /**+ * The set `StylePatcher` caps at the roads handover zoom.+ *+ * Derived from `fillRoles` rather than listed, so what needs asserting is the boundary: every+ * road surface and casing is in, and nothing that draws a road's *label* is — the `roads`+ * overlay carries no `name`, so capping a label layer would leave an unlabelled city.+ */+ @Test+ fun `road surface ids cover every surface and casing and no label`() {+ val families = BasemapPalette.roadSurfaceFamilies+ for (id in listOf(+ "roads_highway", "roads_major", "roads_minor", "roads_minor_service", "roads_other",+ "roads_link", "roads_highway_casing_early", "roads_major_casing_late",+ "roads_tunnels_highway", "roads_tunnels_link_casing",+ "roads_bridges_major", "roads_bridges_minor_casing",+ )) {+ assertTrue(id in families, "'$id' draws a road surface but is not in the handover set")+ }+ // Labels, shields, arrows, rail, piers and runways are not road surfaces.+ for (id in listOf(+ "roads_labels_major", "roads_labels_minor", "roads_shields", "roads_oneway",+ "address_label", "roads_rail", "roads_pier", "roads_runway", "roads_taxiway",+ "water", "buildings",+ )) {+ assertTrue(id !in families, "'$id' is not a road surface but would be capped")+ }+ // And every member really does resolve to a road-surface role.+ for (id in families.keys) {+ assertTrue(+ BasemapPalette.fillRole(id) in listOf(+ BasemapPalette.Fill.RoadCasing,+ BasemapPalette.Fill.RoadTunnel,+ BasemapPalette.Fill.RoadMajor,+ BasemapPalette.Fill.RoadMinor,+ ),+ "'$id' is in the handover set but is not a road surface",+ )+ }+ }++ /**+ * The family decides WHEN the base stops drawing a layer, so a wrong one leaves a zoom where+ * neither the base nor our overlay draws that road. The `_link` layers are the case worth+ * pinning: they are ramps of the through network, not minor streets.+ */+ @Test+ fun `every capped road layer is assigned the family it draws`() {+ val families = BasemapPalette.roadSurfaceFamilies+ for (id in listOf(+ "roads_highway", "roads_major", "roads_link", "roads_link_casing",+ "roads_tunnels_link", "roads_bridges_link_casing", "roads_major_casing_early",+ )) {+ assertEquals(BasemapPalette.RoadFamily.Through, families[id], "family of '$id'")+ }+ for (id in listOf(+ "roads_minor", "roads_minor_service", "roads_other", "roads_minor_casing",+ "roads_tunnels_other", "roads_bridges_minor_casing",+ )) {+ assertEquals(BasemapPalette.RoadFamily.Minor, families[id], "family of '$id'")+ }+ // 33 road surface and casing layers in the bundled style, all classified.+ assertEquals(33, families.size, "unexpected road layer count: ${families.keys}")+ }+ /** * The palette and the bundled style have to stay in step. *
scripts/maps/README.md
diff --git a/scripts/maps/README.md b/scripts/maps/README.mdindex b7a5f9a1f1..aa2d5ad141 100644--- a/scripts/maps/README.md+++ b/scripts/maps/README.md@@ -64,7 +64,7 @@ earth landcover landuse water roads buildings boundaries pois places | source-layer | geometry | key attributes | |---|---|---| | `safety` | Point | `kind` ∈ {`speed_camera`,`alpr`,`surveillance`,`stop_sign`,`traffic_signals`}, `name?`, `direction?`, `operator?`, `ref?`, `osm_id` |-| `maxspeed` | LineString/MultiLineString | **`maxspeed`** (raw OSM value, e.g. `"35 mph"`, `"50"`, `"50 km/h"`), `highway?`, `name?`, `osm_id` |+| `roads` | LineString | **`class`** (number 1-15, `tags::get_hw_id`'s road type), **`maxspeed?`** (raw OSM value, e.g. `"35 mph"`, `"none"`, `"DE:urban"`), `maxspeed_kmh?` (the same limit parsed, ABSENT when there is no numeric one), `lanes?`, `turn_lanes_forward?`/`turn_lanes_backward?` (`\|`-separated decimal `LANE_*` masks), `oneway?`, `width?` (metres), `bridge?`, `tunnel?`, `layer?`, `osm_id` | | `transit_lines` | LineString/MultiLineString | **`kind`** ∈ {`rail`,`subway`,`light_rail`,`tram`,`monorail`,`train`}, `name?`, `ref?`, `colour?` (route colour, e.g. `"#DA291C"`), `osm_id` | | `ma_pois` | Point | **`name`** (string), **`type`** (number, see POI type map), `osm_id` (number). OUR baked OSM POI layer — NOT the base `pois` layer. | | `admin_country` | Polygon/MultiPolygon | `admin_level=2`, `name`, `name_en`, **`ISO_A2`**, `iso_a3` |@@ -75,11 +75,22 @@ The admin layers deliberately preserve `ISO_A2` (countries) and `iso_3166_2` (regions) — the same keys `CountryMap.kt` matches on — so P13 can repoint the mask lookup at the PMTiles source with **no attribute changes**. -The `maxspeed` layer feeds P5b's `MaxspeedSource`, which reads the posted speed-limit via `queryRenderedFeatures` on **source-layer `maxspeed`**, property-**`maxspeed`**. It is a dedicated layer (not an attribute on the base `roads`-layer) so it works whether the base is freshly built or the upstream Protomaps-base is reused verbatim. P13 points `MaxspeedSource.PMTILES_URL` at v5.pmtiles.+The `roads` layer **replaces the `maxspeed` layer**, and above z11 it replaces the+base's road rendering too. `maxspeed` carried one property and a copy of every+road's geometry to attach it to; `roads` carries that geometry once and also has+what it takes to draw and label the road in-app. `RoadsLayer.kt` draws it and+`StylePatcher.kt` caps the base's own road surfaces at the matching zoom, so nothing+is drawn twice and no zoom is left without roads — see+[Caveats](#caveats--known-limitations) §11 for the two-step handover, why z0-10 stays+with the base, and the deploy ordering it implies.++P5b's posted-limit probe reads **source-layer `roads`**, property **`maxspeed`**,+via `queryRenderedFeatures` under the puck. It reads the RAW string, not+`maxspeed_kmh`: the number is the styling attribute and is omitted for every value+that is not a plain speed, while the string is the only thing that still carries an+implicit country scheme (`DE:urban` is 50 km/h) and the only record of whether a+limit was authored in mph — which decides the unit the badge renders in.+`OsmMaxspeed.kt::parseMaxspeed` owns both judgements and is unchanged. The `transit_lines` layer feeds the **P22** transit-line highlight: the app queries **source-layer `transit_lines`** and styles each feature by **`kind`**@@ -119,11 +130,16 @@ mutually consistent (same POI set, same coordinates). See * `man_made=surveillance` (any other) → `surveillance` * `highway=stop` → `stop_sign` * `highway=traffic_signals` → `traffic_signals`-* **Maxspeed** — OpenStreetMap. Ways carrying a `maxspeed` (or- `maxspeed:forward`/`maxspeed:backward`) tag; the raw value is kept verbatim so- the app parses `mph`/`km/h`/bare numbers itself. Non-numeric OSM values- (`none`, `signals`, `walk`, etc.) are also passed through raw — the app-side- parser (`MaxspeedSource`) decides how to render them.+* **Roads** — OpenStreetMap. Every way whose `highway` value has a non-zero+ `tags::get_hw_id` (the routing graph's own road set, 15 classes), carrying the+ class number plus speed, lanes, turn lanes, width and the bridge/tunnel/layer+ draw-order flags. Every tag parser is shared with the routing graph, so a road+ cannot describe itself one way to the router and another to the renderer.+ Speed is carried twice on purpose: `maxspeed` is the tag verbatim and+ `maxspeed_kmh` is `tags::parse_maxspeed`'s number, **omitted** rather than zeroed+ when the value is not a plain speed — `none`, `walk`, `signals` and every+ implicit country scheme all parse to 0, and 0 is not a speed limit. Retires the+ old `maxspeed` layer. * **Transit lines** — OpenStreetMap. Two inputs feed the `transit_lines` layer: * railway **ways** where `railway` ∈ {`rail`,`subway`,`light_rail`,`tram`, `monorail`,`narrow_gauge`} → `kind` (`narrow_gauge` folds into `rail`).@@ -171,10 +187,11 @@ mutually consistent (same POI set, same coordinates). See | `build_all.sh` | **The superscript**: one command from `.osm.pbf` + GTFS to all 11 runtime artifacts, with per-stage stamps and a `manifest.txt` of sizes and SHA-256s. Chains graph → pois → transit → tiles. Overlay-only by default; `--with-base` merges a base in | | `build_all.ps1` | **Windows twin** of the above. Stages graph/pois/transit are complete; the tiles stage composites only the cargo-only layers onto a `-BaseArchive` (see [Caveats](#caveats--known-limitations)) | | `run_generator.sh` | **Deprecated** thin wrapper over `build_all.sh` (graph + pois + publish) |-| `build_v5_pmtiles.sh` | Tile orchestrator: base + safety + maxspeed + transit_lines + ma_pois + admin + transit_stops → merge → `v5.pmtiles` |+| `build_v5_pmtiles.sh` | Tile orchestrator: base + safety + roads + transit_lines + ma_pois + admin + transit_stops → merge → `v5.pmtiles` | | `build_base_layers.sh` | Base tiles (Planetiler build **or** reuse a published archive). A `--bbox` reuse extract now uses our own `pmtiles_extract`; `--extractor go-pmtiles` is still accepted, and is the only practical way to clip the 137 GB planet base | | `build_safety_layer.sh` | **`--engine rust`** (default): `osm_ingest` `osm_extract` → geojsonseq → `tile_build` `tile_points` → `safety.pmtiles`, cargo-only. `--engine legacy`: osmium → GeoJSON → `normalize_safety.py` → tippecanoe |-| `build_maxspeed_layer.sh` | **`--engine rust`** (default): `osm_extract` → geojsonseq → `tile_lines`, cargo-only. `--engine legacy`: osmium → GeoJSON → `normalize_maxspeed.py` → tippecanoe |+| `build_roads_layer.sh` | `osm_extract` → geojsonseq → `tile_lines` at z11-16, cargo-only. **No legacy engine**: there was never a `normalize_roads.py` to be faithful to |+| `build_maxspeed_layer.sh` | **Superseded** by `build_roads_layer.sh`, and no longer in any pipeline. Kept so the retired layer can still be built and diffed against `roads` — delete it once that comparison is done (same policy as [Caveats](#caveats--known-limitations) §8) | | `build_transit_lines_layer.sh` | **`--engine rust`** (default): `osm_extract` reads railway ways **and** route relations straight from the PBF → `tile_lines`, cargo-only, **no GDAL**. `--engine legacy`: osmium + ogr2ogr → GeoJSON → `normalize_transit_lines.py` → tippecanoe, and **requires** ogr2ogr (see [Caveats](#caveats--known-limitations) 9) | | `build_pois_layer.sh` | `osm_ingest` `poi_extract` → geojsonseq + `poi_names.bin` + `poi_index.bin` → `tile_points` (or tippecanoe with `--engine legacy`) → `ma_pois.pmtiles` | | `osm_ingest/` | Rust OSM ingest crate (detached, `.osm.pbf` read natively): `poi_extract` (POI layer + side files), `road_graph` (routing graph) and `osm_extract` (one geojsonseq per baked vector layer, with its own boundary ring assembler in `src/rings.rs`). Full TYPE MAP and on-disk layouts in `src/poi_build.rs` / `src/graph_build.rs`; see [`osm_ingest/README.md`](osm_ingest/README.md) |@@ -186,7 +203,7 @@ mutually consistent (same POI set, same coordinates). See | `tile_build/` | Rust MVT + PMTiles v3 crate (detached), **replacing tippecanoe, tile-join and go-pmtiles**. Bins: `tile_points` / `tile_lines` / `tile_polygons` (one per geometry kind), `tile_join` (merge archives), `pmtiles_extract` (subset by bbox, zoom and layer — the `go-pmtiles extract` replacement and the admin layer lift), `pmtiles_dump` (canonical text dump, for the differential harness). Library: `geojson` (the shared GeoJSONSeq reader), `geom` (web-mercator projection, tile ranges, quantisation), `clip` (Liang-Barsky for lines, Sutherland-Hodgman for polygons), `simplify` (Douglas-Peucker in integer tile coordinates), `pyramid` (the tile pyramid driver and the drop policy), `mvt` (line and polygon encoders beside the opaque passthrough that keeps `tile_join` lossless). Container layout documented in `src/pmtiles.rs`, the pipeline order in `src/geom.rs`, the drop policy in `src/pyramid.rs` | | `publish_r2.sh` | Upload built artifacts to Cloudflare R2 (creds from env vars only) | | `normalize_safety.py` | OSM tags → `safety` layer schema (pure stdlib, unit-tested). **Superseded** by `osm_ingest/src/safety.rs`; kept as the contract of record and as `--engine legacy` for the differential harness |-| `normalize_maxspeed.py` | OSM maxspeed ways → `maxspeed` layer schema (pure stdlib, unit-tested). **Superseded** by `osm_ingest/src/maxspeed.rs`; kept as the contract of record and as `--engine legacy` |+| `normalize_maxspeed.py` | OSM maxspeed ways → `maxspeed` layer schema (pure stdlib, unit-tested). **Superseded** twice over: by `osm_ingest/src/maxspeed.rs`, and then by the `roads` layer that retired `maxspeed` entirely. Kept only as `--engine legacy` for the retired builder | | `normalize_transit_lines.py` | OSM railway ways + route relations → `transit_lines` schema (pure stdlib, unit-tested). **Superseded** by `osm_ingest/src/transit_lines.rs`; kept as the contract of record and as `--engine legacy` | | `normalize_admin.py` | NE/OSM attrs → admin layer schema (pure stdlib, unit-tested). Still the **only** producer for `admin_country`/`admin_region`; the city level is superseded by `osm_ingest/src/admin.rs` | | `test/test_normalize.py` | Dry-run unit test of the schema mapping (no external tools) |@@ -384,6 +401,53 @@ there is no legacy output to diff, so the harness cannot be the thing that tells you the relation half went missing. That is why the check lives in the build script as a hard failure instead. +### 11. `roads` starts at z11, and base roads keep z0-10++Not a phasing choice — a z6-16 all-classes planet roads layer is not something the+current tiler can build:++* `pyramid::build_archive` uses the non-streaming `Builder`, which holds the whole+ archive in memory; `tile_build/src/pmtiles.rs` records 76 GB peak for a 17 GB /+ 36.8 M-tile job. A z6-16 roads layer is several times that. `StreamBuilder`+ exists and is proven on the overlay merge, but is wired only into `tile_join`.+* `pyramid` reads the whole geojsonseq with `read_to_string` and keeps every+ feature parsed, plus a second projected copy per zoom.+* **There is no per-feature zoom gating anywhere in the tiler.** No `min_zoom` on+ `Feature`, no filter in `Options`, nothing property-driven in the zoom loop.+ Dropping `residential` below z12 is exactly how a low zoom is kept small and+ correct, and it cannot be expressed.+* The drop policy is class-blind: `extent_of` sorts by bbox span, so at z6 a long+ suburban collector outranks a motorway stretch.++So the layer covers z11-16 and the handover is done in two steps, because the base+groups its road layers into two families and `RoadsLayer` staggers by class for the+same reason the tiler can't:++| family | base draws | `roads` draws |+|---|---|---|+| motorway, trunk, primary, secondary, tertiary (+ their `*_link` ramps) | z0-11 | z11-16 |+| unclassified, residential, service, living_street, pedestrian, track, footway, cycleway, path, steps | z0-13 | z13-16 |++`StylePatcher` caps each base road layer at its family's zoom and `RoadsLayer` starts+each class at the same one, so no zoom has both drawing and none has neither. A third+threshold would open a hole: the base cannot express one. Road **labels**, shields and+oneway arrows are never capped — the `roads` layer carries no `name` — and+`RoadsLayer` anchors itself below them so its opaque surfaces do not paint over them.++`*_link` ramps get their parent's class (`roads::base_highway`): `tags::get_hw_id` has+no id for one and cannot be given one, since those numbers are an on-disk contract+with `maps/src/main/rust/src/graph.rs`.++**Deploy order matters.** The base's roads are capped unconditionally, so an app build+carrying this change needs an overlay archive that already has the `roads` layer.+Republish `v5-overlay.pmtiles` *before* shipping it, or the map has no roads above+z11.++Extending downward means, in dependency order: wire `StreamBuilder` into+`build_archive` (`add_tile_raw` needs ascending `tile_id`, while the tile loop sorts+by `(x, y)` — not Hilbert order); stream the geojsonseq input; add per-feature+`min_zoom` gating; make the drop policy class-aware.+ --- ## Prerequisites (tools)@@ -403,7 +467,7 @@ here is Rust and Python): go through it, so they run on **Windows**. * **tippecanoe** ≥ 2.x — now only `admin_country`/`admin_region`, and any `--engine legacy` run. The merge does not use its `tile-join`, and `safety`,- `maxspeed`, `transit_lines`, `admin_city` and `ma_pois` do not use it at all.+ `roads`, `transit_lines`, `admin_city` and `ma_pois` do not use it at all. * **osmium-tool** (`osmium`) — `--engine legacy` runs, plus any `--bbox` run of `build_all.sh` (which clips once for every stage). * **GDAL** (`ogr2ogr`) — `admin_country`/`admin_region`, and@@ -420,7 +484,7 @@ here is Rust and Python): Everything that is cargo-only, which is now every layer except `admin_country` and `admin_region`: the routing graph (`build_graph.ps1`), the POI layer and its side-files, `safety`, `maxspeed`, `transit_lines`, `admin_city`, the offline transit pack+files, `safety`, `roads`, `transit_lines`, `admin_city`, the offline transit pack (`build_ca_transit.ps1`), the `transit_stops` layer (`build_transit_stops_layer.ps1`) and the final merge (`tile_join`). `build_all.ps1` chains those. The two Natural Earth levels need ogr2ogr +@@ -489,7 +553,7 @@ unlike the per-layer scripts, the routing graph honours it too. That needs Per-layer `--engine rust|legacy` flags exist for every layer so a ported layer can be rolled back with one flag. Asking for an engine that has not landed is an-error, never a silent fall-back. `safety`, `maxspeed`, `transit_lines`,+error, never a silent fall-back. `safety`, `transit_lines`, `admin-city` and `ma_pois` default to `rust`; `base` and `admin` (meaning the two Natural Earth levels) still default to `legacy`. @@ -571,12 +635,12 @@ Individual layers can also be built standalone — see each script's `--help`. | Artifact | Extent | Approx size | |---|---|---| | `safety.pmtiles` | planet | ~0.3–1 GB (point features only) |-| `maxspeed.pmtiles` | planet | ~1–3 GB (line features on tagged ways) |+| `roads.pmtiles` | planet | ~4–10 GB (every road z11–16, with its lane/width attrs) | | `transit_lines.pmtiles` | planet | ~0.2–1 GB (rail/transit line features) | | `ma_pois.pmtiles` | planet | ~0.5–2 GB (named POI points) | | `poi_names.bin` + `poi_index.bin` + `poi_attrs.bin` + `poi_spatial.bin` + `poi_name_index.bin` | planet | ~1–3 GB combined (side files) | | `admin_country/region/city.pmtiles` | planet | ~50–300 MB combined |-| **`v5-overlay.pmtiles`** | planet | ~**2–7 GB** (every overlay, no base) |+| **`v5-overlay.pmtiles`** | planet | ~**6–17 GB** (every overlay, no base; `roads` is most of it) | | `v5.pmtiles` | planet | ≈ **137 GB** (base + overlays; the base is > 97% of it) | | `v5-sf.pmtiles` | one metro | tens of MB | @@ -637,7 +701,7 @@ It auto-detects the upload tool (`--tool auto|rclone|aws`): * **aws-cli** — `aws s3 cp … --endpoint-url "$R2_ENDPOINT"` (creds scoped to the invocation via `AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY` from the R2 vars). -Since v5 **bakes the maxspeed layer in**, you normally publish just the single+Since v5 **bakes every overlay layer in**, you normally publish just the single `v5.pmtiles`. The script also accepts multiple files (`publish_r2.sh v5.pmtiles aux.pmtiles`) for any siblings built separately. @@ -656,8 +720,8 @@ Then **P13** (separate task, app code) points the style at the new file: "url": "pmtiles://https://data.vayunmathur.com/v5.pmtiles" ``` -…adds style layers for `safety`, points `MaxspeedSource.PMTILES_URL` at the same-file (source-layer `maxspeed`), adds the P22 transit-line highlight against+…adds style layers for `safety`, draws roads from the same file (source-layer+`roads`, which the posted-limit probe also reads), adds the P22 transit-line highlight against source-layer `transit_lines` (styling by `kind` + `colour`), and switches the country/state mask in `CountryMap.kt` / `MyMapLayers.kt` from the `.fgb` assets to the `admin_country` / `admin_region` PMTiles layers (matching on `ISO_A2` /
scripts/maps/build_all.ps1
diff --git a/scripts/maps/build_all.ps1 b/scripts/maps/build_all.ps1index 6233b9cd18..ecb4bd7d1d 100644--- a/scripts/maps/build_all.ps1+++ b/scripts/maps/build_all.ps1@@ -7,7 +7,7 @@ # WHAT THIS TWIN CAN AND CANNOT DO. Only `admin_country` and `admin_region` cannot # be built here, and never will be from OSM: they come from Natural Earth # shapefiles. Everything else is cargo-only, so the tiles stage builds safety,-# maxspeed, transit_lines, admin_city, ma_pois and transit_stops and merges them+# roads, transit_lines, admin_city, ma_pois and transit_stops and merges them # into an OVERLAY-ONLY archive -- no base. The app mounts that alongside the # published base archive, which is also the only shape that fits in tile_join's # memory at planet scale (see build_v5_pmtiles.sh --no-base). It says so loudly@@ -67,7 +67,6 @@ param( # is refused until that layer is actually ported. [ValidateSet("rust", "legacy")] [string] $EnginePois = "rust", [ValidateSet("rust", "legacy")] [string] $EngineSafety = "rust",- [ValidateSet("rust", "legacy")] [string] $EngineMaxspeed = "rust", [ValidateSet("rust", "legacy")] [string] $EngineTransitLines = "rust", [ValidateSet("rust", "legacy")] [string] $EngineAdminCity = "rust", @@ -138,7 +137,7 @@ if ($EnginePois -eq "legacy") { if ($EngineSafety -eq "legacy") { throw "-EngineSafety legacy needs osmium, tippecanoe and python3, none of which have a Windows path; use rust (the default), or build under WSL" }-foreach ($pair in @(@("EngineMaxspeed", $EngineMaxspeed), @("EngineTransitLines", $EngineTransitLines), @("EngineAdminCity", $EngineAdminCity))) {+foreach ($pair in @(@("EngineTransitLines", $EngineTransitLines), @("EngineAdminCity", $EngineAdminCity))) { if ($pair[1] -eq "legacy") { throw "-$($pair[0]) legacy needs osmium, tippecanoe, python3 (and GDAL for transit_lines), none of which have a Windows path; use rust (the default), or build under WSL" }@@ -181,7 +180,7 @@ if ($Geofabrik) { $PoisTile = Join-Path $Work "ma_pois.pmtiles" $SafetyTile = Join-Path $Work "safety.pmtiles"-$MaxspeedTile = Join-Path $Work "maxspeed.pmtiles"+$RoadsTile = Join-Path $Work "roads.pmtiles" $TransitLinesTile = Join-Path $Work "transit_lines.pmtiles" $AdminCityTile = Join-Path $Work "admin_city.pmtiles" $StopsTile = Join-Path $Work "transit_stops.pmtiles"@@ -273,14 +272,16 @@ if (Test-Stage "tiles") { if (Test-Stamp "tiles") { Write-Host "=== tiles: stamp present, skipping (-Force to redo) ===" } else {- # safety, maxspeed, transit_lines and admin_city are all cargo-only:+ # safety, roads, transit_lines and admin_city are all cargo-only: # osm_extract reads the PBF directly -- assembling boundary rings itself for # admin_city -- and the tile_build tilers tile it. No osmium, tippecanoe, # GDAL or python3 is involved. if ($Pbf) { foreach ($spec in @( @{ Layer = "safety"; Tile = $SafetyTile; Bin = "tile_points"; Min = 10; Max = 16; Extra = @() },- @{ Layer = "maxspeed"; Tile = $MaxspeedTile; Bin = "tile_lines"; Min = 12; Max = 16; Extra = @() },+ # z11 up: base roads keep z0-10 and this layer takes over above+ # them, so there is a handover rather than a gap.+ @{ Layer = "roads"; Tile = $RoadsTile; Bin = "tile_lines"; Min = 11; Max = 16; Extra = @() }, @{ Layer = "transit_lines"; Tile = $TransitLinesTile; Bin = "tile_lines"; Min = 8; Max = 16; Extra = @() }, # Admin polygons must stay whole enough to reassemble for the # dimming mask, so the per-tile byte budget is effectively lifted --@@ -298,7 +299,7 @@ if (Test-Stage "tiles") { "--minzoom", "$($spec.Min)", "--maxzoom", "$($spec.Max)") + $spec.Extra) } } else {- Write-Warning "no -Pbf given; skipping the safety, maxspeed, transit_lines and admin_city layers"+ Write-Warning "no -Pbf given; skipping the safety, roads, transit_lines and admin_city layers" } # transit_stops needs the same feed manifest world.transit was built from,@@ -324,7 +325,7 @@ if (Test-Stage "tiles") { # stale copy. No base is joined: the overlay names are disjoint from the # base schema's, so the app mounts the two archives side by side instead. $inputs = @()- foreach ($t in @($SafetyTile, $MaxspeedTile, $TransitLinesTile, $AdminCityTile, $PoisTile, $StopsTile)) {+ foreach ($t in @($SafetyTile, $RoadsTile, $TransitLinesTile, $AdminCityTile, $PoisTile, $StopsTile)) { if ((Test-Path $t) -or $DryRun) { $inputs += $t } } Write-Host "=== tiles: merging $($inputs.Count) source(s) -> $Out ==="
scripts/maps/build_all.sh
diff --git a/scripts/maps/build_all.sh b/scripts/maps/build_all.shindex 629bb330f4..6bfc0e0d80 100644--- a/scripts/maps/build_all.sh+++ b/scripts/maps/build_all.sh@@ -98,7 +98,6 @@ set -euo pipefail # --engine-base E rust|legacy (default legacy) # --engine-safety E rust|legacy (default rust: osm_extract + tile_points, # no osmium/tippecanoe/python3)-# --engine-maxspeed E rust|legacy (default rust: osm_extract + tile_lines) # --engine-transit-lines E (default rust: ways AND route relations # read straight from the PBF, no GDAL) # --engine-admin E rust|legacy (default legacy: admin_country and@@ -149,7 +148,6 @@ PUBLISH=0 PUBLISH_DRY_RUN=0 ENGINE_BASE="legacy" ENGINE_SAFETY="rust"-ENGINE_MAXSPEED="rust" ENGINE_TRANSIT_LINES="rust" ENGINE_ADMIN="legacy" ENGINE_ADMIN_CITY="rust"@@ -187,12 +185,11 @@ while [[ $# -gt 0 ]]; do --publish-dry-run) PUBLISH_DRY_RUN=1; shift ;; --engine-base) ENGINE_BASE="$2"; shift 2 ;; --engine-safety) ENGINE_SAFETY="$2"; shift 2 ;;- --engine-maxspeed) ENGINE_MAXSPEED="$2"; shift 2 ;; --engine-transit-lines) ENGINE_TRANSIT_LINES="$2"; shift 2 ;; --engine-admin) ENGINE_ADMIN="$2"; shift 2 ;; --engine-admin-city) ENGINE_ADMIN_CITY="$2"; shift 2 ;; --engine-pois) ENGINE_POIS="$2"; shift 2 ;;- -h|--help) sed -n '4,119p' "$0" | sed 's/^# \?//'; exit 0 ;;+ -h|--help) sed -n '4,118p' "$0" | sed 's/^# \?//'; exit 0 ;; *) echo "Unknown arg: $1" >&2; exit 1 ;; esac done@@ -217,7 +214,6 @@ engine_check() { } engine_check base "$ENGINE_BASE" 0 engine_check safety "$ENGINE_SAFETY" 1-engine_check maxspeed "$ENGINE_MAXSPEED" 1 engine_check transit-lines "$ENGINE_TRANSIT_LINES" 1 engine_check admin "$ENGINE_ADMIN" 0 engine_check admin-city "$ENGINE_ADMIN_CITY" 1@@ -409,7 +405,6 @@ if want_stage tiles; then V5_ARGS+=(--gtfs-manifest "$GTFS_MANIFEST") fi V5_ARGS+=(--engine-safety "$ENGINE_SAFETY"- --engine-maxspeed "$ENGINE_MAXSPEED" --engine-transit-lines "$ENGINE_TRANSIT_LINES" --engine-admin "$ENGINE_ADMIN" --engine-admin-city "$ENGINE_ADMIN_CITY")
scripts/maps/build_maxspeed_layer.sh
diff --git a/scripts/maps/build_maxspeed_layer.sh b/scripts/maps/build_maxspeed_layer.shindex adf115602f..cebab8af30 100644--- a/scripts/maps/build_maxspeed_layer.sh+++ b/scripts/maps/build_maxspeed_layer.sh@@ -3,6 +3,16 @@ set -euo pipefail # build_maxspeed_layer.sh — bake the `maxspeed` layer (P5b) into a .pmtiles #+# SUPERSEDED BY build_roads_layer.sh, and no longer called by any pipeline. The+# `roads` layer carries this layer's geometry and its raw `maxspeed` string beside+# the class, lane and width attributes the app needs to draw the road, so keeping a+# second copy of every road in the world to hold one property is not worth it.+#+# Kept only so the retired layer can still be built and diffed against `roads`.+# Delete this, normalize_maxspeed.py and osm_ingest/src/maxspeed.rs once that+# comparison is done — the same policy README.md's Caveat §8 applies to the other+# superseded normalisers.+# # Extracts posted speed limits from OSM ways and tiles them into a single-layer # PMTiles file, so the app's MaxspeedSource reads them from the basemap instead of # querying anything at runtime.@@ -61,7 +71,7 @@ while [[ $# -gt 0 ]]; do --engine) ENGINE="$2"; shift 2 ;; --geojson-out) GEOJSON_OUT="$2"; shift 2 ;; --keep-tmp) KEEP_TMP=1; shift ;;- -h|--help) sed -n '4,42p' "$0" | sed 's/^# \?//'; exit 0 ;;+ -h|--help) sed -n '4,52p' "$0" | sed 's/^# \?//'; exit 0 ;; *) echo "Unknown arg: $1" >&2; exit 1 ;; esac done
scripts/maps/build_roads_layer.sh
diff --git a/scripts/maps/build_roads_layer.sh b/scripts/maps/build_roads_layer.shnew file mode 100644index 0000000000..ce72472e9d--- /dev/null+++ b/scripts/maps/build_roads_layer.sh@@ -0,0 +1,118 @@+#!/bin/bash+set -euo pipefail++# build_roads_layer.sh — bake the `roads` layer into a .pmtiles+#+# Extracts road geometry from OSM ways with the attributes the app needs to draw+# and label roads itself — class, speed, lanes, turn lanes, width and the+# bridge/tunnel/layer draw-order flags — and tiles it into a single-layer PMTiles+# file.+#+# Source layer produced: roads+# class number 1-15, `osm_ingest::tags::get_hw_id`'s road type.+# A `*_link` ramp carries its PARENT's class -- get_hw_id has+# no id for one and cannot be given one, since those numbers+# are an on-disk contract with the routing graph.+# maxspeed? the OSM tag verbatim ("25 mph", "none", "DE:urban")+# maxspeed_kmh? the same limit as a number, ABSENT when there isn't one+# lanes? number+# turn_lanes_forward? `|`-separated decimal LANE_* masks, one per lane+# turn_lanes_backward? the same, for the reverse direction+# oneway? 1 when `oneway=yes`+# width? metres+# bridge? tunnel? 1 when set+# layer? signed, absent at ground level+# osm_id "way/123"+#+# THIS LAYER RETIRES `maxspeed`. That layer carried one property and a copy of+# every road's geometry to hang it on; this one carries the same geometry once and+# answers the rendering questions too. The app now draws roads from this layer+# (`RoadsLayer.kt`) above z11 and reads the posted limit out of the same features+# (`queryPostedLimit`); `MaxspeedOverlay.kt` is gone.+#+# SPEED IS CARRIED TWICE, ON PURPOSE. `maxspeed` is the raw tag and `maxspeed_kmh`+# is the parsed km/h number. The number is what a style expression can compare+# against without parsing a string per feature; the raw value is the only thing+# that survives `maxspeed=DE:urban` (the parser answers 0 for every implicit+# country scheme) and the only record of whether a limit was authored in mph, which+# decides the unit the speed badge renders in. `maxspeed_kmh` is omitted rather+# than zeroed when there is no numeric limit, so `none` never reads as 0 km/h.+#+# z11-16, NOT z6-16. Base roads keep z0-10 and this layer takes over above them, so+# there is a clean handover rather than a gap. Replacing base roads outright needs+# tiler work that does not exist yet: `pyramid::build_archive` holds the whole+# archive in memory (see `tile_build/src/pmtiles.rs`'s peak-RSS note) and there is+# no per-feature min-zoom gating, without which a z6 all-classes planet roads layer+# is neither small nor correct. See scripts/maps/README.md.+#+# Usage:+# ./build_roads_layer.sh --pbf planet.osm.pbf --out roads.pmtiles+# ./build_roads_layer.sh --pbf planet.osm.pbf --bbox -122.6,37.2,-121.7,37.9 --out roads.pmtiles+#+# Options:+# --pbf FILE Input OSM .pbf (required)+# --out FILE Output .pmtiles (default: roads.pmtiles)+# --bbox BOX Optional "minlon,minlat,maxlon,maxlat" metro extract (dry runs)+# --minzoom N tiler minzoom (default 11)+# --maxzoom N tiler maxzoom (default 16)+# --geojson-out F also keep the intermediate geojsonseq here+# --keep-tmp Don't delete intermediate files+#+# Tools required: cargo. Nothing else — there is no legacy engine, because there+# was never a `normalize_roads.py` to be faithful to.++HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+PBF=""+OUT="roads.pmtiles"+BBOX=""+MINZOOM=11+MAXZOOM=16+GEOJSON_OUT=""+KEEP_TMP=0++while [[ $# -gt 0 ]]; do+ case "$1" in+ --pbf) PBF="$2"; shift 2 ;;+ --out) OUT="$2"; shift 2 ;;+ --bbox) BBOX="$2"; shift 2 ;;+ --minzoom) MINZOOM="$2"; shift 2 ;;+ --maxzoom) MAXZOOM="$2"; shift 2 ;;+ --geojson-out) GEOJSON_OUT="$2"; shift 2 ;;+ --keep-tmp) KEEP_TMP=1; shift ;;+ -h|--help) sed -n '4,58p' "$0" | sed 's/^# \?//'; exit 0 ;;+ *) echo "Unknown arg: $1" >&2; exit 1 ;;+ esac+done++[[ -n "$PBF" ]] || { echo "ERROR: --pbf required" >&2; exit 1; }+[[ -f "$PBF" ]] || { echo "ERROR: pbf not found: $PBF" >&2; exit 1; }+(( MINZOOM <= MAXZOOM )) || { echo "ERROR: --minzoom above --maxzoom" >&2; exit 1; }+command -v cargo >/dev/null || { echo "ERROR: cargo not installed (https://rustup.rs)" >&2; exit 1; }++TMP="$(mktemp -d)"+cleanup() { [[ "$KEEP_TMP" == "1" ]] || rm -rf "$TMP"; }+trap cleanup EXIT++GEOJSON="${GEOJSON_OUT:-$TMP/roads.geojsonseq}"+[[ -z "$GEOJSON_OUT" ]] || mkdir -p "$(dirname "$GEOJSON_OUT")"++echo "[roads] extracting road ways -> $GEOJSON (osm_extract)"+EXTRACT_ARGS=("$PBF" --layer roads --out "$GEOJSON")+[[ -n "$BBOX" ]] && EXTRACT_ARGS+=(--bbox "$BBOX")+cargo run --release --quiet --manifest-path "$HERE/osm_ingest/Cargo.toml" \+ --bin osm_extract -- "${EXTRACT_ARGS[@]}"++FEATURES="$(wc -l < "$GEOJSON" | tr -d ' ')"+echo "[roads] $FEATURES feature(s)"+[[ "$FEATURES" -gt 0 ]] || echo "[roads] WARNING: 0 features — check bbox/extract"++echo "[roads] tiling -> $OUT (z$MINZOOM-$MAXZOOM)"+cargo run --release --quiet --manifest-path "$HERE/tile_build/Cargo.toml" \+ --bin tile_lines -- \+ --geojson "$GEOJSON" \+ --out "$OUT" \+ --layer roads \+ --minzoom "$MINZOOM" \+ --maxzoom "$MAXZOOM"++echo "[roads] done: $OUT"
scripts/maps/build_v5_pmtiles.sh
diff --git a/scripts/maps/build_v5_pmtiles.sh b/scripts/maps/build_v5_pmtiles.shindex abfce33958..8d1af71778 100644--- a/scripts/maps/build_v5_pmtiles.sh+++ b/scripts/maps/build_v5_pmtiles.sh@@ -20,7 +20,8 @@ set -euo pipefail # # v5.pmtiles = Protomaps base schema (unchanged, style.json-compatible) # + safety (baked road-furniture: cameras/ALPR/stops/signals)-# + maxspeed (posted speed limits for the P5b MaxspeedSource)+# + roads (road geometry + class/speed/lanes/width, retiring the+# separate maxspeed layer) # + transit_lines (OSM rail/subway/tram/… lines for the P22 highlight) # + ma_pois (OUR baked OSM POI layer: placement/name/type from OSM) # + transit_stops (GTFS stop pins + their MOTIS ids, replacing the@@ -39,7 +40,7 @@ set -euo pipefail # 1. build_base_layers.sh -> base.pmtiles (planetiler OR reuse v4) # (skipped by --no-base) # 2. build_safety_layer.sh -> safety.pmtiles (osmium + tippecanoe)-# 3. build_maxspeed_layer.sh-> maxspeed.pmtiles (osmium + tippecanoe)+# 3. build_roads_layer.sh -> roads.pmtiles (cargo-only) # 4. build_transit_lines_layer.sh -> transit_lines.pmtiles (osmium/ogr2ogr + tippecanoe) # 5. build_pois_layer.sh -> ma_pois.pmtiles + poi_{names,index,attrs}.bin # 6. build_admin_layers.sh -> admin_*.pmtiles (Natural Earth/OSM + tippecanoe)@@ -86,13 +87,16 @@ set -euo pipefail # --extra-layer F fold an already-built .pmtiles into the final merge # (repeatable). Lets a caller that built a layer itself skip # the matching step here instead of building it twice.-# --engine-base E rust|legacy per-layer engine. `safety`, `maxspeed`,+# --engine-base E rust|legacy per-layer engine. `safety`, # --engine-safety E `transit_lines` and `admin-city` default to rust-# --engine-maxspeed E (cargo-only); the rest default to legacy, and asking for-# --engine-transit-lines E rust before a layer is ported is an error rather than-# --engine-admin E a silent no-op, so a rollback is always one flag.-# --engine-admin-city E `admin-country`/`admin-region` come from Natural-# Earth and will never have a rust engine.+# --engine-transit-lines E (cargo-only); the rest default to legacy, and asking+# --engine-admin E for rust before a layer is ported is an error rather+# --engine-admin-city E than a silent no-op, so a rollback is always one flag.+# `admin-country`/`admin-region` come from Natural+# Earth and will never have a rust engine. `roads` has+# no switch: it never had a Python normaliser to be+# faithful to, so there is no legacy path to fall back+# to. # --admin-reuse SRC Carry admin_country and admin_region forward from an existing # archive (a local .pmtiles or a URL) with pmtiles_extract, # instead of rebuilding them from Natural Earth. Those two are@@ -102,7 +106,7 @@ set -euo pipefail # --dry-run print each step's command instead of running it # --skip-base don't (re)build base; expects <workdir>/base.pmtiles present # --skip-safety omit safety layer-# --skip-maxspeed omit maxspeed layer+# --skip-roads omit roads layer # --skip-transit-lines omit transit_lines layer # --skip-pois omit ma_pois layer + poi_{names,index,attrs}.bin side files # --skip-admin omit admin layers@@ -112,10 +116,10 @@ set -euo pipefail # --publish-key K remote object key when publishing (default: basename of --out) # --keep-work keep intermediates #-# Tools: osmium, ogr2ogr (GDAL), python3, tippecanoe (base/safety/maxspeed/+# Tools: osmium, ogr2ogr (GDAL), python3, tippecanoe (base/safety/ # transit_lines/pois/admin layers), and either java+planetiler (base build)-# or curl/pmtiles (base reuse). The transit_stops layer and the final merge-# need only cargo. See README.md.+# or curl/pmtiles (base reuse). The roads and transit_stops layers and the+# final merge need only cargo. See README.md. HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" PBF=""@@ -129,7 +133,6 @@ BASE_SOURCE="" EXTRA_LAYERS=() ENGINE_BASE="legacy" ENGINE_SAFETY="rust"-ENGINE_MAXSPEED="rust" ENGINE_TRANSIT_LINES="rust" ENGINE_ADMIN="legacy" ENGINE_ADMIN_CITY="rust"@@ -138,7 +141,7 @@ DRY_RUN=0 NO_BASE=0 SKIP_BASE=0 SKIP_SAFETY=0-SKIP_MAXSPEED=0+SKIP_ROADS=0 SKIP_TRANSIT_LINES=0 SKIP_POIS=0 SKIP_ADMIN=0@@ -161,7 +164,6 @@ while [[ $# -gt 0 ]]; do --extra-layer) EXTRA_LAYERS+=("$2"); shift 2 ;; --engine-base) ENGINE_BASE="$2"; shift 2 ;; --engine-safety) ENGINE_SAFETY="$2"; shift 2 ;;- --engine-maxspeed) ENGINE_MAXSPEED="$2"; shift 2 ;; --engine-transit-lines) ENGINE_TRANSIT_LINES="$2"; shift 2 ;; --engine-admin) ENGINE_ADMIN="$2"; shift 2 ;; --engine-admin-city) ENGINE_ADMIN_CITY="$2"; shift 2 ;;@@ -170,7 +172,7 @@ while [[ $# -gt 0 ]]; do --no-base) NO_BASE=1; shift ;; --skip-base) SKIP_BASE=1; shift ;; --skip-safety) SKIP_SAFETY=1; shift ;;- --skip-maxspeed) SKIP_MAXSPEED=1; shift ;;+ --skip-roads) SKIP_ROADS=1; shift ;; --skip-transit-lines) SKIP_TRANSIT_LINES=1; shift ;; --skip-pois) SKIP_POIS=1; shift ;; --skip-admin) SKIP_ADMIN=1; shift ;;@@ -179,7 +181,7 @@ while [[ $# -gt 0 ]]; do --keep-work) KEEP_WORK=1; shift ;; --publish) PUBLISH=1; shift ;; --publish-key) PUBLISH_KEY="$2"; shift 2 ;;- -h|--help) sed -n '4,118p' "$0" | sed 's/^# \?//'; exit 0 ;;+ -h|--help) sed -n '4,122p' "$0" | sed 's/^# \?//'; exit 0 ;; *) echo "Unknown arg: $1" >&2; exit 1 ;; esac done@@ -232,7 +234,6 @@ engine_check() { } engine_check base "$ENGINE_BASE" 0 engine_check safety "$ENGINE_SAFETY" 1-engine_check maxspeed "$ENGINE_MAXSPEED" 1 engine_check transit-lines "$ENGINE_TRANSIT_LINES" 1 engine_check admin "$ENGINE_ADMIN" 0 engine_check admin-city "$ENGINE_ADMIN_CITY" 1@@ -283,13 +284,13 @@ if [[ "$SKIP_SAFETY" == "0" ]]; then INPUTS+=("$WORK/safety.pmtiles") fi -# --- 3. maxspeed ----if [[ "$SKIP_MAXSPEED" == "0" ]]; then- [[ -n "$PBF" ]] || { echo "ERROR: --pbf required for maxspeed layer (or --skip-maxspeed)" >&2; exit 1; }- MS_ARGS=(--pbf "$PBF" --out "$WORK/maxspeed.pmtiles" --engine "$ENGINE_MAXSPEED")- [[ -n "$BBOX" ]] && MS_ARGS+=(--bbox "$BBOX")- run "$HERE/build_maxspeed_layer.sh" "${MS_ARGS[@]}"- INPUTS+=("$WORK/maxspeed.pmtiles")+# --- 3. roads ---+if [[ "$SKIP_ROADS" == "0" ]]; then+ [[ -n "$PBF" ]] || { echo "ERROR: --pbf required for roads layer (or --skip-roads)" >&2; exit 1; }+ ROADS_ARGS=(--pbf "$PBF" --out "$WORK/roads.pmtiles")+ [[ -n "$BBOX" ]] && ROADS_ARGS+=(--bbox "$BBOX")+ run "$HERE/build_roads_layer.sh" "${ROADS_ARGS[@]}"+ INPUTS+=("$WORK/roads.pmtiles") fi # --- 4. transit_lines ---@@ -408,7 +409,7 @@ if [[ "$NO_BASE" == "1" ]]; then else echo " base : earth landcover landuse water roads buildings boundaries pois places" fi-echo " new : safety maxspeed transit_lines ma_pois transit_stops"+echo " new : safety roads transit_lines ma_pois transit_stops" echo " admin_country admin_region admin_city" echo "" if [[ "$SKIP_POIS" == "0" ]]; then
scripts/maps/osm_ingest/src/extract.rs
diff --git a/scripts/maps/osm_ingest/src/extract.rs b/scripts/maps/osm_ingest/src/extract.rsindex 4aff0ba00a..7a3cfe3189 100644--- a/scripts/maps/osm_ingest/src/extract.rs+++ b/scripts/maps/osm_ingest/src/extract.rs@@ -43,6 +43,7 @@ use crate::osm::{visit_block, Element, Member, MEMBER_WAY}; use crate::pbf::{self, KIND_NODES, KIND_RELATIONS, KIND_WAYS}; use crate::proto::{Error, Result}; use crate::rings::{self, MemberWay, RingStats};+use crate::roads::{self, RoadTags}; use crate::safety::{self, Kind, SafetyTags}; use crate::select::Select; use crate::transit_lines::{self, TransitTags};@@ -51,6 +52,7 @@ use crate::transit_lines::{self, TransitTags}; pub enum Layer { Safety, Maxspeed,+ Roads, TransitLines, AdminCity, }@@ -60,6 +62,7 @@ impl Layer { match s { "safety" => Ok(Layer::Safety), "maxspeed" => Ok(Layer::Maxspeed),+ "roads" => Ok(Layer::Roads), "transit_lines" => Ok(Layer::TransitLines), "admin_city" => Ok(Layer::AdminCity), other => Err(format!(@@ -70,13 +73,14 @@ impl Layer { } pub fn names() -> Vec<&'static str> {- vec!["safety", "maxspeed", "transit_lines", "admin_city"]+ vec!["safety", "maxspeed", "roads", "transit_lines", "admin_city"] } pub fn name(self) -> &'static str { match self { Layer::Safety => "safety", Layer::Maxspeed => "maxspeed",+ Layer::Roads => "roads", Layer::TransitLines => "transit_lines", Layer::AdminCity => "admin_city", }@@ -134,6 +138,7 @@ pub fn build(input: &Path, out: &Path, opts: &Options) -> Result<Stats> { match opts.layer { Layer::Safety => build_safety(input, &blobs, out, opts), Layer::Maxspeed => build_maxspeed(input, &blobs, out, opts),+ Layer::Roads => build_roads(input, &blobs, out, opts), Layer::TransitLines => build_transit_lines(input, &blobs, out, opts), Layer::AdminCity => build_admin_city(input, &blobs, out, opts), }@@ -501,6 +506,156 @@ fn maxspeed_blob( Ok(kinds) } +// --- roads ----------------------------------------------------------------++/// One road way, with every tag value the layer emits copied out of the block.+///+/// The tag strings are owned because the pass borrows them from the+/// `PrimitiveBlock` it is reading, which is dropped with the blob. Thirteen+/// `Option<String>` per road is the one place this layer is heavier than+/// `maxspeed`, and since this is every road rather than only the ones with a posted+/// limit, `build_roads` consumes the rows as it renders them rather than holding+/// both the rows and the output at once.+struct RoadRow {+ id: i64,+ refs: Vec<i64>,+ class: u8,+ maxspeed: Option<String>,+ lanes: Option<String>,+ lanes_forward: Option<String>,+ lanes_backward: Option<String>,+ turn_lanes: Option<String>,+ turn_lanes_forward: Option<String>,+ turn_lanes_backward: Option<String>,+ oneway: Option<String>,+ width: Option<String>,+ bridge: Option<String>,+ tunnel: Option<String>,+ layer: Option<String>,+}++impl RoadRow {+ fn tags(&self) -> RoadTags<'_> {+ RoadTags {+ // `highway` is not re-read: `class` already holds what it classified to.+ highway: None,+ maxspeed: self.maxspeed.as_deref(),+ lanes: self.lanes.as_deref(),+ lanes_forward: self.lanes_forward.as_deref(),+ lanes_backward: self.lanes_backward.as_deref(),+ turn_lanes: self.turn_lanes.as_deref(),+ turn_lanes_forward: self.turn_lanes_forward.as_deref(),+ turn_lanes_backward: self.turn_lanes_backward.as_deref(),+ oneway: self.oneway.as_deref(),+ width: self.width.as_deref(),+ bridge: self.bridge.as_deref(),+ tunnel: self.tunnel.as_deref(),+ layer: self.layer.as_deref(),+ }+ }+}++fn build_roads(+ input: &Path,+ blobs: &[pbf::BlobLoc],+ out: &Path,+ opts: &Options,+) -> Result<Stats> {+ let select = Select::parse(&roads::FILTERS)?;++ // Same two passes as `maxspeed`: ways, then the node coordinates they need.+ let (chunks, blob_kinds) = pbf::run_pass(+ input,+ blobs,+ None,+ KIND_WAYS,+ "Pass 1: ways",+ Vec::<RoadRow>::new,+ |state: &mut Vec<RoadRow>, block| roads_blob(state, block, &select),+ )?;+ let mut rows: Vec<RoadRow> = Vec::new();+ for chunk in chunks {+ rows.extend(chunk);+ }+ println!("{} road way(s)", rows.len());++ let table = NodeLocations::new(rows.iter().flat_map(|r| r.refs.iter().copied()).collect());+ println!("{} node location(s) needed", table.len());+ let table = resolve_nodes(input, blobs, &blob_kinds, "Pass 2: nodes", table)?;++ let mut lines: Vec<LineFeature> = Vec::with_capacity(rows.len());+ let mut outside_bbox = 0usize;+ // `drain` rather than a borrow: at planet scale the rows and the rendered output+ // would otherwise both be resident, and the rows are the larger half.+ for row in rows.drain(..) {+ let coords = table.line(&row.refs);+ if coords.len() < 2 {+ continue;+ }+ if !parts_touch_bbox(std::slice::from_ref(&coords), opts.bbox.as_ref()) {+ outside_bbox += 1;+ continue;+ }+ let f = roads::feature(row.class, &row.tags(), Geometry::LineString(coords), row.id);+ lines.push(LineFeature { sort: ("way", row.id), rendered: render(&f) });+ }++ let written = write_lines(out, lines)?;+ println!("Wrote {} roads feature(s) to {}", written, out.display());+ if outside_bbox > 0 {+ println!("{outside_bbox} feature(s) dropped by --bbox");+ }+ Ok(Stats {+ features: written,+ from_nodes: 0,+ from_ways: written,+ from_relations: 0,+ outside_bbox,+ })+}++fn roads_blob(+ state: &mut Vec<RoadRow>,+ block: &pbf::PrimitiveBlock,+ select: &Select,+) -> Result<u8> {+ let mut kinds = 0u8;+ visit_block(block, KIND_WAYS, &mut kinds, &mut |el: Element| {+ if let Element::Way(w) = el {+ if w.refs.len() < 2 || w.tags.is_empty() {+ return Ok(());+ }+ if !select.matches(|k| w.tags.get_str(k)) {+ return Ok(());+ }+ let t = RoadTags { highway: w.tags.get_str("highway"), ..Default::default() };+ let Some(class) = roads::classify(&t) else {+ return Ok(());+ };+ let own = |k: &str| w.tags.get_str(k).map(str::to_string);+ state.push(RoadRow {+ id: w.id,+ refs: w.refs.to_vec(),+ class,+ maxspeed: own("maxspeed"),+ lanes: own("lanes"),+ lanes_forward: own("lanes:forward"),+ lanes_backward: own("lanes:backward"),+ turn_lanes: own("turn:lanes"),+ turn_lanes_forward: own("turn:lanes:forward"),+ turn_lanes_backward: own("turn:lanes:backward"),+ oneway: own("oneway"),+ width: own("width"),+ bridge: own("bridge"),+ tunnel: own("tunnel"),+ layer: own("layer"),+ });+ }+ Ok(())+ })?;+ Ok(kinds)+}+ // --- transit_lines -------------------------------------------------------- /// One classified way or relation, with its tag values copied out of the block.@@ -1228,6 +1383,78 @@ mod tests { assert!(mph.contains("-122.43"), "{mph}"); } + // --- roads ------------------------------------------------------------++ #[test]+ fn extracts_the_roads_layer_with_lanes_speed_and_width() {+ let (lines, stats) = extract_layer("extract_roads", Layer::Roads);+ // All three of the fixture's highway ways, including the one with no+ // speed limit: `roads` is every road, not only the ones with a limit.+ assert_eq!((stats.features, stats.from_ways), (3, 3));+ assert_eq!(lines.len(), 3);++ // The fully-attributed motorway.+ let m = lines.iter().find(|l| l.contains("way/3002")).unwrap();+ assert!(m.contains("\"class\":1"), "motorway is class 1: {m}");+ assert!(m.contains("\"lanes\":3"), "{m}");+ // through|through|right as the graph's own LANE_* masks, left to right.+ assert!(+ m.contains(&format!(+ "\"turn_lanes_forward\":\"{}|{}|{}\"",+ crate::tags::LANE_THROUGH,+ crate::tags::LANE_THROUGH,+ crate::tags::LANE_RIGHT+ )),+ "{m}"+ );+ assert!(m.contains("\"oneway\":1"), "{m}");+ assert!(m.contains("\"width\":12.00"), "{m}");+ assert!(m.contains("\"bridge\":1"), "{m}");+ assert!(m.contains("\"layer\":1"), "{m}");+ // `maxspeed=none` keeps its string and gets no number: it is not 0 km/h.+ assert!(m.contains("\"maxspeed\":\"none\""), "{m}");+ assert!(!m.contains("maxspeed_kmh"), "{m}");++ // A posted mph limit arrives as both forms.+ let r = lines.iter().find(|l| l.contains("way/3001")).unwrap();+ assert!(r.contains("\"class\":7"), "residential is class 7: {r}");+ assert!(r.contains("\"maxspeed\":\"25 mph\""), "{r}");+ assert!(r.contains("\"maxspeed_kmh\":40"), "{r}");+ assert!(r.contains("\"type\":\"LineString\""), "{r}");+ // Geometry came from resolved node coordinates.+ assert!(r.contains("-122.43"), "{r}");++ // And the service road with nothing on it is class + osm_id only.+ let s = lines.iter().find(|l| l.contains("way/3003")).unwrap();+ assert!(s.contains("\"properties\":{\"class\":8,\"osm_id\":\"way/3003\"}"), "{s}");++ // The railway ways and the platform are not roads.+ assert!(!lines.iter().any(|l| l.contains("way/5001")));+ }++ #[test]+ fn roads_is_deterministic_and_bbox_filtered() {+ let (pbf_path, dir) = testpbf::write_layers_sample("det_roads");+ let run = |suffix: &str| {+ let out = dir.join(format!("roads{suffix}.geojsonseq"));+ build(&pbf_path, &out, &Options { layer: Layer::Roads, bbox: None }).unwrap();+ std::fs::read(out).unwrap()+ };+ assert_eq!(run("a"), run("b"));++ let stats = build(+ &pbf_path,+ &dir.join("empty.geojsonseq"),+ &Options {+ layer: Layer::Roads,+ bbox: Some(BBox::parse("-30,20,-20,30").unwrap()),+ },+ )+ .unwrap();+ assert_eq!(stats.features, 0);+ assert_eq!(stats.outside_bbox, 3);+ }+ // --- transit_lines ---------------------------------------------------- #[test]
scripts/maps/osm_ingest/src/lib.rs
diff --git a/scripts/maps/osm_ingest/src/lib.rs b/scripts/maps/osm_ingest/src/lib.rsindex 2a54dff75b..43462511ce 100644--- a/scripts/maps/osm_ingest/src/lib.rs+++ b/scripts/maps/osm_ingest/src/lib.rs@@ -35,6 +35,7 @@ pub mod poi_build; pub mod poi_side; pub mod proto; pub mod rings;+pub mod roads; pub mod safety; pub mod select; pub mod spatial;
scripts/maps/osm_ingest/src/maxspeed.rs
diff --git a/scripts/maps/osm_ingest/src/maxspeed.rs b/scripts/maps/osm_ingest/src/maxspeed.rsindex b863632ad4..c07bfdd6f2 100644--- a/scripts/maps/osm_ingest/src/maxspeed.rs+++ b/scripts/maps/osm_ingest/src/maxspeed.rs@@ -1,5 +1,13 @@ //! The `maxspeed` layer: posted speed limits, for the app's `MaxspeedSource`. //!+//! **Superseded by [`crate::roads`], and no longer in any build pipeline.** That+//! layer carries the same geometry with the same raw `maxspeed` string beside the+//! lane, width and class attributes the app needs to draw the road, so a second+//! copy of every road in the world is not worth one property. Kept only so the+//! retired layer can still be built and diffed against `roads`; delete it, and+//! `build_maxspeed_layer.sh` and `normalize_maxspeed.py` with it, once that+//! comparison is done.+//! //! A port of `normalize_maxspeed.py`, which is the contract of record. //! //! ## The value is a RAW STRING and must stay one
scripts/maps/osm_ingest/src/roads.rs
diff --git a/scripts/maps/osm_ingest/src/roads.rs b/scripts/maps/osm_ingest/src/roads.rsnew file mode 100644index 0000000000..5b11ddd5b1--- /dev/null+++ b/scripts/maps/osm_ingest/src/roads.rs@@ -0,0 +1,444 @@+//! The `roads` layer: road geometry with the speed, lane and width attributes the+//! app needs to draw and label roads itself.+//!+//! This is the layer that retires [`crate::maxspeed`]. That one existed to answer+//! exactly one question -- what is the posted limit under the puck -- and carried a+//! way's geometry only as the thing the answer was attached to. Owning road+//! rendering in-app needs the same geometry plus lanes and width, and a second+//! near-identical layer of every road in the world is not worth a property.+//!+//! ## Speed is carried BOTH ways, deliberately+//!+//! `maxspeed` is the OSM tag verbatim and `maxspeed_kmh` is+//! [`crate::tags::parse_maxspeed`]'s km/h number. Neither is redundant:+//!+//! * The **number** is what a data-driven style expression can compare against,+//! because MVT gives the app an int and not a string it has to parse per feature.+//! * The **raw string** is the only thing that survives `maxspeed=DE:urban`,+//! `GB:nsl_single` and friends -- `parse_maxspeed` returns 0 for every implicit+//! country scheme -- and the only thing that records whether a limit was authored+//! in mph, which is what decides the unit the app's speed badge renders in.+//! `OsmMaxspeed.kt::parseMaxspeed` resolves both and stays the consumer of record.+//!+//! `maxspeed_kmh` is **omitted, not zeroed**, when there is no numeric limit, so+//! `none`, `walk`, `signals` and `DE:urban` are absent rather than claiming a limit+//! of nought. `crate::maxspeed`'s guard test spells out what each of them becomes.+//!+//! ## Lane masks are the graph's, unchanged+//!+//! `turn_lanes_forward` / `turn_lanes_backward` are `|`-separated decimal+//! [`crate::tags`] `LANE_*` masks, one token per lane, left to right -- the same+//! bits, in the same order, that the routing graph writes and+//! `maps/src/main/rust/src/graph.rs` reads. Which tag feeds which direction follows+//! `graph_build::way_attrs` exactly, so a road cannot describe its lanes one way to+//! the router and another to the renderer.++use crate::geojson::{osm_ref, Feature, Geometry, Value};+use crate::tags;++/// The `highway=*` values this layer carries: the set [`crate::tags::get_hw_id`] gives+/// a non-zero id, since that id *is* the emitted `class`, plus the `*_link` ramps it+/// has no id for (see [`base_highway`]).+pub const CLASSES: [&str; 15] = [+ "motorway",+ "trunk",+ "primary",+ "secondary",+ "tertiary",+ "unclassified",+ "residential",+ "service",+ "living_street",+ "pedestrian",+ "track",+ "footway",+ "cycleway",+ "path",+ "steps",+];++/// The `*_link` values, which are slip roads of a [`CLASSES`] parent.+pub const LINK_CLASSES: [&str; 5] = [+ "motorway_link",+ "trunk_link",+ "primary_link",+ "secondary_link",+ "tertiary_link",+];++/// The `osmium tags-filter` expression, kept in step with [`CLASSES`] and+/// [`LINK_CLASSES`] by a test.+pub const FILTERS: [&str; 1] = ["highway=motorway,trunk,primary,secondary,tertiary,\+unclassified,residential,service,living_street,pedestrian,track,footway,cycleway,\+path,steps,motorway_link,trunk_link,primary_link,secondary_link,tertiary_link"];++#[derive(Debug, Default, Clone, Copy)]+pub struct RoadTags<'a> {+ pub highway: Option<&'a str>,+ pub maxspeed: Option<&'a str>,+ pub lanes: Option<&'a str>,+ pub lanes_forward: Option<&'a str>,+ pub lanes_backward: Option<&'a str>,+ pub turn_lanes: Option<&'a str>,+ pub turn_lanes_forward: Option<&'a str>,+ pub turn_lanes_backward: Option<&'a str>,+ pub oneway: Option<&'a str>,+ pub width: Option<&'a str>,+ pub bridge: Option<&'a str>,+ pub tunnel: Option<&'a str>,+ pub layer: Option<&'a str>,+}++/// The parent class of a `highway` value: `motorway_link` -> `motorway`.+///+/// A slip road IS its parent class as far as drawing goes -- it is the same asphalt at+/// the same width, and a map that omits interchange ramps has holes in every+/// motorway junction. [`crate::tags::get_hw_id`] has no id for one, and cannot be+/// given one: those numbers are an on-disk contract with+/// `maps/src/main/rust/src/graph.rs` and renumbering them would reinterpret every+/// edge in an already-built graph. So the suffix is dropped here instead.+pub fn base_highway(value: Option<&str>) -> Option<&str> {+ let v = value?;+ Some(v.strip_suffix("_link").unwrap_or(v))+}++/// The road class number, or `None` for a `highway` value that is not a road.+pub fn classify(t: &RoadTags) -> Option<u8> {+ match tags::get_hw_id(base_highway(t.highway)) {+ 0 => None,+ id => Some(id),+ }+}++/// An OSM flag tag that is set. Absent, empty and `no` are all unset; anything+/// else counts, because `bridge=viaduct` and `tunnel=building_passage` are as much+/// a bridge and a tunnel as `yes` is.+fn flag(v: Option<&str>) -> bool {+ matches!(v, Some(s) if !s.is_empty() && s != "no")+}++/// `layer=*` as a signed number for draw order. Absent or unparseable is 0, the+/// same as ground level; the `1;2` and `0.5` forms real data contains are not+/// orderings this layer can express, so they get ground level rather than a guess.+pub fn parse_layer(v: Option<&str>) -> i32 {+ v.and_then(|s| s.trim().parse::<i32>().ok()).unwrap_or(0)+}++/// Per-lane `LANE_*` masks for each direction, `(forward, backward)`.+///+/// A verbatim copy of `graph_build::way_attrs`'s derivation: forward lanes come+/// from `turn:lanes:forward`, or from a plain `turn:lanes` when the way is a+/// oneway; backward from `turn:lanes:backward`, and a oneway has none. The plain+/// `lanes*` counts only pad or truncate a real `turn:lanes` list.+pub fn lane_masks(t: &RoadTags) -> (Vec<u16>, Vec<u16>) {+ let oneway = is_oneway(t);+ let count_all = tags::parse_int_tag(t.lanes);+ let count_fwd = tags::parse_int_tag(t.lanes_forward);+ let count_bwd = tags::parse_int_tag(t.lanes_backward);++ let fwd_spec = t.turn_lanes_forward.or(if oneway { t.turn_lanes } else { None });+ let fwd_hint = if count_fwd > 0 {+ count_fwd+ } else if oneway {+ count_all+ } else {+ 0+ };+ let bwd_spec = if oneway { None } else { t.turn_lanes_backward };+ (+ tags::build_dir_lanes(fwd_spec, fwd_hint),+ tags::build_dir_lanes(bwd_spec, count_bwd),+ )+}++/// `oneway=yes`, and only that -- the same test the routing graph applies, so the+/// two cannot disagree about a road. `oneway=-1` is a direction rather than a+/// flag and neither models it.+pub fn is_oneway(t: &RoadTags) -> bool {+ t.oneway == Some("yes")+}++/// One direction's masks as the `|`-separated decimal tokens the property holds.+pub fn pack_lanes(masks: &[u16]) -> String {+ let mut out = String::new();+ for (i, m) in masks.iter().enumerate() {+ if i > 0 {+ out.push('|');+ }+ out.push_str(&m.to_string());+ }+ out+}++/// Build the emitted feature.+///+/// Every attribute past `class` and `osm_id` is **omitted when it has nothing to+/// say**, rather than written as a zero or an empty string. At planet scale this is+/// most of the layer's size: the great majority of roads carry no `turn:lanes`, no+/// `width` and no `layer`, and a property present on every feature is a property+/// paid for on every feature.+pub fn feature<'a>(+ class: u8,+ t: &RoadTags<'a>,+ geometry: Geometry,+ way_id: i64,+) -> Feature<'a> {+ let mut props: Vec<(&'a str, Value)> = vec![("class", Value::num(class))];++ if let Some(v) = t.maxspeed.filter(|v| !v.is_empty()) {+ props.push(("maxspeed", Value::str(v)));+ }+ let kmh = tags::parse_maxspeed(t.maxspeed);+ if kmh > 0 {+ props.push(("maxspeed_kmh", Value::num(kmh)));+ }++ let lanes = tags::parse_int_tag(t.lanes);+ if lanes > 0 {+ props.push(("lanes", Value::num(lanes.min(tags::MAX_LANES))));+ }+ let (fwd, bwd) = lane_masks(t);+ if !fwd.is_empty() {+ props.push(("turn_lanes_forward", Value::str(pack_lanes(&fwd))));+ }+ if !bwd.is_empty() {+ props.push(("turn_lanes_backward", Value::str(pack_lanes(&bwd))));+ }++ if is_oneway(t) {+ props.push(("oneway", Value::num(1u8)));+ }+ let width = tags::parse_width_m(t.width);+ if width > 0.0 {+ // Two decimals: centimetre resolution is already finer than the tag is+ // ever surveyed to, and a fixed form keeps two runs byte-identical.+ props.push(("width", Value::Raw(format!("{width:.2}"))));+ }+ if flag(t.bridge) {+ props.push(("bridge", Value::num(1u8)));+ }+ if flag(t.tunnel) {+ props.push(("tunnel", Value::num(1u8)));+ }+ let layer = parse_layer(t.layer);+ if layer != 0 {+ props.push(("layer", Value::num(layer)));+ }++ props.push(("osm_id", osm_ref("way", way_id)));+ Feature { geometry, props }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::tags::{LANE_LEFT, LANE_NONE, LANE_RIGHT, LANE_THROUGH};++ fn road(highway: &str) -> RoadTags<'_> {+ RoadTags { highway: Some(highway), ..Default::default() }+ }++ fn keys<'a>(f: &Feature<'a>) -> Vec<&'a str> {+ f.props.iter().map(|(k, _)| *k).collect()+ }++ fn rendered(f: &Feature) -> String {+ let mut line = Vec::new();+ crate::geojson::render_feature(f, &mut line);+ String::from_utf8(line).unwrap()+ }++ #[test]+ fn the_class_is_the_graphs_own_road_type_number() {+ // Sharing `get_hw_id` is what keeps the rendered class and the routed+ // class the same fact about a road.+ assert_eq!(classify(&road("motorway")), Some(1));+ assert_eq!(classify(&road("residential")), Some(7));+ assert_eq!(classify(&road("steps")), Some(15));+ // Not a road: no feature at all.+ assert_eq!(classify(&road("proposed")), None);+ assert_eq!(classify(&road("")), None);+ assert_eq!(classify(&RoadTags::default()), None);+ }++ #[test]+ fn a_slip_road_takes_its_parent_class() {+ // `get_hw_id` has no id for a `*_link` and cannot be given one without+ // renumbering the graph's on-disk road types, so the suffix is dropped.+ assert_eq!(classify(&road("motorway_link")), classify(&road("motorway")));+ assert_eq!(classify(&road("tertiary_link")), Some(5));+ assert_eq!(base_highway(Some("primary_link")), Some("primary"));+ assert_eq!(base_highway(Some("primary")), Some("primary"));+ // Not every `_link` suffix is a road: the parent still has to classify.+ assert_eq!(classify(&road("raceway_link")), None);+ }++ #[test]+ fn the_pbf_filter_and_the_class_set_agree() {+ let select = crate::select::Select::parse(&FILTERS).unwrap();+ for value in CLASSES {+ assert_ne!(+ tags::get_hw_id(Some(value)),+ 0,+ "highway={value} is filtered in but has no class"+ );+ assert!(+ select.matches(|k| if k == "highway" { Some(value) } else { None }),+ "highway={value} classifies but is pre-filtered out"+ );+ }+ // Every ramp is let through and lands on its parent's class.+ for value in LINK_CLASSES {+ assert!(+ select.matches(|k| if k == "highway" { Some(value) } else { None }),+ "highway={value} classifies but is pre-filtered out"+ );+ let parent = value.strip_suffix("_link").unwrap();+ assert_eq!(classify(&road(value)), classify(&road(parent)), "{value}");+ }+ // And nothing outside the set gets through.+ for value in ["proposed", "construction", "raceway", "bus_guideway"] {+ assert_eq!(tags::get_hw_id(Some(value)), 0, "{value}");+ assert!(!select.matches(|k| if k == "highway" { Some(value) } else { None }));+ }+ }++ #[test]+ fn speed_is_carried_as_both_the_raw_tag_and_a_number() {+ let t = RoadTags { highway: Some("residential"), maxspeed: Some("25 mph"), ..Default::default() };+ let f = feature(7, &t, Geometry::LineString(vec![]), 3001);+ assert_eq!(keys(&f), ["class", "maxspeed", "maxspeed_kmh", "osm_id"]);+ let s = rendered(&f);+ assert!(s.contains("\"maxspeed\":\"25 mph\""), "{s}");+ assert!(s.contains("\"maxspeed_kmh\":40"), "{s}");+ }++ #[test]+ fn a_speed_the_number_cannot_hold_keeps_its_string_and_omits_the_number() {+ // The whole reason both are emitted. `parse_maxspeed` answers 0 for every+ // one of these, and 0 is not a speed limit, so the property is absent and+ // the app falls back to parsing the raw value.+ for raw in ["none", "walk", "signals", "DE:urban", "GB:nsl_single"] {+ let t = RoadTags { highway: Some("motorway"), maxspeed: Some(raw), ..Default::default() };+ let f = feature(1, &t, Geometry::LineString(vec![]), 1);+ assert_eq!(keys(&f), ["class", "maxspeed", "osm_id"], "{raw}");+ assert!(rendered(&f).contains(&format!("\"maxspeed\":\"{raw}\"")), "{raw}");+ }+ // And a way with no maxspeed tag at all carries neither.+ let f = feature(7, &road("residential"), Geometry::LineString(vec![]), 1);+ assert_eq!(keys(&f), ["class", "osm_id"]);+ }++ #[test]+ fn turn_lanes_pack_to_the_graphs_masks_in_lane_order() {+ let t = RoadTags {+ highway: Some("primary"),+ turn_lanes_forward: Some("left|through|through;right"),+ ..Default::default()+ };+ let (fwd, bwd) = lane_masks(&t);+ assert_eq!(fwd, vec![LANE_LEFT, LANE_THROUGH, LANE_THROUGH | LANE_RIGHT]);+ assert!(bwd.is_empty());+ assert_eq!(+ pack_lanes(&fwd),+ format!("{LANE_LEFT}|{LANE_THROUGH}|{}", LANE_THROUGH | LANE_RIGHT)+ );+ let f = feature(3, &t, Geometry::LineString(vec![]), 1);+ assert_eq!(keys(&f), ["class", "turn_lanes_forward", "osm_id"]);+ }++ #[test]+ fn lane_direction_derivation_matches_the_routing_graph() {+ // A plain `turn:lanes` belongs to the forward direction only on a oneway;+ // on a two-way street it is ambiguous and the graph takes neither side.+ let two_way = RoadTags {+ highway: Some("residential"),+ turn_lanes: Some("left|through"),+ ..Default::default()+ };+ assert_eq!(lane_masks(&two_way), (Vec::new(), Vec::new()));++ let one_way = RoadTags { oneway: Some("yes"), ..two_way };+ assert_eq!(lane_masks(&one_way).0, vec![LANE_LEFT, LANE_THROUGH]);+ assert!(lane_masks(&one_way).1.is_empty());++ // A oneway never carries backward lanes, whatever the tag says.+ let contradictory = RoadTags {+ oneway: Some("yes"),+ turn_lanes_backward: Some("through"),+ ..two_way+ };+ assert!(lane_masks(&contradictory).1.is_empty());++ // `lanes:forward` pads a short list; on a oneway plain `lanes` does.+ let padded = RoadTags {+ highway: Some("primary"),+ turn_lanes_forward: Some("left"),+ lanes_forward: Some("3"),+ ..Default::default()+ };+ assert_eq!(lane_masks(&padded).0, vec![LANE_LEFT, LANE_NONE, LANE_NONE]);+ }++ #[test]+ fn a_mistagged_lane_count_cannot_become_an_allocation() {+ // `MAX_LANES` guards both the padding and the emitted count.+ let t = RoadTags {+ highway: Some("motorway"),+ turn_lanes_forward: Some("through"),+ lanes: Some("999999999"),+ lanes_forward: Some("999999999"),+ ..Default::default()+ };+ assert_eq!(lane_masks(&t).0.len(), tags::MAX_LANES as usize);+ let s = rendered(&feature(1, &t, Geometry::LineString(vec![]), 1));+ assert!(s.contains(&format!("\"lanes\":{}", tags::MAX_LANES)), "{s}");+ }++ #[test]+ fn width_converts_feet_and_rejects_nonsense() {+ assert!((tags::parse_width_m(Some("3.5")) - 3.5).abs() < 1e-9);+ assert!((tags::parse_width_m(Some("3.5 m")) - 3.5).abs() < 1e-9);+ assert_eq!(tags::parse_width_m(Some("wide")), 0.0);+ assert_eq!(tags::parse_width_m(Some("-2")), 0.0);+ assert_eq!(tags::parse_width_m(None), 0.0);+ // Every form of feet, however it is spaced or cased. Reading one of these as+ // metres would make a residential street wider than a motorway.+ for v in ["10 ft", "10ft", "10 FT ", "10 Feet", "10'"] {+ assert!((tags::parse_width_m(Some(v)) - 3.048).abs() < 1e-9, "{v}");+ }++ // Emitted with two decimals, so two runs are byte-identical.+ let t = RoadTags { highway: Some("residential"), width: Some("10 ft"), ..Default::default() };+ assert!(rendered(&feature(7, &t, Geometry::LineString(vec![]), 1)).contains("\"width\":3.05"));+ }++ #[test]+ fn draw_order_flags_survive_their_real_tag_values() {+ // `bridge=viaduct` is a bridge; `tunnel=no` is not a tunnel.+ let t = RoadTags {+ highway: Some("motorway"),+ bridge: Some("viaduct"),+ tunnel: Some("no"),+ layer: Some("-1"),+ ..Default::default()+ };+ let f = feature(1, &t, Geometry::LineString(vec![]), 1);+ assert_eq!(keys(&f), ["class", "bridge", "layer", "osm_id"]);+ assert!(rendered(&f).contains("\"layer\":-1"));++ // Ground level is the default, so it is never written.+ for v in [None, Some("0"), Some(""), Some("1;2"), Some("half")] {+ assert_eq!(parse_layer(v), 0, "{v:?}");+ }+ }++ #[test]+ fn a_bare_road_is_class_plus_osm_id_and_nothing_else() {+ // The common case at planet scale, and the reason every other property is+ // conditional.+ let f = feature(7, &road("residential"), Geometry::LineString(vec![(0.0, 0.0), (1.0, 1.0)]), 42);+ assert_eq!(keys(&f), ["class", "osm_id"]);+ assert!(rendered(&f).contains("\"osm_id\":\"way/42\""));+ }+}
scripts/maps/osm_ingest/src/tags.rs
diff --git a/scripts/maps/osm_ingest/src/tags.rs b/scripts/maps/osm_ingest/src/tags.rsindex bbc737aa8d..c810e7bf96 100644--- a/scripts/maps/osm_ingest/src/tags.rs+++ b/scripts/maps/osm_ingest/src/tags.rs@@ -74,6 +74,31 @@ pub fn parse_int_tag(value: Option<&str>) -> u32 { digits.parse::<u32>().unwrap_or(0) } +/// Carriageway width in metres from a `width`-style tag; 0 when absent or not a+/// positive number.+///+/// Bare values and an `m` suffix are metres, which is the OSM default. Feet are+/// the one other unit the tag is written in often enough to matter, and are the+/// reason this cannot just be [`parse_int_tag`]: US data carries `width=10'`, and+/// reading that as 10 metres would make a residential street wider than a+/// motorway.+pub fn parse_width_m(value: Option<&str>) -> f64 {+ let s = match value {+ Some(s) => s,+ None => return 0.0,+ };+ let (val, rest) = parse_leading_f64(s);+ if val <= 0.0 {+ return 0.0;+ }+ // Trimmed and case-folded: `"10 ft "` and `"10 FT"` are the same ten feet, and+ // reading either as ten metres is the exact mistake this exists to prevent.+ match rest.trim().to_ascii_lowercase().as_str() {+ "ft" | "feet" | "'" => val * 0.3048,+ _ => val,+ }+}+ /// Leading decimal number, plus the remainder of the string. Recognises the /// forms OSM `maxspeed` values actually use (`50`, `50.5`, `1e2`, `+50`). fn parse_leading_f64(s: &str) -> (f64, &str) {
scripts/maps/osm_ingest/src/testpbf.rs
diff --git a/scripts/maps/osm_ingest/src/testpbf.rs b/scripts/maps/osm_ingest/src/testpbf.rsindex bb77c34510..8572608f72 100644--- a/scripts/maps/osm_ingest/src/testpbf.rs+++ b/scripts/maps/osm_ingest/src/testpbf.rs@@ -373,7 +373,8 @@ pub const LAYERS_CAFE_NODE_ID: i64 = 1008; /// `highway=residential` + `maxspeed=25 mph`, the raw-string case. pub const MAXSPEED_WAY_ID: i64 = 3001; /// `highway=motorway` + `maxspeed=none`, which the graph's parser would collapse-/// to 0 and this layer must keep verbatim.+/// to 0 and this layer must keep verbatim. Also the `roads` layer's+/// fully-attributed way: a oneway bridge with lanes, turn lanes, width and layer. pub const MAXSPEED_NONE_WAY_ID: i64 = 3002; /// `highway=service` with no speed limit at all. The negative control. pub const NO_MAXSPEED_WAY_ID: i64 = 3003;@@ -471,6 +472,13 @@ pub fn layers_block() -> Vec<u8> { let k_colour = st.id("colour"); let k_boundary = st.id("boundary"); let k_admin_level = st.id("admin_level");+ // roads: the attributes the `roads` layer carries beyond geometry and class.+ let k_lanes = st.id("lanes");+ let k_turn_lanes_forward = st.id("turn:lanes:forward");+ let k_oneway = st.id("oneway");+ let k_width = st.id("width");+ let k_bridge = st.id("bridge");+ let k_layer = st.id("layer"); let v_speed_camera = st.id("speed_camera"); let v_surveillance = st.id("surveillance");@@ -503,6 +511,11 @@ pub fn layers_block() -> Vec<u8> { let v_six = st.id("6"); let v_oakland = st.id("Oakland"); let v_alameda = st.id("Alameda County");+ let v_three = st.id("3");+ let v_through_through_right = st.id("through|through|right");+ let v_yes = st.id("yes");+ let v_12m = st.id("12 m");+ let v_one = st.id("1"); let role_outer = st.id("outer"); let role_inner = st.id("inner"); let role_platform = st.id("platform");@@ -570,13 +583,21 @@ pub fn layers_block() -> Vec<u8> { ], &WAY_NODE_IDS[..3], ),- // maxspeed=none, plus a directional tag that must NOT win over it.+ // maxspeed=none, plus a directional tag that must NOT win over it. Also the+ // `roads` layer's fully-attributed way: a oneway bridge with lanes, turn+ // lanes, a width and a layer. way( MAXSPEED_NONE_WAY_ID, &[ (k_highway, v_motorway), (k_maxspeed, v_none), (k_maxspeed_forward, v_30mph),+ (k_lanes, v_three),+ (k_turn_lanes_forward, v_through_through_right),+ (k_oneway, v_yes),+ (k_width, v_12m),+ (k_bridge, v_yes),+ (k_layer, v_one), ], &WAY_NODE_IDS[2..5], ),
scripts/maps/publish_r2.sh
diff --git a/scripts/maps/publish_r2.sh b/scripts/maps/publish_r2.shindex 9a33033f14..720229d6a9 100644--- a/scripts/maps/publish_r2.sh+++ b/scripts/maps/publish_r2.sh@@ -19,7 +19,7 @@ set -euo pipefail # export R2_ACCESS_KEY_ID=... R2_SECRET_ACCESS_KEY=... # ./publish_r2.sh v5.pmtiles # -> s3://$R2_BUCKET/v5.pmtiles # ./publish_r2.sh v5.pmtiles --key v5.pmtiles-# ./publish_r2.sh v5.pmtiles maxspeed.pmtiles # multiple files (aux/siblings)+# ./publish_r2.sh v5.pmtiles poi_names.bin # multiple files (aux/siblings) # # Options: # --key NAME Remote object key for the FIRST file (default: its basename).@@ -29,7 +29,7 @@ set -euo pipefail # --dry-run Print what would happen; upload nothing. # -h|--help Show this help. #-# Note: v5.pmtiles BAKES the maxspeed layer in, so normally you only publish the+# Note: v5.pmtiles BAKES every overlay layer in, so normally you only publish the # single v5.pmtiles. The multi-file form exists for aux/sibling artifacts if you # ever build them separately.