Skip to content

[GSoC] Pedestrian area routing: Build area polygons and generate medial axis - #6195

Merged
chrstnbwnkl merged 20 commits into
masterfrom
pedestrian-area-ways-clean
Aug 10, 2026
Merged

chrstnbwnkl merged 20 commits into
masterfrom
pedestrian-area-ways-clean

Conversation

@pacoalbacetec

@pacoalbacetec pacoalbacetec commented Jul 9, 2026 •

Copy link
Copy Markdown
Collaborator

Continuation of #6127

What is this PR about

Enables pedestrian routing through pedestrian areas (highway=pedestrian + area=yes). For each area it generates a traversal skeleton along the medial axis and connects the area's entrances to it, so a pedestrian can cross a square directly.

Implementation

  • ParseAreaWays: areas tagged only on the relation have member ways with no routable tags, so lua drops them during regular way parsing. This pass recovers the ways referenced by area relations and marks them so their geometry survives to the builder.

  • BuildAreas: assembles each area's polygon/s from its member ways (including inner members), computes the medial axis via a Voronoi diagram of the densified boundary, prunes branches, connects each entrance to the nearest skeleton vertex it can reach without leaving the polygon, and materialises the result as synthetic footways. ConstructEdges then turns those into edges like any other way.

  • Synthetic ids: generated ways and nodes get ids above the highest real way and node ids, so they never collide with real OSM ids, and are kept out of the final tiles.

Decisions we made

  • Areas below a size threshold keep their routable perimeter instead of a traversal.
  • Entrances within a few meters that can see each other through the area are merged, to avoid redundant connections.
  • Areas that already have pedestrian paths mapped inside are left untouched.
  • Densify tolerance at 4m, a speed/detail trade-off validated visually.

Performance

BuildAreas on Germany started at ~114s. With GEOSPrepare on the Voronoi filter
and the two-pass node collection it dropped to ~65s, and raising the densify
tolerance takes it further:
2m -> ~33s
4m -> ~19s
Roughly 6 minutes projected for a full Europe build.

Notes

This is a fully functional version that we've tested on real data (Germany and
Europe builds) with really good results. We've marked a number of TODOs in the code for things that work well but could be improved further down the line.

Here's a before/after from Plaza de Santo Domingo in Murcia, Spain, without the feature the route goes around the square, with it it crosses straight through:

Before:
githubOFF

After:
githubON

A note on stability

This is a functional first version. It works well and noticeably improves routing
across pedestrian areas, though there are still things that could be refined and
improved further down the line (marked as TODOs in the code). None of that affects
existing behaviour: the whole feature sits behind the mjolnir.pedestrian_areas
config option and is off by default, so unless it's explicitly enabled Valhalla
builds and routes exactly as it does today.

Comment thread valhalla/mjolnir/util.h

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added two new build stages. kParseAreaWays and kBuildAreas

