Repository navigation
feat: open area routing - #7161
Conversation
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
|
Had a first look at the change. First of all, great feature! I think this has been on the todo list for more than 10 years 😀 The main question I have is that we should probably own the Dijkstra implementation that is used and not fall back to boost. |
|
Do we have a general dislike for boost? Just asking ... |
Perhaps 😉 Also, routing is our expertise and we should own all routing logic. |
|
Dijkstra in itself is trivial to implement. The hardest piece is the priority queue, if we don't want to take the one in boost. They use a 4-ary heap. A binary heap will do for our problem sizes. I will look into this. |
|
The good news is that heap implementations already exist in our code base:
|
|
just tweaked the settings s.t. GitHub Actions should now run automatically on push. |
|
I have now implemented Dijkstra and a binary heap that works with it. The d-ary heap in Shouldn't we drop / update the macos-x64 build since it is based on apple-clang-14? All other builds use clang >= 16. |
a15ab31 to
d89c932
Compare
This comment was marked as outdated.
This comment was marked as outdated.
a36aa05 to
d15c029
Compare
|
@DennisOSRM I think this is ready for review. |
| const extractor::ManeuverOverrideRelationParser &) override final | ||
| { | ||
| } | ||
|
|
There was a problem hiding this comment.
TODO
- entrances to buildings along the perimeter of the area,
- PT stations in the middle of the area
This could also include other routable points like a bridge/tunnel/stairs starting in the middle of an area.
For example: this, otherwise unconnected, bridge starting/ending in two parking lots (OSM):

Further, we could include POIs in the middle of routable areas. Perhaps include specific classes like tourism=artwork and amenity=drinking_water, or more simply anything with a name= tag?
My inbuilt assumption is mappers will lessen the use of artificial routes within a routable area, once apps support area routing, increasing the need of routing to individual POIs.
(comment pinned to a line of code to allow for threaded discussion)
There was a problem hiding this comment.
The main difficulty is to get all information into one place: in a typical OSM file all nodes come first, then all ways, then all relations. When you get to the area relation in the OSM file the node tags are long gone, so either you save all interesting nodes with their tags in memory (expensive in memory) or you save all interesting relations and make a second pass over the OSM file to get all the nodes and tags (less expensive in memory but expensive in cpu).
Further, if you want to include nodes that are 'inside' the area but not members of the area relation, you have to perform point-in-polygon tests for all nodes against all interesting areas. That means building an rtree of areas and a second pass over all nodes testing them all (very expensive in cpu).
There was a problem hiding this comment.
What percent of OSM files will the meshing run on? And what percent will have POIs inside? Perhaps we just have to keep the happy path fast, and the other to be bounded and reasonable?
Could do:
- Run all steps including the new area meshing (as your PR does currently)
- If meshing occurred – breaking off from the happy path
- Create lat/lng bounding box for each meshed area (fast to check against; granted some corner cases at the poles and wrapping of the world)
- Ignore any mesh area that is trivial small, like <3m width and <3m height, letting free space routing handle the case
- Second pass:
- Filter nodes:
- Fast filter: ignore nodes not in a one of the meshes' bounding boxes
- Slower filter: full check for point-in-polygon
- Slower filter: ignore nodes that are with-in 3m of an existing/new path in the mesh, letting free space routing handle the point
- Limiting step: keep at max ~10k nodes that pass the filters (further reduced later)
- Perhaps prioritizing keeping nodes with
name=or other likely source/destination POI?
- Perhaps prioritizing keeping nodes with
- Store remaining nodes, then gather ways, relations
- Filter to POIs w/
name=tags or other likely source/destination POI?
- Filter to POIs w/
- Limiting step: keep at max ~100 nodes (not POIs) for each mesh areas
- For any mesh area that we found POIs inside, rerun the meshing
- Filter nodes:
Upside: happy path is fast, low and bounded memory, bounded compute
Downside: need to remesh if new POIs are added inside of a mesh area, two passes when area mesh code runs
There was a problem hiding this comment.
This could also include other routable points like a bridge/tunnel/stairs starting in the middle of an area.
For example: this, otherwise unconnected, bridge starting/ending in two parking lots (OSM):
As a sidenote because it was used as an example, amenity=parking areas cannot safely be assumed to be fully traversible. Very often the mapped parking lot area also includes grassy medians, etc... that cannot be walked/driven over.
The parking lot in the example isn't even mapped as an area, just as single nodes, so this wouldn't work there either way.
Attempting to automatically connect and route between two otherwise unconnected ways just because they are in close proximity but that are not known to lie in a routable area is absolutely not a good idea. That way lies madness.
There was a problem hiding this comment.
Good list, and the unconnected bridge between two parking lots is a case the mesher has nothing to say about today. Entry points are only where another way meets the perimeter, so a way starting in the middle of an area is invisible to it, and POIs are not considered at all. Recorded in #7683 as a follow-up.
|
It's great that “area routing” is getting some attention again. The algorithms and implementations are available (see, for example, this comment and the follow-up posts seven years(!) ago)... I was recently made aware of this missing feature when I was testing my “vampire mode” - an OSRM profile for pedestrians that prefers shady streets... |
|
Taking full advantage of this may require new tags for areas where it's not clear whether they are traversable or not (for example a |
TheMarex
left a comment
There was a problem hiding this comment.
I've not completed the review yet, mostly focused on the structural things. Haven't looked at the algorithmic side at all so far. Overall really great contribution - but a large change with a lot of API implications lua-side so I'm trying to be a bit stricter. Let me know if you are interested in further evolving this in this PR (or if you have the time), otherwise we can figure out how to do that on master.
| initial test": | ||
|
|
||
| ```lua | ||
| function process_way(profile, way, result, relations) |
There was a problem hiding this comment.
I'm wondering it it would be better to have an additional process_area. Right now the flow is a bit weird IMHO because we let this code decide which way/relation is considered an area, which all the consequences of messing that up. That would also safe us from having to expose the area_manager to lua at all from what I can tell.
There was a problem hiding this comment.
Agreed that the current flow reads oddly, with areas registered from process_way and process_relation rather than from something of their own. It is a profile API change, so it wants its own discussion rather than being folded in here. Recorded in #7683.
| | d | f | 4:1:2:3:6 | 248.4 | Avoids the alley d,e,f | | ||
|
|
||
| | from | to | a:nodes | weight | # | | ||
| | a | f | abcf | 196.2 | Avoids d,e,f | |
There was a problem hiding this comment.
Looks like an unrelated change? 1:2:3:6 -> names?
There was a problem hiding this comment.
Not unrelated, though the connection is easy to miss. This branch changes the route step to render a:nodes as node names instead of raw ids (features/support/shared_steps.js), so every existing assertion on that column had to be rewritten: 32 rows across four files, of which alley.feature is three. The weights are unchanged.
The rename earns its place here because meshing an area creates virtual nodes whose ids move whenever the mesh changes, so numeric assertions on them would be unstable.
It left a gap, though. features/step_definitions/matching.js resolves the same column by its own path and was not changed, so four cells in features/testbot/matching.feature still assert numeric ids and still pass. Two conventions for one column, now recorded in #7683.
| { | ||
| std::int64_t d_lon = static_cast<std::int32_t>(lhs.lon - rhs.lon); | ||
| std::int64_t d_lat = static_cast<std::int32_t>(lhs.lat - rhs.lat); | ||
| std::int64_t d_lon = from_alias<int64_t>(lhs.lon) - from_alias<int64_t>(rhs.lon); |
There was a problem hiding this comment.
Can you explain what is going on here? FYI we don't use the full range of the 32bits - only ~29 (28bits for the magnitude 1bit for the sign) are actually required for the encoding. It should be static cast to 64bit though I guess.
There was a problem hiding this comment.
It is safer from overflow.
There was a problem hiding this comment.
It widens each coordinate to 64 bits before the subtraction rather than after it, and drops a redundant cast on the result. Previously the difference was computed as an alias of int32_t and only then assigned to an int64_t.
Your reading is right that it cannot overflow in practice, since only about 29 bits are in use, so this is robustness and clarity rather than a fix for an observed defect. And yes, casting to 64 bit is exactly what it now does.
| &ProfileProperties::weight_precision, | ||
| "weight_name", | ||
| sol::property(&ProfileProperties::SetWeightName, &ProfileProperties::GetWeightName), | ||
| sol::property(&ProfileProperties::GetWeightName, &ProfileProperties::SetWeightName), |
There was a problem hiding this comment.
This is interesting - I'm fairly sure we reference this already in the car profile for example. So why does it work now? 🤔
There was a problem hiding this comment.
The two arguments were the wrong way round. sol::property takes the getter first and the setter second, and this had SetWeightName in the read slot and GetWeightName in the write slot.
It works today because nothing reaches it. All the profiles in the repo are api_version = 4, and for those the properties come back from setup() as a plain Lua table that is read key by key (scripting_environment_lua.cpp:738 for weight_name), so the usertype accessor is never used. A v1 to v3 profile touching properties.weight_name through the usertype object would have hit it.
| &RasterContainer::GetRasterInterpolateFromSource); | ||
|
|
||
| // the first parameter to the LUA process_* functions | ||
| // FIXME: shouldn't all of this be readonly? |
There was a problem hiding this comment.
V1 profiles have a global properties object. We kind of missed an opportunity with 6.0 to do some actual cleanup here which is sad.
There was a problem hiding this comment.
Agreed, and the split is awkward: v4 reads the same fields twice over, once through this usertype and once as a plain table further down. Not something to unpick here, but worth doing when the profile API is next opened up.
| @@ -0,0 +1,227 @@ | |||
| #ifndef OSRM_EXTRACTOR_AREA_INDEX_PRIORITY_QUEUE_HPP | |||
There was a problem hiding this comment.
Can you add more context why we can't use query_heap.hpp here? While the implementation is slightly simpler (no Data) it should be almost identical in function. One advantage of QueryHeap is that you do not need a visited array because it supports a WasInserted operation.
There was a problem hiding this comment.
I couldn't figure out how to use it. There's not a single comment in that whole file. And I need key update operations: the heap is sorted by distance from the sweep centerpoint and as you sweep the ray around the center obstacles don't maintain the same distance.
There was a problem hiding this comment.
Fair question, and it is not answered in the header. Carried over to #7683: either the header says why query_heap does not fit, or the area code uses it.
| namespace osrm::extractor::area | ||
| { | ||
|
|
||
| namespace bg = boost::geometry; |
There was a problem hiding this comment.
In header files please always refer to the full namespace and not create aliases. Can get really confusing with other headers doing this.
There was a problem hiding this comment.
Still open. include/extractor/area/typedefs.hpp keeps the OsmiumPolygon, OsmiumMultiPolygon and NodeRefSet aliases, and has a using namespace osrm::extractor::area; inside the boost::geometry::traits block, which leaks into every translation unit that includes it. The second of those is the one worth removing first. Recorded in #7683.
There was a problem hiding this comment.
Fixed in #7687, which is small and independent: the two using-directives are gone, VisibilityGraph::Vertex is named in full inside the traits block, and COEFF moves out of boost::geometry::traits and becomes osrm::extractor::area::MERCATOR_COEFF.
| { | ||
| if (!poly_segments.contains(s)) | ||
| { | ||
| double weight = bg::distance(s.first, s.second); |
There was a problem hiding this comment.
We have our own haversine implementation in utils/coordinate_calculation.hpp - I suspect you can probably get of some (all?) of the boost geometry dependencies?
There was a problem hiding this comment.
Still open, and there is a wrinkle worth recording before anyone changes it. AreaMesher::run_dijkstra weights edges with boost::geometry::distance, which for these coordinates yields an angle rather than a length. Only the ratios matter to Dijkstra so the routes come out right, but swapping in the haversine from coordinate_calculation rescales every weight, and Dijkstra::distance_epsilon is an absolute tolerance. There is a note in docs/areas.md; also recorded in #7683.
There was a problem hiding this comment.
Pull request overview
This PR adds experimental pedestrian area routing functionality to OSRM. The feature enables routing across the interior of pedestrian areas (such as plazas and squares) by generating virtual ways between entry points using a visibility graph algorithm combined with Dijkstra's shortest path algorithm.
Changes:
- Implemented area meshing using visibility graphs and Dijkstra's algorithm to generate routing ways across pedestrian areas
- Added comprehensive test coverage including unit tests for core algorithms and integration tests for area routing scenarios
- Updated the Lua scripting API to support area registration and processing via a new
process_relationfunction andarea_managerglobal
Reviewed changes
Copilot reviewed 45 out of 45 changed files in this pull request and generated 5 comments.
Show a summary per file
| File | Description |
|---|---|
| src/extractor/area/* | Core area meshing implementation including visibility graph, Dijkstra, and area management |
| include/extractor/area/* | Header files defining typedefs, algorithms, and area manager interface |
| src/extractor/scripting_environment_lua.cpp | Extended Lua API with area manager support and new OSMObject base class |
| src/extractor/extraction_relation.cpp | New relation container implementation with flyweight pattern for memory efficiency |
| src/extractor/extractor.cpp | Integrated area processing pipeline into extraction workflow |
| unit_tests/extractor/area/* | Comprehensive unit tests for util functions, priority queue, and Dijkstra |
| features/foot/area_mesh.feature | Integration tests for closed way and multipolygon area routing |
| docs/areas.md, docs/lua-types.dox | Complete documentation for the new feature |
| profiles/foot_area.lua | Example profile demonstrating area routing configuration |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Co-authored-by: DennisOSRM <[email protected]>
Co-authored-by: DennisOSRM <[email protected]>
Ruben-VandeVelde
left a comment
There was a problem hiding this comment.
This would be great to have! A drive-by comment below
209f53d to
78d5956
Compare
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #7161 +/- ##
==========================================
+ Coverage 90.78% 94.36% +3.58%
==========================================
Files 485 503 +18
Lines 37845 39088 +1243
==========================================
+ Hits 34359 36887 +2528
+ Misses 3486 2201 -1285 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Pedestrian areas -- squares, plazas and the like -- were opaque to the router: a way could enter one and a way could leave it, but nothing connected the two, so a route either detoured around the area or failed outright. Mesh each area instead. For every area the extractor determines the nodes by which it can be entered or exited, builds a visibility graph over those nodes plus the vertices that can block a line of sight, and runs Dijkstra over that graph to keep only the edges lying on a shortest path between a pair of entry points. The surviving edges are emitted as virtual ways tagged osrm:virtual=yes carrying the area's own tags, so the rest of the pipeline treats them like any other way. Areas reached through a multipolygon relation inherit that relation's membership, so a hiking route crossing a plaza stays intact. The visibility graph follows the rotational sweep of de Berg, Cheong, van Kreveld and Overmars, Computational Geometry, 3rd ed., chapter 15, adapted for an observer standing on the boundary rather than outside the obstacles. Coordinates are projected to OSM Mercator and held as integers so the geometry predicates do not depend on floating-point noise. Comes with the foot_area profile, the area_mesh cucumber feature covering closed ways, multipolygons with holes and a multi-hole area, and unit tests for the Dijkstra and indexed priority queue building blocks.
b23f4a3 to
2a00cc1
Compare
The mesher could emit ways that run straight through the very obstacles they are meant to route around. On GCC/Linux CI the scenario "Foot - Route across a complex multipolygon area" failed on exactly that, byte-identically in every run, while every clang build passed. Differential fuzzing of the sweep against a brute-force reference shows the defect was never compiler-specific: on 400 random polygons with holes it ran 41 lines of sight through an obstacle on 37 of them. The scenario simply sits near the tipping point and GCC tips it over. Three defects, all the same kind: a result that depends on an ordering nothing maintains. - The sweep status tau was kept ordered by distance along the sweep ray and only its nearest edge was tested, as the textbook describes. That ordering cannot be maintained here. Distances were refreshed only when the pending queue was non-empty, and an edge whose ray/segment test hits an endpoint -- which happens at every sweep step, and again at every triple collinear with the observer -- silently kept a stale distance. One stale distance puts a non-blocking edge in front, and the nearest-edge test then reports a vertex as visible although a farther edge in tau does block it. Keep tau unordered and test every edge in it. Both answer the same question, but the unordered variant does not depend on the distances at all: intersect() is a segment-segment test, so an edge in tau can only reject w if it genuinely crosses observer -> w, which means the change can only remove false "visible" answers, never introduce false "invisible" ones. tau holds just the edges the ray currently crosses -- a handful even for large polygons -- so scanning it costs nothing. With no ordering left to maintain the pending-edge queue goes away too, and with it the failure mode it introduced: an edge whose deferred insertion test kept failing never blocked anything. - util.hpp documents that intersect() excludes endpoints, and visible() relied on it -- an edge enters tau at its first endpoint and stays until the sweep reaches the second, so tau routinely holds edges incident to the very vertex being tested. intersect() cannot be relied on to notice: it solves for the segment parameters, and a shared endpoint comes out at s = t = 0.99999999999995703437 rather than exactly 1. The endpoint is then mistaken for a proper crossing and a perfectly good line of sight vanishes in both directions, dropping it from the graph. Skip edges sharing an endpoint with the segment under test, comparing the projected integer coordinates so a node appearing in two rings is covered as well. The tau initialization guard was wrong the other way round. The edge under consideration there is (v, v->next), so it is adjacent to the observer exactly when v->next is the observer; v->prev being the observer makes v the observer's successor, whose outgoing edge does not touch the observer at all -- an ordinary obstacle that was being dropped from the initial tau. - Vertex::operator< compared angle and distance within an epsilon, and the Dijkstra priority queue compared distances the same way. Tolerant equality is not transitive, so neither was a strict weak ordering and std::sort on the first was undefined behaviour. Both now compare exactly and fall back to an id, which is a total order and just as deterministic. run() now looks the observer up in the polygon and passes that vertex to visible_vertices, instead of letting the implicit conversion from osmium::NodeRef materialize a temporary. The guard keeping observer-adjacent edges out of tau compares &observer against the ring links and could never match a temporary, so it was dead code; it is now live. After all three the sweep agrees with the reference on 3500 random polygons across eight seeds, up to 14 outer vertices and 5 holes. Also register the open-area files as optional in StorageConfig, refresh the vcpkg dependencies, extend the area unit tests with the invariants the above relies on, and address review nits: drop the leftover name lookups whose only use was a debug log line, use an empty default for a missing name tag as the rest of the code does, and fix a typo in the alley feature.
2a00cc1 to
8578e7a
Compare
The area module had no unit tests for its two largest pieces, and could not
have had any: VisibilityGraph defines its member functions in the header
without inline, so the header can only ever be included by one translation
unit. Since the unit test binary links osrm_extract, which already contains
those symbols by way of area_mesher.cpp, a test including the header was a
duplicate symbol link error.
Move the definitions into src/extractor/area/visibility_graph.cpp. That also
moves the Mercator projection object out of an anonymous namespace in the
header, where every includer would have got a copy of its own and the
implicitly inline Vertex constructor referred to an object with internal
linkage.
With that out of the way, add tests for the visibility graph, the mesher and
the area manager. Line coverage of the area module:
src/extractor/area/visibility_graph.cpp 98.4% (was untestable)
src/extractor/area/area_mesher.cpp 94.5% (was untestable)
src/extractor/area/area_manager.cpp 68.3% (was 0%)
include/extractor/area/util.hpp 97.4%
include/extractor/area/dijkstra.hpp 92.7%
include/extractor/area/index_priority_queue.hpp 100%
What is left uncovered in the area manager is after_way() and
complete_relation(), which need libosmium's two pass machinery around them and
are covered by the cucumber feature instead.
Two of the tests pin down the defects that made the mesher route through
obstacles, so a regression shows up as a unit test failure rather than as a
routing test failure in one compiler's CI job.
The tests immediately found a third one. write_debug() writes the visibility
graph and the meshed ways to a file for inspection, but did so through the
same helper that emits the real ways, so it consumed way ids and incremented
added_ways for output nobody sees. A debug build therefore produced different
way ids and a way count roughly five times the real one -- for the test area,
21 against 4. Save and restore both around the debug write.
Also drop the `bg` and `srs` namespace aliases from the headers in favour of
the full boost::geometry namespace, as requested in review, and record the
trade-offs the module deliberately makes -- the unordered sweep status, the
remaining Boost.Geometry dependency and its interaction with Dijkstra's
absolute epsilon, and the reasons for the module's own priority queue -- in
docs/areas.md and next to the code they concern.
DennisOSRM
left a comment
There was a problem hiding this comment.
Approving to move changes to master. More follow-up changes will come to PRs afterwards.
|
Merged. Thank you, @MarcelloPerathoner, for this contribution and for your patience: Routing across pedestrian areas has been asked for since #64, and the visibility graph Work continues in follow-ups: snapping a coordinate that falls inside an area, pruning |
Both traits blocks opened with `using namespace osrm::extractor::area;`, which every translation unit that includes the header inherits inside `boost::geometry::traits`. The one in typedefs.hpp was not needed at all: every specialisation in that block is on an `osmium::` type. The one in visibility_graph.hpp is replaced by naming `osrm::extractor::area::VisibilityGraph::Vertex` in full. `COEFF` moves out with it. It was declared in `boost::geometry::traits`, so a name that generic was being added to a namespace we do not own; it is now `osrm::extractor::area::MERCATOR_COEFF`, next to the `Vertex::point` it describes. Addresses a review comment on #7161.
|
Wow, this is legendary work! |
… place (#7695) Dijkstra::run could leave a cycle in the predecessor array, and run_dijkstra walks that array with no bound, so extraction ran forever: no output, no error, nothing to look at. Ile-de-France did not finish in 33 minutes. With this it takes 1 minute 57 seconds. The tie-break that keeps the choice of predecessor deterministic when two paths are equally long had no notion of a settled vertex, so it would rewrite the predecessor of a vertex whose distance was decided long ago. That needs an edge of no length between two vertices the same distance from the source, which is ordinary input: plaza rings routinely carry two nodes mapped at the same place, and the ring edge between them weighs zero. Both vertices then settle together and each becomes a better predecessor for the other than the source is, so each ends up pointing at the other. Fixed at the source with a settled set. That also makes the result acyclic by construction rather than by luck: a vertex only ever points at one that settled before it did, so following predecessors strictly decreases settle time and has to reach the root. The tie-break still runs, and still picks the lower vertex, so which of two equal paths wins is unchanged. run_dijkstra's walk is bounded as well. A tree of n vertices has no path longer than n edges, and that loop runs over every vertex of every area in the input, where the cost of being wrong is an extraction that never ends. It now says so and moves on. Found by bisecting: this has been present since areas were first meshed in #7161. One 2 MB tile of Ile-de-France produced 43 of these cycles.

This PR provides routing over areas.
It builds a visibility graph of the area, then runs dijkstra from each entry point to reduce the number of edges, then adds the remaining edges as ways to the router.
From the OSM site, without area routing, following mapped-for-the-router ways:
With area routing, also note the better directions:
Documentation
Issue
Fixes #64 #2655 #7146
Tasklist
TODO
The two follow-up commits on this branch (
8578e7aee,e2c57a772) were written with AIassistance: Claude Code, Claude Opus 5 🤖
Known defects and the review points deferred to follow-ups are tracked in #7683.