1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
|
#include "generator/routing_generator.hpp"
#include "generator/borders_generator.hpp"
#include "generator/borders_loader.hpp"
#include "generator/gen_mwm_info.hpp"
#include "routing/osrm2feature_map.hpp"
#include "routing/osrm_data_facade.hpp"
#include "routing/osrm_engine.hpp"
#include "routing/cross_routing_context.hpp"
#include "indexer/classificator_loader.hpp"
#include "indexer/data_header.hpp"
#include "indexer/feature.hpp"
#include "indexer/ftypes_matcher.hpp"
#include "indexer/index.hpp"
#include "indexer/mercator.hpp"
#include "geometry/distance_on_sphere.hpp"
#include "coding/file_container.hpp"
#include "coding/read_write_utils.hpp"
#include "coding/internal/file_data.hpp"
#include "base/logging.hpp"
#include "std/fstream.hpp"
#include "3party/osrm/osrm-backend/data_structures/edge_based_node_data.hpp"
#include "3party/osrm/osrm-backend/data_structures/query_edge.hpp"
#include "3party/osrm/osrm-backend/data_structures/internal_route_result.hpp"
using platform::CountryFile;
using platform::LocalCountryFile;
namespace routing
{
using RawRouteResult = InternalRouteResult;
static double const EQUAL_POINT_RADIUS_M = 2.0;
bool LoadIndexes(string const & mwmFile, string const & osrmFile, osrm::NodeDataVectorT & nodeData, gen::OsmID2FeatureID & osm2ft)
{
if (!osrm::LoadNodeDataFromFile(osrmFile + ".nodeData", nodeData))
{
LOG(LCRITICAL, ("Can't load node data"));
return false;
}
{
FileReader reader(mwmFile + OSM2FEATURE_FILE_EXTENSION);
ReaderSource<FileReader> src(reader);
osm2ft.Read(src);
}
return true;
}
bool CheckBBoxCrossingBorder(m2::RegionD const & border, osrm::NodeData const & data)
{
ASSERT(data.m_segments.size(), ());
double minLon = data.m_segments[0].lon1;
double minLat = data.m_segments[0].lat1;
double maxLon = data.m_segments[0].lon1;
double maxLat = data.m_segments[0].lat1;
for (auto const & segment : data.m_segments)
{
minLon = min(minLon, min(segment.lon1, segment.lon2));
maxLon = max(maxLon, max(segment.lon1, segment.lon2));
minLat = min(minLat, min(segment.lat1, segment.lat2));
maxLat = max(maxLat, max(segment.lat1, segment.lat2));
}
bool const upLeft = border.Contains(MercatorBounds::FromLatLon(minLat, minLon));
bool const upRight = border.Contains(MercatorBounds::FromLatLon(minLat, maxLon));
bool const downLeft = border.Contains(MercatorBounds::FromLatLon(maxLat, minLon));
bool const downRight = border.Contains(MercatorBounds::FromLatLon(maxLat, maxLon));
bool const all = upLeft && upRight && downLeft && downRight;
bool const any = upLeft || upRight || downLeft || downRight;
return any && !all;
}
void FindCrossNodes(osrm::NodeDataVectorT const & nodeData, gen::OsmID2FeatureID const & osm2ft, borders::CountriesContainerT const & m_countries, string const & countryName, routing::CrossRoutingContextWriter & crossContext)
{
vector<m2::RegionD> regionBorders;
m_countries.ForEach([&](borders::CountryPolygons const & c)
{
if (c.m_name == countryName)
c.m_regions.ForEach([®ionBorders](m2::RegionD const & region)
{
regionBorders.push_back(region);
});
});
for (WritedNodeID nodeId = 0; nodeId < nodeData.size(); ++nodeId)
{
auto const & data = nodeData[nodeId];
// Check for outgoing candidates.
if (!data.m_segments.empty())
{
auto const & startSeg = data.m_segments.front();
auto const & endSeg = data.m_segments.back();
// Check if we have geometry for our candidate.
if (osm2ft.GetFeatureID(startSeg.wayId) || osm2ft.GetFeatureID(endSeg.wayId))
{
// Check mwm borders crossing.
for (m2::RegionD const & border: regionBorders)
{
if (!CheckBBoxCrossingBorder(border, data))
continue;
m2::PointD intersection = m2::PointD::Zero();
for (auto const & segment : data.m_segments)
{
bool const outStart =
border.Contains(MercatorBounds::FromLatLon(segment.lat1, segment.lon1));
bool const outEnd =
border.Contains(MercatorBounds::FromLatLon(segment.lat2, segment.lon2));
if (outStart == outEnd)
continue;
border.FindIntersection(MercatorBounds::FromLatLon(segment.lat1, segment.lon1),
MercatorBounds::FromLatLon(segment.lat2, segment.lon2),
intersection);
// for old format compatibility
intersection = m2::PointD(MercatorBounds::XToLon(intersection.x), MercatorBounds::YToLat(intersection.y));
if (!outStart && outEnd)
crossContext.AddIngoingNode(nodeId, intersection);
else if (outStart && !outEnd)
{
string mwmName;
m2::PointD const & mercatorPoint = MercatorBounds::FromLatLon(endSeg.lat2, endSeg.lon2);
m_countries.ForEachInRect(m2::RectD(mercatorPoint, mercatorPoint), [&](borders::CountryPolygons const & c)
{
if (c.m_name == countryName)
return;
c.m_regions.ForEachInRect(m2::RectD(mercatorPoint, mercatorPoint), [&](m2::RegionD const & region)
{
// Sometimes Contains make errors for cases near the border.
if (region.Contains(mercatorPoint) || region.AtBorder(mercatorPoint, 0.01 /*Near border accuracy. In mercator.*/))
mwmName = c.m_name;
});
});
if (!mwmName.empty())
crossContext.AddOutgoingNode(nodeId, mwmName, intersection);
else
LOG(LINFO, ("Unknowing outgoing edge", endSeg.lat2, endSeg.lon2, startSeg.lat1, startSeg.lon1));
}
}
}
}
}
}
}
void CalculateCrossAdjacency(string const & mwmRoutingPath, routing::CrossRoutingContextWriter & crossContext)
{
OsrmDataFacade<QueryEdge::EdgeData> facade;
FilesMappingContainer routingCont(mwmRoutingPath);
facade.Load(routingCont);
LOG(LINFO, ("Calculating weight map between outgoing nodes"));
crossContext.ReserveAdjacencyMatrix();
auto const & in = crossContext.GetIngoingIterators();
auto const & out = crossContext.GetOutgoingIterators();
TRoutingNodes sources, targets;
sources.reserve(distance(in.first, in.second));
targets.reserve(distance(out.first, out.second));
// Fill sources and targets with start node task for ingoing (true) and target node task
// (false) for outgoing nodes
for (auto i = in.first; i != in.second; ++i)
sources.emplace_back(i->m_nodeId, true /* isStartNode */, mwmRoutingPath);
for (auto i = out.first; i != out.second; ++i)
targets.emplace_back(i->m_nodeId, false /* isStartNode */, mwmRoutingPath);
LOG(LINFO, ("Cross section has", sources.size(), "incomes and ", targets.size(), "outcomes."));
vector<EdgeWeight> costs;
FindWeightsMatrix(sources, targets, facade, costs);
auto res = costs.begin();
for (auto i = in.first; i != in.second; ++i)
for (auto j = out.first; j != out.second; ++j)
{
EdgeWeight const & edgeWeigth = *(res++);
if (edgeWeigth != INVALID_EDGE_WEIGHT && edgeWeigth > 0)
crossContext.SetAdjacencyCost(i, j, edgeWeigth);
}
LOG(LINFO, ("Calculation of weight map between outgoing nodes DONE"));
}
void WriteCrossSection(routing::CrossRoutingContextWriter const & crossContext, string const & mwmRoutingPath)
{
LOG(LINFO, ("Collect all data into one file..."));
FilesContainerW routingCont(mwmRoutingPath, FileWriter::OP_WRITE_EXISTING);
FileWriter w = routingCont.GetWriter(ROUTING_CROSS_CONTEXT_TAG);
size_t const start_size = w.Pos();
crossContext.Save(w);
LOG(LINFO, ("Have written routing info, bytes written:", w.Pos() - start_size, "bytes"));
}
void BuildCrossRoutingIndex(string const & baseDir, string const & countryName, string const & osrmFile)
{
LOG(LINFO, ("Cross mwm routing section builder"));
string const mwmFile = baseDir + countryName + DATA_FILE_EXTENSION;
osrm::NodeDataVectorT nodeData;
gen::OsmID2FeatureID osm2ft;
if (!LoadIndexes(mwmFile, osrmFile, nodeData, osm2ft))
return;
routing::CrossRoutingContextWriter crossContext;
LOG(LINFO, ("Loading countries borders"));
borders::CountriesContainerT m_countries;
CHECK(borders::LoadCountriesList(baseDir, m_countries),
("Error loading country polygons files"));
FindCrossNodes(nodeData, osm2ft, m_countries, countryName, crossContext);
string const mwmRoutingPath = mwmFile + ROUTING_FILE_EXTENSION;
CalculateCrossAdjacency(mwmRoutingPath, crossContext);
WriteCrossSection(crossContext, mwmRoutingPath);
}
void BuildRoutingIndex(string const & baseDir, string const & countryName, string const & osrmFile)
{
classificator::Load();
CountryFile countryFile(countryName);
// Correct mwm version doesn't matter here - we just need access to mwm files via Index.
LocalCountryFile localFile(baseDir, countryFile, 0 /* version */);
localFile.SyncWithDisk();
Index index;
auto p = index.Register(localFile);
if (p.second != MwmSet::RegResult::Success)
{
LOG(LCRITICAL, ("MWM file not found"));
return;
}
ASSERT(p.first.IsAlive(), ());
osrm::NodeDataVectorT nodeData;
gen::OsmID2FeatureID osm2ft;
if (!LoadIndexes(localFile.GetPath(MapOptions::Map), osrmFile, nodeData, osm2ft))
return;
OsrmFtSegMappingBuilder mapping;
uint32_t found = 0, all = 0, multiple = 0, equal = 0, moreThan1Seg = 0, stored = 0;
for (WritedNodeID nodeId = 0; nodeId < nodeData.size(); ++nodeId)
{
auto const & data = nodeData[nodeId];
OsrmFtSegMappingBuilder::FtSegVectorT vec;
for (auto const & seg : data.m_segments)
{
m2::PointD const pts[2] = { { seg.lon1, seg.lat1 }, { seg.lon2, seg.lat2 } };
m2::PointD const segVector = MercatorBounds::FromLatLon(seg.lat2, seg.lon2) -
MercatorBounds::FromLatLon(seg.lat1, seg.lon1);
++all;
// now need to determine feature id and segments in it
uint32_t const fID = osm2ft.GetFeatureID(seg.wayId);
if (fID == 0)
{
LOG(LWARNING, ("No feature id for way:", seg.wayId));
continue;
}
FeatureType ft;
Index::FeaturesLoaderGuard loader(index, p.first.GetId());
loader.GetFeatureByIndex(fID, ft);
ft.ParseGeometry(FeatureType::BEST_GEOMETRY);
typedef pair<int, double> IndexT;
vector<IndexT> indices[2];
// Match input segment points on feature points.
for (int j = 0; j < ft.GetPointsCount(); ++j)
{
double const lon = MercatorBounds::XToLon(ft.GetPoint(j).x);
double const lat = MercatorBounds::YToLat(ft.GetPoint(j).y);
for (int k = 0; k < 2; ++k)
{
double const dist = ms::DistanceOnEarth(pts[k].y, pts[k].x, lat, lon);
if (dist <= EQUAL_POINT_RADIUS_M)
indices[k].push_back(make_pair(j, dist));
}
}
if (!indices[0].empty() && !indices[1].empty())
{
for (int k = 0; k < 2; ++k)
{
sort(indices[k].begin(), indices[k].end(), [] (IndexT const & r1, IndexT const & r2)
{
return (r1.second < r2.second);
});
}
// Show warnings for multiple or equal choices.
if (indices[0].size() != 1 && indices[1].size() != 1)
{
++multiple;
//LOG(LWARNING, ("Multiple index choices for way:", seg.wayId, indices[0], indices[1]));
}
{
size_t const count = min(indices[0].size(), indices[1].size());
size_t i = 0;
for (; i < count; ++i)
if (indices[0][i].first != indices[1][i].first)
break;
if (i == count)
{
++equal;
LOG(LWARNING, ("Equal choices for way:", seg.wayId, indices[0], indices[1]));
}
}
// Find best matching for multiple choices.
int ind1 = -1, ind2 = -1, dist = numeric_limits<int>::max();
for (auto i1 : indices[0])
for (auto i2 : indices[1])
{
// We use delta of the indexes to avoid P formed curves cases.
int const d = abs(i1.first - i2.first);
if (d < dist && i1.first != i2.first)
{
// Check if resulting vector has same direction with the edge.
m2::PointD candidateVector = ft.GetPoint(i2.first) - ft.GetPoint(i1.first);
if (m2::DotProduct(candidateVector, segVector) < 0)
continue;
ind1 = i1.first;
ind2 = i2.first;
dist = d;
}
}
if (ind1 != -1 && ind2 != -1)
{
++found;
// Emit segment.
OsrmMappingTypes::FtSeg ftSeg(fID, ind1, ind2);
if (vec.empty() || !vec.back().Merge(ftSeg))
{
vec.push_back(ftSeg);
++stored;
}
continue;
}
}
// Matching error. Print warning message.
LOG(LWARNING, ("!!!!! Match not found:", seg.wayId));
LOG(LWARNING, ("(Lat, Lon):", pts[0].y, pts[0].x, "; (Lat, Lon):", pts[1].y, pts[1].x));
int ind1 = -1;
int ind2 = -1;
double dist1 = numeric_limits<double>::max();
double dist2 = numeric_limits<double>::max();
for (int j = 0; j < ft.GetPointsCount(); ++j)
{
double lon = MercatorBounds::XToLon(ft.GetPoint(j).x);
double lat = MercatorBounds::YToLat(ft.GetPoint(j).y);
double const d1 = ms::DistanceOnEarth(pts[0].y, pts[0].x, lat, lon);
double const d2 = ms::DistanceOnEarth(pts[1].y, pts[1].x, lat, lon);
if (d1 < dist1)
{
ind1 = j;
dist1 = d1;
}
if (d2 < dist2)
{
ind2 = j;
dist2 = d2;
}
}
LOG(LWARNING, ("ind1 =", ind1, "ind2 =", ind2, "dist1 =", dist1, "dist2 =", dist2));
}
if (vec.size() > 1)
++moreThan1Seg;
mapping.Append(nodeId, vec);
}
LOG(LINFO, ("All:", all, "Found:", found, "Not found:", all - found, "More that one segs in node:", moreThan1Seg,
"Multiple:", multiple, "Equal:", equal));
LOG(LINFO, ("Collect all data into one file..."));
string const fPath = localFile.GetPath(MapOptions::CarRouting);
FilesContainerW routingCont(fPath /*, FileWriter::OP_APPEND*/);
{
// Write version for routing file that is equal to correspondent mwm file.
FilesContainerR mwmCont(localFile.GetPath(MapOptions::Map));
FileWriter w = routingCont.GetWriter(VERSION_FILE_TAG);
ReaderSource<ModelReaderPtr> src(mwmCont.GetReader(VERSION_FILE_TAG));
rw::ReadAndWrite(src, w);
w.WritePaddingByEnd(4);
}
mapping.Save(routingCont);
auto appendFile = [&] (string const & tag)
{
string const fileName = osrmFile + "." + tag;
LOG(LINFO, ("Append file", fileName, "with tag", tag));
routingCont.Write(fileName, tag);
};
appendFile(ROUTING_SHORTCUTS_FILE_TAG);
appendFile(ROUTING_EDGEDATA_FILE_TAG);
appendFile(ROUTING_MATRIX_FILE_TAG);
appendFile(ROUTING_EDGEID_FILE_TAG);
routingCont.Finish();
uint64_t sz;
VERIFY(my::GetFileSize(fPath, sz), ());
LOG(LINFO, ("Nodes stored:", stored, "Routing index file size:", sz));
}
}
|