Comment thread src/mjolnir/util.cc
Comment on lines +728 to +742
// Second pass over the ways to collect the geometry of ways that
// are members of pedestrian area relations
if (start_stage <= BuildStage::kParseAreaWays && BuildStage::kParseAreaWays <= end_stage) {
if (config.get<bool>("mjolnir.pedestrian_areas", false)) {
PBFGraphParser::ParseAreaWays(config.get_child("mjolnir"), input_files, ways_bin, way_nodes_bin,
osm_data);

// Write the OSMData to files if the end stage is less than enhancing
if (end_stage <= BuildStage::kEnhance) {
osm_data.write_to_temp_files(tile_dir);
}
}
log_stage(BuildStage::kParseAreaWays);
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Runs ParseAreaWays only when the pedestrian_areas option is on. This stage is needed because members ways of pedestrian area relations, weren't parsed because the order of the stages

Comment thread src/mjolnir/util.cc
Comment on lines +757 to +769
// Builds pedestrian areas
if (start_stage <= BuildStage::kBuildAreas && BuildStage::kBuildAreas <= end_stage) {
if (config.get<bool>("mjolnir.pedestrian_areas", false)) {
AreaBuilder::BuildAreas(config.get_child("mjolnir"), ways_bin, way_nodes_bin, osm_data);

// Write the OSMData to files if the end stage is less than enhancing
if (end_stage <= BuildStage::kEnhance) {
osm_data.write_to_temp_files(tile_dir);
}
}
log_stage(BuildStage::kBuildAreas);
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Calls, AreaBuilder::BuildAreas, gated behind the pedestrian_areas option. This is where polygons and medial axis get built, before kContructEdges

Comment thread valhalla/mjolnir/pbfgraphparser.h Outdated
Comment on lines +52 to +58
// TODO: doxygen comment
static void ParseAreaWays(const boost::property_tree::ptree& pt,
const std::vector<std::string>& input_files,
const std::string& ways_file,
const std::string& way_nodes_file,
OSMData& osmdata);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Second selective pass over the ways. Declared static like the other Parse* methods. It reads area_relations to know which member ways to collect


#include <string>

typedef struct GEOSGeom_t GEOSGeometry;

@pacoalbacetec pacoalbacetec Jul 9, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

forward declaration so we don't have geos_c.h in the header

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why make GenerateMedialAxis a member of AreaBuilder anyway? I'd suggest to just define it as a free standing function in an anonymous namespace in the source file.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know we have this weird convention to wrap the functions that represent a build stage into a class, but feel free to break that pattern if it does not make sense to you.

Comment on lines +5347 to +5420
void PBFGraphParser::ParseAreaWays(const boost::property_tree::ptree& pt,
const std::vector<std::string>& input_files,
const std::string& ways_file,
const std::string& way_nodes_file,
OSMData& osmdata) {
SCOPED_TIMER();

// we need area_relations to know which ways to collect, read it from disk if needed
if (!osmdata.initialized)
osmdata.read_from_temp_files(pt.get<std::string>("tile_dir"));

// nothing to do if there are no area relations
if (osmdata.area_relations.empty())
return;

// collect the way ids we need (outer and inner members of the area relations)
std::unordered_set<uint64_t> needed_way_ids;
for (const auto& entry : osmdata.area_relations)
needed_way_ids.insert(entry.second.way_id);

LOG_INFO("Parsing area ways... looking for " + std::to_string(needed_way_ids.size()) + " ways");

// open the existing ways/way_nodes files
sequence<OSMWay> ways(ways_file, false);
sequence<OSMWayNode> way_nodes(way_nodes_file, false);

uint32_t found = 0;
for (const auto& file : input_files) {
osmium::io::Reader reader(file, osmium::osm_entity_bits::way);
while (osmium::memory::Buffer buffer = reader.read()) {
for (const auto& item : buffer) {
const auto& osm_way = static_cast<const osmium::Way&>(item);

// skip ways we don't care about
if (!needed_way_ids.count(static_cast<uint64_t>(osm_way.id())))
continue;

// gather the node ids of this way
std::vector<uint64_t> nodes;
nodes.reserve(osm_way.nodes().size());
for (const auto& node : osm_way.nodes()) {
nodes.push_back(node.ref());
}

// Do not add ways with < 2 nodes. Log error or add to a problem list
// TODO - find out if we do need these, why they exist...
if (nodes.size() < 2)
continue;

// the index this way will have in the ways file
uint32_t way_index = static_cast<uint32_t>(ways.size());

// store each node as a way node referencing this way by index
for (size_t i = 0; i < nodes.size(); ++i) {
OSMNode osm_node{nodes[i]};
osm_node.intersection_ = i == 0 || i == nodes.size() - 1;
way_nodes.push_back({osm_node, way_index, static_cast<uint32_t>(i)});
}

// build the way with the area bit set, no lua transform needed
OSMWay w{static_cast<uint64_t>(osm_way.id())};
w.set_node_count(nodes.size());
w.set_area(true);
ways.push_back(w);
++found;
}
}
reader.close();
}

LOG_INFO("Finished parsing area ways, found " + std::to_string(found) + " of " +
std::to_string(needed_way_ids.size()));
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Second pass over the PBF but without lua. We only keep those ways whose id is in our relation ways set. Appends each collected way to ways.bin and way_nodes.bin with the area bit set. The coordinates get filled in later during ParseNodes

Comment on lines +68 to +114
}

TEST(area_routing, area_member_ways_collected) {
const std::string ascii_map = R"(
A----B
| |
D----C
)";

// the member way has no routable tags, so lua discards it during ParseWays
const gurka::ways ways = {
{"ABCDA", {}},
};

// the relation carries the area tags
const gurka::relations relations = {
{{{
{gurka::way_member, "ABCDA", "outer"},
}},
{{"type", "multipolygon"}, {"highway", "pedestrian"}, {"area", "yes"}}},
};

const auto layout = gurka::detail::map_to_coordinates(ascii_map, 100);
const std::string workdir = "test/data/gurka_area_members";

// run up to ParseRelations, the member way was discarded by lua
auto map =
gurka::buildtiles(layout, ways, {}, relations, workdir,
{{"mjolnir.concurrency", "1"}, {"mjolnir.pedestrian_areas", "true"}},
mjolnir::BuildStage::kInitialize, mjolnir::BuildStage::kParseRelations);

EXPECT_THROW(gurka::findWay(map, "ABCDA"), std::runtime_error);

// run the new stage on top of the partial build
gurka::buildtiles(layout, ways, {}, relations, workdir,
{{"mjolnir.concurrency", "1"}, {"mjolnir.pedestrian_areas", "true"}},
mjolnir::BuildStage::kParseAreaWays, mjolnir::BuildStage::kParseAreaWays);

// now the member way was collected with the area bit set
auto way = gurka::findWay(map, "ABCDA");
EXPECT_TRUE(way.area());

// its geometry was collected too. Coords aren't yet since ParseNodes runs after ParseAreaWays
auto b_nodes = gurka::findWayNodes(map, "B");
ASSERT_FALSE(b_nodes.empty());
EXPECT_FALSE(b_nodes.front().node.latlng().IsValid());
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verifies kParseAreaWays.
Phase 1 runs up to kParseRelations: member way was discarded so we check it's not in ways.bin
Phase 2 runs kParseAreaWays: And now we see the way is there and also with the area bit
We also check that coordinates aren't set yet since kParseNodes runs later.

Comment on lines +116 to +160
TEST(area_routing, area_relations_collected) {
const std::string ascii_map = R"(
A----B
| |
D----C
)";

// the member way has no routable tags, so lua discards it during ParseWays
const gurka::ways ways = {
{"ABCDA", {}},
};

// the relation carries the area tags
const gurka::relations relations = {
{{{
{gurka::way_member, "ABCDA", "outer"},
}},
{{"type", "multipolygon"}, {"highway", "pedestrian"}, {"area", "yes"}}},
};

const auto layout = gurka::detail::map_to_coordinates(ascii_map, 100);
const std::string workdir = "test/data/gurka_area_relations";

// run up to ParseRelations so area_relations is filled and written to temp files
auto map =
gurka::buildtiles(layout, ways, {}, relations, workdir,
{{"mjolnir.concurrency", "1"}, {"mjolnir.pedestrian_areas", "true"}},
mjolnir::BuildStage::kInitialize, mjolnir::BuildStage::kParseRelations);

// load the OSMData from the temp files and check the area relation members
const auto tile_dir = map.config.get<std::string>("mjolnir.tile_dir");
mjolnir::OSMData osmdata{};
osmdata.read_from_temp_files(tile_dir);

// the area relation collected its member way as an outer
ASSERT_FALSE(osmdata.area_relations.empty());
const auto way_id = map.way_osm_ids.at("ABCDA");
bool found_outer = false;
for (const auto& [rel_id, member] : osmdata.area_relations) {
if (member.way_id == way_id && member.is_outer) {
found_outer = true;
}
}
EXPECT_TRUE(found_outer);
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verifies that area_relations collects the members with the correct outer/inner role. This covers the coverage gap from the previous PR

Comment thread test/gurka/test_area_routing.cc Outdated
Comment on lines +162 to +193
TEST(area_routing, area_polygons_assembled) {
const std::string ascii_map = R"(
A-----------------B
| |
| E----F I-J |
| | | | | |
| G----H K-L |
| |
D-----------------C
)";

const gurka::ways ways = {
{"ABCDA", {}},
{"EFHGE", {}},
{"IJLKI", {}},
};
const gurka::relations relations = {
{{{
{gurka::way_member, "ABCDA", "outer"},
{gurka::way_member, "EFHGE", "inner"},
{gurka::way_member, "IJLKI", "inner"},
}},
{{"type", "multipolygon"}, {"highway", "pedestrian"}, {"area", "yes"}}},
};

const auto layout = gurka::detail::map_to_coordinates(ascii_map, 10);

auto map = gurka::buildtiles(layout, ways, {}, relations, "test/data/gurka_area_polygons",
{{"mjolnir.concurrency", "1"}, {"mjolnir.pedestrian_areas", "true"}},
mjolnir::BuildStage::kInitialize, mjolnir::BuildStage::kBuildAreas);

SUCCEED();

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verifies the polygon assembly with holes, since kBuildAreas only lives inside of the function yet, this test is useless unless there are prints in the areabuilder.cc code that let us see data as the number of polygons, holes...

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for example, with the prints we can see that it works fine:

3 ways -> 3 raw polygon(s) -> 1 final polygon(s)
   polygon 0 has 2 hole(s)

and for the first test that also runs up to this stage:

1 ways -> 1 raw polygon(s) -> 1 final polygon(s)
   polygon 0 has 0 hole(s)


constexpr double kMinAreaSquareMeters = 100.0;
constexpr double kDensifyToleranceMeters = 1.0;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kMinAreaSquareMeters : areas smaller than this skip the medial axis
kDensifyToleranceMeters : max spacing between points when densifying the boundary

Comment on lines +27 to +31
// way_id > relation_id, to know which relation each area way belongs to
std::unordered_map<uint64_t, uint64_t> way_to_relation;
for (const auto& entry : osmdata.area_relations) {
way_to_relation[entry.second.way_id] = entry.first;
}

@pacoalbacetec pacoalbacetec Jul 9, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maps each member way id to its relation id, so we know to which area each way belongs to

Comment thread src/mjolnir/areabuilder.cc Outdated
Comment on lines +38 to +45
// grab the way and its first node
size_t current_way_node_index = 0;
while (current_way_node_index < way_nodes.size()) {
auto way_node = *way_nodes[current_way_node_index];
const auto way = *ways[way_node.way_index];
const auto first_way_node_index = current_way_node_index;
const auto last_way_node_index =
first_way_node_index + way.node_count() - way_node.way_shape_node_index - 1;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

walks the way nodes the same way as kConstructEdges does, way by way, using node_count to find the way's node range.

Comment thread src/mjolnir/areabuilder.cc Outdated
Comment on lines +47 to +58
// if it is an area, collect and store its shape
if (way.area()) {
std::vector<midgard::PointLL> shape;
for (auto node_idx = first_way_node_index; node_idx <= last_way_node_index; node_idx++) {
shape.push_back((*way_nodes[node_idx]).node.latlng());
}
auto it = way_to_relation.find(way.way_id());
uint64_t area_key = (it != way_to_relation.end()) ? it->second : way.way_id();
area_ways[area_key].push_back(std::move(shape));
}
current_way_node_index = last_way_node_index + 1;
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For each area, collect its coordinates. If it belongs to a relation, we group by its relation id, if it's a simple way, group by its own id. This way both mapping area handled in the same way.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

while collecting the geometry, also record the nodes flagged as intersections

Comment thread src/mjolnir/areabuilder.cc Outdated
Comment on lines +66 to +83
// reference point for the local projection, first point of the first way
const midgard::PointLL center = shapes.front().front();
midgard::DistanceApproximator<midgard::PointLL> aprox(center);
const double meter_per_lng = aprox.GetMetersPerLngDegree();

// project each way to meters and create a GEOS line for each one
std::vector<GEOSGeometry*> lines;
for (const auto& shape : shapes) {
if (shape.size() < 2) {
continue;
}
// sequence of meter coords of the nodes of a way
GEOSCoordSequence* seq = GEOSCoordSeq_create(shape.size(), 2);
for (size_t i = 0; i < shape.size(); i++) {
double x = (shape[i].lng() - center.lng()) * meter_per_lng;
double y = (shape[i].lat() - center.lat()) * midgard::kMetersPerDegreeLat;
GEOSCoordSeq_setX(seq, i, x);
GEOSCoordSeq_setY(seq, i, y);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GEOS works in cartesian coordinates, so we project to local meters relative to the reference point, using the already in Valhalla function DistanceApproximator. We keep the center and scale to project back later

Comment on lines +85 to +93
// create a line with these points
GEOSGeometry* line = GEOSGeom_createLineString(seq);
if (line) {
lines.push_back(line);
}
}
if (lines.empty()) {
continue;
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Build one line string per way from the projected coordinates

Comment thread src/mjolnir/areabuilder.cc Outdated
continue;
}
// with the lines we created, returns a collection of polygons
GEOSGeometry* polygons = GEOSPolygonize(lines.data(), lines.size());

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GEOSpolygonize assemble the lines into polygons, finds the closed rings, handling the case where several ways together form one ring. It returns th epolygon already with its hole, plus the inner as a separete leftover polygon

Comment on lines +99 to +122
std::vector<GEOSGeometry*> final_polygons;
for (int i = 0; i < num_polygons; ++i) {
const GEOSGeometry* poly_i = GEOSGetGeometryN(polygons, i);
GEOSGeometry* point = GEOSPointOnSurface(poly_i);
bool fills_a_hole = false;
for (int j = 0; j < num_polygons; ++j) {
if (i == j || GEOSGetNumInteriorRings(GEOSGetGeometryN(polygons, j)) == 0) {
continue;
}
const GEOSGeometry* exterior = GEOSGetExteriorRing(GEOSGetGeometryN(polygons, j));
GEOSGeometry* shell = GEOSGeom_createPolygon(GEOSGeom_clone(exterior), nullptr, 0);
char inside_shell = GEOSContains(shell, point);
char inside_poly = GEOSContains(GEOSGetGeometryN(polygons, j), point);
GEOSGeom_destroy(shell);
if (inside_shell == 1 && inside_poly == 0) {
fills_a_hole = true;
break;
}
}
GEOSGeom_destroy(point);
if (!fills_a_hole) {
final_polygons.push_back(GEOSGeom_clone(poly_i));
}
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since it returns the inners as a separate polygon, we detect those (a polygon whose interior point falls inside another polygon's hole) and drop them, keeping the outer with its holes

Comment on lines +131 to +139
for (GEOSGeometry* poly : final_polygons) {
double area = 0;
GEOSArea(poly, &area);
// skip areas that are too small to be worth routing through
if (area < kMinAreaSquareMeters) {
continue;
}
GenerateMedialAxis(poly, center, meter_per_lng);
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

skip areas smaller than the threshold, otherwise generate medial axis

Comment thread src/mjolnir/areabuilder.cc Outdated
Comment on lines +165 to +169
// densify the polygon boundary so the voronoi diagram has enough points
GEOSGeometry* densified = GEOSDensify(polygon, kDensifyToleranceMeters);
if (!densified) {
return;
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

densify the polygon boundary so the Voronoi diagram has enough points to produce a smooth skeleton

Comment thread src/mjolnir/areabuilder.cc Outdated
Comment on lines +178 to +183
// compute the voronoi diagram using the densified polygon vertices
GEOSGeometry* voronoi = GEOSVoronoiDiagram(densified, nullptr, 0.0, GEOS_VORONOI_ONLY_EDGES);
if (!voronoi) {
GEOSGeom_destroy(densified);
return;
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Compute the voronoi diagram of the boundary points, with the GEOS_VORONOI_ONLY_EDGES flag, it returns the edges as line strings.

Comment thread src/mjolnir/areabuilder.cc Outdated
Comment on lines +187 to +194
// keep only the voronoi edges that fall completely inside the polygon
std::vector<GEOSGeometry*> medial_edges;
for (int i = 0; i < num_voronoi_edges; ++i) {
const GEOSGeometry* edge = GEOSGetGeometryN(voronoi, i);
if (GEOSContains(polygon, edge) == 1) {
medial_edges.push_back(GEOSGeom_clone(edge));
}
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GEOSContains keeps only the Voronoi edges completely inside the polygon, this results into the raw medial axis.

Comment thread src/mjolnir/areabuilder.cc Outdated
Comment on lines +201 to +206
// clean up the kept edges
for (GEOSGeometry* edge : medial_edges) {
GEOSGeom_destroy(edge);
}
GEOSGeom_destroy(voronoi);
GEOSGeom_destroy(densified);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clean up all the GEOS geomtries. The kept edges, are clones, so they're destoyed separately from the Voronoi collection

Comment on lines +209 to +211
auto vertex_key = [](double x, double y) {
return std::make_pair(std::llround(x * 1000.0), std::llround(y * 1000.0));
};

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Vertices coming out of the Voronoi sharing an endpoint can differ in the last bits, rounding make those compare exactly, so the graph doesn't end up disconnected

Comment on lines +213 to +214
std::map<std::pair<int64_t, int64_t>, int> vertex_ids;
std::vector<midgard::Point2d> vertex_coords;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

vertex_ids answers if I have seen this point before, and the vector vector_coords answers where the vertex N(id) is.

We need the map to unify duplicate endpoints, and the vector to recover the actual geometry later when stitching the chains

Comment thread src/mjolnir/pbfgraphparser.cc Resolved
Comment thread src/mjolnir/areabuilder.cc Resolved
Comment thread src/mjolnir/areabuilder.cc Outdated
Comment on lines +28 to +35
bool visible_within(const GEOSGeometry* poly, const midgard::Point2d& a, const midgard::Point2d& b) {
namespace {
bool visible_within(const GEOSPreparedGeometry* prepared,
const midgard::Point2d& a,
const midgard::Point2d& b) {
GEOSCoordSequence* seq = GEOSCoordSeq_create(2, 2);
GEOSCoordSeq_setXY(seq, 0, a.x(), a.y());
GEOSCoordSeq_setXY(seq, 1, b.x(), b.y());
GEOSGeometry* segment = GEOSGeom_createLineString(seq);
const bool visible = segment && GEOSContains(poly, segment) == 1;
const bool visible = segment && GEOSPreparedCovers(prepared, segment) == 1;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Switched this to take a prepared geometry and use GEOSPreparedCovers instead of GEOSContains. the main reason : the polygon is prepared once per polygon and reused across all the visibility checks, which is a great saving since it's called many times against the same geometry


// way_id > relation_id, to know which relation each area way belongs to
std::unordered_map<uint64_t, uint64_t> way_to_relation;
way_to_relation.reserve(osmdata.area_relations.size());

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

reserve since we know the size from area_relations

Comment on lines 99 to +143
@@ -104,26 +109,46 @@ void AreaBuilder::BuildAreas(const boost::property_tree::ptree& /*pt*/,
shape.push_back(node.latlng());
if (node.intersection()) {
area_shared_nodes[area_key].push_back({node.osmid_, node.latlng()});
area_perimeter_nodes.insert(node.osmid_);
}
}
area_ways[area_key].push_back(std::move(shape));
}
current_way_node_index = last_way_node_index + 1;
}

} else if (way.pedestrian_forward() || way.pedestrian_backward()) {
pedestrian_way_spans[way.way_id()] = {first_way_node_index, last_way_node_index};
// second pass collecting pedestrian ways, filtered against the perimeter set
current_way_node_index = 0;
while (current_way_node_index < way_nodes.size()) {
auto way_node = *way_nodes[current_way_node_index];
const auto way = *ways[way_node.way_index];
const auto first_way_node_index = current_way_node_index;
const auto last_way_node_index =
first_way_node_index + way.node_count() - way_node.way_shape_node_index - 1;

if (!way.area() && (way.pedestrian_forward() || way.pedestrian_backward())) {
bool touches_area = false;
for (auto node_idx = first_way_node_index; node_idx <= last_way_node_index; node_idx++) {
const auto& node = (*way_nodes[node_idx]).node;
if (node.intersection()) {
if (node.intersection() && area_perimeter_nodes.count(node.osmid_)) {
touches_area = true;
pedestrian_node_ways[node.osmid_].push_back(
{way.way_id(), static_cast<uint32_t>(node_idx - first_way_node_index)});
}
}
// only ways that touch an area can be crossing candidates, so we only need
// to remember where their nodes live in the file for those
if (touches_area) {
pedestrian_way_spans[way.way_id()] = {first_way_node_index, last_way_node_index};
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Split the single sweep into two. The first pass handles areas an records every perimeter node into area_perimeter_nodes. The second pass handles pedestrians ways but only keeps a entry when the node is in that set, so the map stays proportional to the nodes that actually touch areas instead of every pedestrian node on the continent.

Comment thread src/mjolnir/areabuilder.cc Outdated

constexpr double kMinAreaSquareMeters = 100.0;
constexpr double kDensifyToleranceMeters = 1.0;
constexpr double kDensifyToleranceMeters = 4.0;

@pacoalbacetec pacoalbacetec Jul 30, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

raising the meters, makes it run much faster without any visual difference

@pacoalbacetec
pacoalbacetec marked this pull request as ready for review July 31, 2026 01:23

@chrstnbwnkl chrstnbwnkl left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I haven't gotten to the end yet, give me a little more time to go through the remainder @pacoalbacetec. So far mostly comments on adding comments, plus some nitpicks. Anything labeled as a nit is optional of course :)

Comment thread src/mjolnir/pbfgraphparser.cc Outdated
// Note, we also allow dataset_id to be set by config, which happens at tile build
if (osmdata.max_changeset_id_ == 0) {
osmdata.max_changeset_id_ = max_osm_id;
osmdata.max_node_id = max_osm_id;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: move this outside of this if block, otherwise the pedestrian area stuff won't work if you bring your own dataset id.

namespace valhalla {
namespace mjolnir {
// can two points be joined by a straight segment that stays inside the polygon?
namespace {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: we usually put the anonymous namespace at the very top instead of nesting it into another namespace

Comment thread valhalla/mjolnir/areabuilder.h Outdated
* @param polygon the area polygon, in local meter coordinates
* @return the skeleton of the medial axis as a list of chains
*/
static std::vector<std::vector<midgard::Point2d>> GenerateMedialAxis(const GEOSGeometry* polygon);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: can you make this a free standing function in the anonymous namespace? Then there's no need to forward declare anything

std::unordered_map<uint64_t, WaySpan> pedestrian_way_spans;

// first pass for areas, collect each area's shape, and remember which nodes lie on some perimeter.
std::unordered_set<uint64_t> area_perimeter_nodes;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

those are a lot of sets and maps, can you add a short comment above all their declarations so it's clear what they're for? Also, I assume at this point the 64 bit keys are either way IDs or relation IDs, maybe also worth a comment.

auto it = way_to_relation.find(way.way_id());
uint64_t area_key = (it != way_to_relation.end()) ? it->second : way.way_id();
if (way.name_index() != 0) {
area_name_indices[area_key] = way.name_index();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for areas that are ways, this is fine, but what about relations? Then the area_key is the relation ID, but you're still getting the name from the way, where it's actually on the relation.

}

initGEOS(nullptr, nullptr);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

now that you've filled all the mappings you need, it'd be nice to have a little comment what you're about to do with all this information next.

Comment thread src/mjolnir/areabuilder.cc Outdated

uint64_t next_synthetic_osm_id = osmdata.max_way_id + 1;
uint64_t next_synthetic_node_id = osmdata.max_node_id + 1;
for (const auto& [relation_id, shapes] : area_ways) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

relation_id is a bit of a misnomer at this point, because it might be a relation or a way ID

Comment thread src/mjolnir/areabuilder.cc Outdated
Comment on lines +160 to +166
if (shared_it != area_shared_nodes.end()) {
for (const auto& [node_id, ll] : shared_it->second) {
if (pedestrian_node_ways.count(node_id) && seen_entrances.insert(node_id).second) {
entrances.push_back({node_id, ll});
}
}
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: can this be refactored to look like this so it's one nesting level less?

Suggested change
if (shared_it != area_shared_nodes.end()) {
for (const auto& [node_id, ll] : shared_it->second) {
if (pedestrian_node_ways.count(node_id) && seen_entrances.insert(node_id).second) {
entrances.push_back({node_id, ll});
}
}
}
if (shared_it == area_shared_nodes.end()) {
continue;
}
for (const auto& [node_id, ll] : shared_it->second) {
if (pedestrian_node_ways.count(node_id) && seen_entrances.insert(node_id).second) {
entrances.push_back({node_id, ll});
}
}

Comment thread src/mjolnir/areabuilder.cc Outdated
}
// reference point for the local projection, first point of the first way
const midgard::PointLL center = shapes.front().front();
midgard::DistanceApproximator<midgard::PointLL> aprox(center);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: could use midgard::AzimuthalEquidistant here.

const double meter_per_lng = aprox.GetMetersPerLngDegree();

// project the entrances to meters and build a GEOS point for each one
std::vector<std::pair<uint64_t, midgard::Point2d>> entrances_m;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this function is already ~300 lines long, maybe this projection stuff could be turned into an anonymous function?

@chrstnbwnkl chrstnbwnkl left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your patience @pacoalbacetec while I'm trying to review this 😄 The overall logic is not that simple, but we've talked about it plenty of times before. For future reviewers, or who ever is interested in the implementation, this is the rough outline:

  1. preparation: construct the areas, find shared nodes, construct all the other mappings
  2. go through each (multi-)polygon and
    a. filter the irrelevant ones (by area, whether they're reachable, or already crossed by existing ways),
    b. find and group nearby entrances
    c. construct the medial axis
    d. connect entrances to it

I only have some small change requests, in order of decreasing relevance:

  • some more comments and todos
  • use our own DistanceSquared member functions where possible
  • look into using GEOSPolygonize_valid instead of rolling your own removal of hole polygons (not a must if it turns out to be too much work)

Other than that I think this is good enough for a public beta! As we talked about in our weekly meetings, we agreed on a number of simplifications that we might want to revisit in the future to cover some edge cases, but this should cover ~80-90% of pedestrian areas in a way that significantly improves routing across these! Really nice work @pacoalbacetec 🥳

Comment thread src/mjolnir/areabuilder.cc Outdated
for (int i = 0; i < num_polygons; ++i) {
const GEOSGeometry* poly_i = GEOSGetGeometryN(polygons, i);
GEOSGeometry* point = GEOSPointOnSurface(poly_i);
bool fills_a_hole = false;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can do something simpler here: instead of calling GEOSPolygonize and then untangling holes and non-holes, we should be able to simply call GEOSPolygonize_valid (see docs). This should give you a single polygon/multipolygon instead of a std::vector of polygons, but it seems to be the correct way that handles nested holes better and avoids this O(n^2) loop. What do you think?

for (size_t i = 0; i < entrance_points.size(); ++i) {
double distance = 0;
GEOSDistance(poly, entrance_points[i], &distance);
if (distance < kEntranceToleranceMeters) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably a good idea to leave a todo about the exact value of this tolerance. I feel like 0.5 is a bit too high, and we might revisit this in the future. Ideally an entrance should have zero distance to the polygon it belongs to, right? So I'm tempted to change the tolerance to something like std::numerical_limits<double>::epsilon() 😄

Comment thread src/mjolnir/areabuilder.cc Outdated
int num_groups = 0;
for (size_t i = 0; i < poly_entrances.size(); ++i) {
for (size_t j = 0; j < i && group_of[i] == -1; ++j) {
const double dx = poly_entrances[i].second.x() - poly_entrances[j].second.x();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can just call Point2d::DistanceSquared() here instead

group_of[i] = num_groups++;
}
}
if (num_groups < static_cast<int>(poly_entrances.size())) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you leave some comments here? The code reads like you're looking for the entrance with the least relative distance to all the other entrances in the group, but it took me a little to get to that conclusion

Comment thread src/mjolnir/areabuilder.cc Outdated
for (size_t i = 0; i < medial_axis[c].size(); ++i) {
const auto& p = medial_axis[c][i];
const double dx = p.x() - entrance.x();
const double dy = p.y() - entrance.y();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

again, use the existing DistanceSquared member functions

Comment thread src/mjolnir/areabuilder.cc Outdated
const auto& seg = segments[current_segment];
const int next_vertex = (seg.first == current_vertex) ? seg.second : seg.first;
// stop at a fork, continue at degree 2 vertex
if (incident[next_vertex].size() != 2) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: can you reuse the is_important lambda up here as well?

int current_vertex = start_vertex;
int current_segment = start_segment;
while (true) {
used[current_segment] = true;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's fine to leave the chain walking code duplicated, but it should be possible to reuse it for the removal loop above, right? maybe just leave a little todo

if (removed[s] || used[s]) {
continue;
}
chains.push_back(walk_chain(segments[s].first, static_cast<int>(s)));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

have you seen loops like this in the wild? just wondering, I couldn't come up with an example in my head 😄

Comment on lines +229 to +234
// clean up the kept edges
for (GEOSGeometry* edge : medial_edges) {
GEOSGeom_destroy(edge);
}
GEOSGeom_destroy(voronoi);
GEOSGeom_destroy(densified);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's painful to read through all these manual C object desstruction calls. Is it possible to use some sort of RAII as it is done in Geometry in valhalla/mjolnir/admin.h ?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

alternatively, one can use a built-in C++ construct for that - std::unique_ptr

auto raw_ptr = GEOSVoronoiDiagram(densified, nullptr, 0.0, GEOS_VORONOI_ONLY_EDGES);
auto smart_ptr = std::unique_ptr(raw_ptr, GEOSGeom_destroy);

or somewhat like that.

Comment on lines +5419 to +5422
OSMWay w{static_cast<uint64_t>(osm_way.id())};
w.set_node_count(nodes.size());
w.set_area(true);
ways.push_back(w);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Basically this logic adds new edges into the graph that surround such pedestrian areas. We are typically trying to keep graph reasonably small.
Have you considered to keep areas in a separate file? I've tried to follow the code path but I still got no idea if having such "perimeter edges" is a desired outcome or a side-effect.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For some of these areas it makes sense to not create synthetic ways inside them and instead just route on the perimeter (e.g. when the area is very small), so we keep them and later decide whether or not to actually use them as routable ways. If we created synthetic ways inside an area, we'll discard the perimeter for now.

We decided to possibly revisit that idea in the future, because it's easy to think of examples where having the perimeter as well as synthesized edges in the area might be necessary.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't set any OSMWay properties here aside area. Shouldn't we at least add something like "pedestrian access" to it?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's left to the kBuildAreas stage, after it's been decided to keep the perimeter. I suppose you could do it here as well, but it's more concise to set these where we also set the access flags etc. for the synthetic ways.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes perfect sense. Still, I would appreciate a comment about this here as it introduces a new state for that object - "exists but not filled"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking about this item and what I really don't like here is that after this PR we will have some OSMWays in "fully ok" state and some others OSMWays in "not fully processed" state led in the same file/collection.

Can we make it somehow less surprising?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I understand that

  1. separating these ways into different files is cleaner and more easy to comprehend
  2. using RAII is the cleaner way for interacting with the GEOS C API

but the GSoC project is about to end, so I would really try to get a first version merged.

The challenge with GSoC is to onboard somebody onto this codebase, show them how it is to work on such a large and complex codebase, while also enabling them to work on something innovative, all at the same time, all in this short time window. So we have to cut some corners to get this feature done, and these are precisely the things I deem "nice to have".

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's true that I did give @pacoalbacetec some things to improve in my last review, but the end (of the project) is nigh now 😄

@kinkard kinkard Aug 6, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@chrstnbwnkl don't get me wrong, I'm not pressing "request changes" regarding these items. Valhalla codebase has so many places to improve, so adding these two will barely make any difference. We can address these items later.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No worries, I just wanted to make clear that I'm not opposed to your ideas, just maybe we can wait a week or two to make them happen (or forever append them to the infinite list of things we could improve in the library 😄)

@chrstnbwnkl chrstnbwnkl left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is good to merge for me! Nice to see the change to how geos polygonization is used is such a small change 😄

@chrstnbwnkl
chrstnbwnkl merged commit 1854526 into master Aug 10, 2026
25 of 26 checks passed
@chrstnbwnkl
chrstnbwnkl deleted the pedestrian-area-ways-clean branch August 10, 2026 13:39
kinkard pushed a commit to kinkard/valhalla that referenced this pull request Aug 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants