SUMO - Simulation of Urban MObility
NIImporter_OpenStreetMap.cpp
Go to the documentation of this file.
1 /****************************************************************************/
10 // Importer for networks stored in OpenStreetMap format
11 /****************************************************************************/
12 // SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/
13 // Copyright (C) 2001-2016 DLR (http://www.dlr.de/) and contributors
14 /****************************************************************************/
15 //
16 // This file is part of SUMO.
17 // SUMO is free software: you can redistribute it and/or modify
18 // it under the terms of the GNU General Public License as published by
19 // the Free Software Foundation, either version 3 of the License, or
20 // (at your option) any later version.
21 //
22 /****************************************************************************/
23 
24 
25 // ===========================================================================
26 // included modules
27 // ===========================================================================
28 #ifdef _MSC_VER
29 #include <windows_config.h>
30 #else
31 #include <config.h>
32 #endif
33 #include <algorithm>
34 #include <set>
35 #include <functional>
36 #include <sstream>
37 #include <limits>
41 #include <utils/common/ToString.h>
45 #include <netbuild/NBEdge.h>
46 #include <netbuild/NBEdgeCont.h>
47 #include <netbuild/NBNode.h>
48 #include <netbuild/NBNodeCont.h>
49 #include <netbuild/NBNetBuilder.h>
50 #include <netbuild/NBOwnTLDef.h>
56 #include <utils/xml/XMLSubSys.h>
57 #include "NILoader.h"
59 
60 #ifdef CHECK_MEMORY_LEAKS
61 #include <foreign/nvwa/debug_new.h>
62 #endif // CHECK_MEMORY_LEAKS
63 
64 //#define DEBUG_LAYER_ELEVATION
65 
66 // ---------------------------------------------------------------------------
67 // static members
68 // ---------------------------------------------------------------------------
70 
72 
73 // ===========================================================================
74 // Private classes
75 // ===========================================================================
76 
80 public:
81  bool operator()(const Edge* e1, const Edge* e2) const {
82  if (e1->myHighWayType != e2->myHighWayType) {
83  return e1->myHighWayType > e2->myHighWayType;
84  }
85  if (e1->myNoLanes != e2->myNoLanes) {
86  return e1->myNoLanes > e2->myNoLanes;
87  }
88  if (e1->myNoLanesForward != e2->myNoLanesForward) {
89  return e1->myNoLanesForward > e2->myNoLanesForward;
90  }
91  if (e1->myMaxSpeed != e2->myMaxSpeed) {
92  return e1->myMaxSpeed > e2->myMaxSpeed;
93  }
94  if (e1->myIsOneWay != e2->myIsOneWay) {
95  return e1->myIsOneWay > e2->myIsOneWay;
96  }
97  return e1->myCurrentNodes > e2->myCurrentNodes;
98  }
99 };
100 
101 // ===========================================================================
102 // method definitions
103 // ===========================================================================
104 // ---------------------------------------------------------------------------
105 // static methods
106 // ---------------------------------------------------------------------------
108 
109 
110 void
112  NIImporter_OpenStreetMap importer;
113  importer.load(oc, nb);
114 }
115 
116 
118 
119 
121  // delete nodes
122  for (std::set<NIOSMNode*, CompareNodes>::iterator i = myUniqueNodes.begin(); i != myUniqueNodes.end(); i++) {
123  delete *i;
124  }
125  // delete edges
126  for (std::map<long long int, Edge*>::iterator i = myEdges.begin(); i != myEdges.end(); ++i) {
127  delete(*i).second;
128  }
129 }
130 
131 
132 void
134  // check whether the option is set (properly)
135  if (!oc.isSet("osm-files")) {
136  return;
137  }
138  /* Parse file(s)
139  * Each file is parsed twice: first for nodes, second for edges. */
140  std::vector<std::string> files = oc.getStringVector("osm-files");
141  // load nodes, first
142  NodesHandler nodesHandler(myOSMNodes, myUniqueNodes, oc.getBool("osm.elevation"));
143  for (std::vector<std::string>::const_iterator file = files.begin(); file != files.end(); ++file) {
144  // nodes
145  if (!FileHelpers::isReadable(*file)) {
146  WRITE_ERROR("Could not open osm-file '" + *file + "'.");
147  return;
148  }
149  nodesHandler.setFileName(*file);
150  PROGRESS_BEGIN_MESSAGE("Parsing nodes from osm-file '" + *file + "'");
151  if (!XMLSubSys::runParser(nodesHandler, *file)) {
152  return;
153  }
155  }
156  // load edges, then
157  EdgesHandler edgesHandler(myOSMNodes, myEdges);
158  for (std::vector<std::string>::const_iterator file = files.begin(); file != files.end(); ++file) {
159  // edges
160  edgesHandler.setFileName(*file);
161  PROGRESS_BEGIN_MESSAGE("Parsing edges from osm-file '" + *file + "'");
162  XMLSubSys::runParser(edgesHandler, *file);
164  }
165 
166  /* Remove duplicate edges with the same shape and attributes */
167  if (!oc.getBool("osm.skip-duplicates-check")) {
168  PROGRESS_BEGIN_MESSAGE("Removing duplicate edges");
169  if (myEdges.size() > 1) {
170  std::set<const Edge*, CompareEdges> dupsFinder;
171  for (std::map<long long int, Edge*>::iterator it = myEdges.begin(); it != myEdges.end();) {
172  if (dupsFinder.count(it->second) > 0) {
173  WRITE_MESSAGE("Found duplicate edges. Removing " + toString(it->first));
174  delete it->second;
175  myEdges.erase(it++);
176  } else {
177  dupsFinder.insert(it->second);
178  it++;
179  }
180  }
181  }
183  }
184 
185  /* Mark which nodes are used (by edges or traffic lights).
186  * This is necessary to detect which OpenStreetMap nodes are for
187  * geometry only */
188  std::map<long long int, int> nodeUsage;
189  // Mark which nodes are used by edges (begin and end)
190  for (std::map<long long int, Edge*>::const_iterator i = myEdges.begin(); i != myEdges.end(); ++i) {
191  Edge* e = (*i).second;
192  assert(e->myCurrentIsRoad);
193  for (std::vector<long long int>::const_iterator j = e->myCurrentNodes.begin(); j != e->myCurrentNodes.end(); ++j) {
194  if (nodeUsage.find(*j) == nodeUsage.end()) {
195  nodeUsage[*j] = 0;
196  }
197  nodeUsage[*j] = nodeUsage[*j] + 1;
198  }
199  }
200  // Mark which nodes are used by traffic lights
201  for (std::map<long long int, NIOSMNode*>::const_iterator nodesIt = myOSMNodes.begin(); nodesIt != myOSMNodes.end(); ++nodesIt) {
202  if (nodesIt->second->tlsControlled) {
203  // If the key is not found in the map, the value is automatically
204  // initialized with 0.
205  nodeUsage[nodesIt->first] += 1;
206  }
207  }
208 
209  /* Instantiate edges
210  * Only those nodes in the middle of an edge which are used by more than
211  * one edge are instantiated. Other nodes are considered as geometry nodes. */
212  NBNodeCont& nc = nb.getNodeCont();
214  for (std::map<long long int, Edge*>::iterator i = myEdges.begin(); i != myEdges.end(); ++i) {
215  Edge* e = (*i).second;
216  assert(e->myCurrentIsRoad);
217  if (e->myCurrentNodes.size() < 2) {
218  WRITE_WARNING("Discarding way '" + toString(e->id) + "' because it has only " +
219  toString(e->myCurrentNodes.size()) + " node(s)");
220  continue;
221  }
222  // build nodes;
223  // - the from- and to-nodes must be built in any case
224  // - the in-between nodes are only built if more than one edge references them
225  NBNode* currentFrom = insertNodeChecking(*e->myCurrentNodes.begin(), nc, tlsc);
226  NBNode* last = insertNodeChecking(*(e->myCurrentNodes.end() - 1), nc, tlsc);
227  int running = 0;
228  std::vector<long long int> passed;
229  for (std::vector<long long int>::iterator j = e->myCurrentNodes.begin(); j != e->myCurrentNodes.end(); ++j) {
230  passed.push_back(*j);
231  if (nodeUsage[*j] > 1 && j != e->myCurrentNodes.end() - 1 && j != e->myCurrentNodes.begin()) {
232  NBNode* currentTo = insertNodeChecking(*j, nc, tlsc);
233  running = insertEdge(e, running, currentFrom, currentTo, passed, nb);
234  currentFrom = currentTo;
235  passed.clear();
236  }
237  }
238  if (running == 0) {
239  running = -1;
240  }
241  insertEdge(e, running, currentFrom, last, passed, nb);
242  }
243 
244  const SUMOReal layerElevation = oc.getFloat("osm.layer-elevation");
245  if (layerElevation > 0) {
246  reconstructLayerElevation(layerElevation, nb);
247  }
248 
249  // load relations (after edges are built since we want to apply
250  // turn-restrictions directly to NBEdges)
251  RelationHandler relationHandler(myOSMNodes, myEdges);
252  for (std::vector<std::string>::const_iterator file = files.begin(); file != files.end(); ++file) {
253  // relations
254  relationHandler.setFileName(*file);
255  PROGRESS_BEGIN_MESSAGE("Parsing relations from osm-file '" + *file + "'");
256  XMLSubSys::runParser(relationHandler, *file);
258  }
259 }
260 
261 
262 NBNode*
264  NBNode* node = nc.retrieve(toString(id));
265  if (node == 0) {
266  NIOSMNode* n = myOSMNodes.find(id)->second;
267  Position pos(n->lon, n->lat, n->ele);
268  if (!NBNetBuilder::transformCoordinates(pos, true)) {
269  WRITE_ERROR("Unable to project coordinates for junction '" + toString(id) + "'.");
270  return 0;
271  }
272  node = new NBNode(toString(id), pos);
273  if (!nc.insert(node)) {
274  WRITE_ERROR("Could not insert junction '" + toString(id) + "'.");
275  delete node;
276  return 0;
277  }
278  n->node = node;
279  if (n->tlsControlled) {
280  // ok, this node is a traffic light node where no other nodes
281  // participate
282  // @note: The OSM-community has not settled on a schema for differentiating between fixed and actuated lights
284  NBOwnTLDef* tlDef = new NBOwnTLDef(toString(id), node, 0, type);
285  if (!tlsc.insert(tlDef)) {
286  // actually, nothing should fail here
287  delete tlDef;
288  throw ProcessError("Could not allocate tls '" + toString(id) + "'.");
289  }
290  }
291  }
292  return node;
293 }
294 
295 
296 int
298  const std::vector<long long int>& passed, NBNetBuilder& nb) {
299  NBNodeCont& nc = nb.getNodeCont();
300  NBEdgeCont& ec = nb.getEdgeCont();
301  NBTypeCont& tc = nb.getTypeCont();
303  // patch the id
304  std::string id = toString(e->id);
305  if (from == 0 || to == 0) {
306  WRITE_ERROR("Discarding edge '" + id + "' because the nodes could not be built.");
307  return index;
308  }
309  if (index >= 0) {
310  id = id + "#" + toString(index);
311  } else {
312  index = 0;
313  }
314  if (from == to) {
315  assert(passed.size() >= 2);
316  if (passed.size() == 2) {
317  WRITE_WARNING("Discarding edge '" + id + "' which connects two identical nodes without geometry.");
318  return index;
319  }
320  // in the special case of a looped way split again using passed
321  int intermediateIndex = (int)passed.size() / 2;
322  NBNode* intermediate = insertNodeChecking(passed[intermediateIndex], nc, tlsc);
323  std::vector<long long int> part1(passed.begin(), passed.begin() + intermediateIndex);
324  std::vector<long long int> part2(passed.begin() + intermediateIndex + 1, passed.end());
325  index = insertEdge(e, index, from, intermediate, part1, nb);
326  return insertEdge(e, index, intermediate, to, part2, nb);
327  }
328  const int newIndex = index + 1;
329 
330  // convert the shape
331  PositionVector shape;
332  shape.push_back(from->getPosition());
333  for (std::vector<long long int>::const_iterator i = passed.begin(); i != passed.end(); ++i) {
334  NIOSMNode* n = myOSMNodes.find(*i)->second;
335  Position pos(n->lon, n->lat, n->ele);
336  if (!NBNetBuilder::transformCoordinates(pos, true)) {
337  WRITE_ERROR("Unable to project coordinates for edge '" + id + "'.");
338  }
339  shape.push_back_noDoublePos(pos);
340  }
341  shape.push_back_noDoublePos(to->getPosition());
342 
343  std::string type = e->myHighWayType;
344  if (!tc.knows(type)) {
345  if (myUnusableTypes.count(type) > 0) {
346  return newIndex;
347  } else if (myKnownCompoundTypes.count(type) > 0) {
348  type = myKnownCompoundTypes[type];
349  } else {
350  // this edge has a type which does not yet exist in the TypeContainer
352  std::vector<std::string> types;
353  while (tok.hasNext()) {
354  std::string t = tok.next();
355  if (tc.knows(t)) {
356  if (std::find(types.begin(), types.end(), t) == types.end()) {
357  types.push_back(t);
358  }
359  } else if (tok.size() > 1) {
360  WRITE_WARNING("Discarding unknown compound '" + t + "' in type '" + type + "' (first occurence for edge '" + id + "').");
361  }
362  }
363  if (types.size() == 0) {
364  WRITE_WARNING("Discarding unusable type '" + type + "' (first occurence for edge '" + id + "').");
365  myUnusableTypes.insert(type);
366  return newIndex;
367  } else {
368  const std::string newType = joinToString(types, "|");
369  if (tc.knows(newType)) {
370  myKnownCompoundTypes[type] = newType;
371  type = newType;
372  } else if (myKnownCompoundTypes.count(newType) > 0) {
373  type = myKnownCompoundTypes[newType];
374  } else {
375  // build a new type by merging all values
376  int numLanes = 0;
377  SUMOReal maxSpeed = 0;
378  int prio = 0;
380  SUMOReal sidewalkWidth = NBEdge::UNSPECIFIED_WIDTH;
381  SUMOReal bikelaneWidth = NBEdge::UNSPECIFIED_WIDTH;
382  bool defaultIsOneWay = false;
383  SVCPermissions permissions = 0;
384  bool discard = true;
385  for (std::vector<std::string>::iterator it = types.begin(); it != types.end(); it++) {
386  if (!tc.getShallBeDiscarded(*it)) {
387  numLanes = MAX2(numLanes, tc.getNumLanes(*it));
388  maxSpeed = MAX2(maxSpeed, tc.getSpeed(*it));
389  prio = MAX2(prio, tc.getPriority(*it));
390  defaultIsOneWay &= tc.getIsOneWay(*it);
391  permissions |= tc.getPermissions(*it);
392  width = MAX2(width, tc.getWidth(*it));
393  sidewalkWidth = MAX2(sidewalkWidth, tc.getSidewalkWidth(*it));
394  bikelaneWidth = MAX2(bikelaneWidth, tc.getBikeLaneWidth(*it));
395  discard = false;
396  }
397  }
398  if (width != NBEdge::UNSPECIFIED_WIDTH) {
399  width = MAX2(width, SUMO_const_laneWidth);
400  }
401  if (discard) {
402  WRITE_WARNING("Discarding compound type '" + newType + "' (first occurence for edge '" + id + "').");
403  myUnusableTypes.insert(newType);
404  return newIndex;
405  } else {
406  WRITE_MESSAGE("Adding new type '" + type + "' (first occurence for edge '" + id + "').");
407  tc.insert(newType, numLanes, maxSpeed, prio, permissions, width, defaultIsOneWay, sidewalkWidth, bikelaneWidth);
408  for (std::vector<std::string>::iterator it = types.begin(); it != types.end(); it++) {
409  if (!tc.getShallBeDiscarded(*it)) {
410  tc.copyRestrictionsAndAttrs(*it, newType);
411  }
412  }
413  myKnownCompoundTypes[type] = newType;
414  type = newType;
415  }
416  }
417  }
418  }
419  }
420 
421  // otherwise it is not an edge and will be ignored
422  bool ok = true;
423  int numLanesForward = tc.getNumLanes(type);
424  int numLanesBackward = tc.getNumLanes(type);
425  SUMOReal speed = tc.getSpeed(type);
426  bool defaultsToOneWay = tc.getIsOneWay(type);
427  SVCPermissions forwardPermissions = tc.getPermissions(type);
428  SVCPermissions backwardPermissions = tc.getPermissions(type);
429  SUMOReal forwardWidth = tc.getWidth(type);
430  SUMOReal backwardWidth = tc.getWidth(type);
431  const bool addSidewalk = (tc.getSidewalkWidth(type) != NBEdge::UNSPECIFIED_WIDTH);
432  const bool addBikeLane = (tc.getBikeLaneWidth(type) != NBEdge::UNSPECIFIED_WIDTH);
433  // check directions
434  bool addForward = true;
435  bool addBackward = true;
436  if (e->myIsOneWay == "true" || e->myIsOneWay == "yes" || e->myIsOneWay == "1" || (defaultsToOneWay && e->myIsOneWay != "no" && e->myIsOneWay != "false" && e->myIsOneWay != "0")) {
437  addBackward = false;
438  }
439  if (e->myIsOneWay == "-1" || e->myIsOneWay == "reverse") {
440  // one-way in reversed direction of way
441  addForward = false;
442  addBackward = true;
443  }
444  if (e->myIsOneWay != "" && e->myIsOneWay != "false" && e->myIsOneWay != "no" && e->myIsOneWay != "true" && e->myIsOneWay != "yes" && e->myIsOneWay != "-1" && e->myIsOneWay != "1" && e->myIsOneWay != "reverse") {
445  WRITE_WARNING("New value for oneway found: " + e->myIsOneWay);
446  }
447  // if we had been able to extract the number of lanes, override the highway type default
448  if (e->myNoLanes > 0) {
449  if (addForward && !addBackward) {
450  numLanesForward = e->myNoLanes;
451  } else if (!addForward && addBackward) {
452  numLanesBackward = e->myNoLanes;
453  } else {
454  if (e->myNoLanesForward > 0) {
455  numLanesForward = e->myNoLanesForward;
456  } else if (e->myNoLanesForward < 0) {
457  numLanesForward = e->myNoLanes + e->myNoLanesForward;
458  } else {
459  numLanesForward = (int)std::ceil(e->myNoLanes / 2.0);
460  }
461  numLanesBackward = e->myNoLanes - numLanesForward;
462  // sometimes ways are tagged according to their physical width of a single
463  // lane but they are intended for traffic in both directions
464  numLanesForward = MAX2(1, numLanesForward);
465  numLanesBackward = MAX2(1, numLanesBackward);
466  }
467  } else if (e->myNoLanes == 0) {
468  WRITE_WARNING("Skipping edge '" + id + "' because it has zero lanes.");
469  ok = false;
470  }
471  // if we had been able to extract the maximum speed, override the type's default
472  if (e->myMaxSpeed != MAXSPEED_UNGIVEN) {
473  speed = (SUMOReal)(e->myMaxSpeed / 3.6);
474  }
475  if (speed <= 0) {
476  WRITE_WARNING("Skipping edge '" + id + "' because it has speed " + toString(speed));
477  ok = false;
478  }
479  // deal with cycleways that run in the opposite direction of a one-way street
480  if (addBikeLane) {
481  if (!addForward && (e->myCyclewayType & WAY_FORWARD) != 0) {
482  addForward = true;
483  forwardPermissions = SVC_BICYCLE;
484  forwardWidth = tc.getBikeLaneWidth(type);
485  numLanesForward = 1;
486  // do not add an additional cycle lane
488  }
489  if (!addBackward && (e->myCyclewayType & WAY_BACKWARD) != 0) {
490  addBackward = true;
491  backwardPermissions = SVC_BICYCLE;
492  backwardWidth = tc.getBikeLaneWidth(type);
493  numLanesBackward = 1;
494  // do not add an additional cycle lane
496  }
497  }
498  // deal with busways that run in the opposite direction of a one-way street
499  if (!addForward && (e->myBuswayType & WAY_FORWARD) != 0) {
500  addForward = true;
501  forwardPermissions = SVC_BUS;
502  numLanesForward = 1;
503  }
504  if (!addBackward && (e->myBuswayType & WAY_BACKWARD) != 0) {
505  addBackward = true;
506  backwardPermissions = SVC_BUS;
507  numLanesBackward = 1;
508  }
509 
510  if (ok) {
512  id = StringUtils::escapeXML(id);
513  if (addForward) {
514  assert(numLanesForward > 0);
515  NBEdge* nbe = new NBEdge(id, from, to, type, speed, numLanesForward, tc.getPriority(type),
516  forwardWidth, NBEdge::UNSPECIFIED_OFFSET, shape,
517  StringUtils::escapeXML(e->streetName), toString(e->id), lsf, true);
518  nbe->setPermissions(forwardPermissions);
519  if ((e->myBuswayType & WAY_FORWARD) != 0) {
520  nbe->setPermissions(SVC_BUS, 0);
521  }
522  if (addBikeLane && (e->myCyclewayType == WAY_UNKNOWN || (e->myCyclewayType & WAY_FORWARD) != 0)) {
523  nbe->addBikeLane(tc.getBikeLaneWidth(type));
524  }
525  if (addSidewalk) {
526  nbe->addSidewalk(tc.getSidewalkWidth(type));
527  }
528  if (!ec.insert(nbe)) {
529  delete nbe;
530  throw ProcessError("Could not add edge '" + id + "'.");
531  }
532  }
533  if (addBackward) {
534  assert(numLanesBackward > 0);
535  NBEdge* nbe = new NBEdge("-" + id, to, from, type, speed, numLanesBackward, tc.getPriority(type),
536  backwardWidth, NBEdge::UNSPECIFIED_OFFSET, shape.reverse(),
537  StringUtils::escapeXML(e->streetName), toString(e->id), lsf, true);
538  nbe->setPermissions(backwardPermissions);
539  if ((e->myBuswayType & WAY_BACKWARD) != 0) {
540  nbe->setPermissions(SVC_BUS, 0);
541  }
542  if (addBikeLane && (e->myCyclewayType == WAY_UNKNOWN || (e->myCyclewayType & WAY_BACKWARD) != 0)) {
543  nbe->addBikeLane(tc.getBikeLaneWidth(type));
544  }
545  if (addSidewalk) {
546  nbe->addSidewalk(tc.getSidewalkWidth(type));
547  }
548  if (!ec.insert(nbe)) {
549  delete nbe;
550  throw ProcessError("Could not add edge '-" + id + "'.");
551  }
552  }
553  }
554  return newIndex;
555 }
556 
557 
558 // ---------------------------------------------------------------------------
559 // definitions of NIImporter_OpenStreetMap::NodesHandler-methods
560 // ---------------------------------------------------------------------------
562  std::map<long long int, NIOSMNode*>& toFill,
563  std::set<NIOSMNode*, CompareNodes>& uniqueNodes,
564  bool importElevation) :
565  SUMOSAXHandler("osm - file"),
566  myToFill(toFill),
567  myLastNodeID(-1),
568  myIsInValidNodeTag(false),
569  myHierarchyLevel(0),
570  myUniqueNodes(uniqueNodes),
571  myImportElevation(importElevation) {
572 }
573 
574 
576 
577 
578 void
581  if (element == SUMO_TAG_NODE) {
582  bool ok = true;
583  if (myHierarchyLevel != 2) {
584  WRITE_ERROR("Node element on wrong XML hierarchy level (id='" + toString(attrs.get<long long int>(SUMO_ATTR_ID, 0, ok)) + "', level='" + toString(myHierarchyLevel) + "').");
585  return;
586  }
587  long long int id = attrs.get<long long int>(SUMO_ATTR_ID, 0, ok);
588  std::string action = attrs.hasAttribute("action") ? attrs.getStringSecure("action", "") : "";
589  if (action == "delete") {
590  return;
591  }
592  if (!ok) {
593  return;
594  }
595  myLastNodeID = -1;
596  if (myToFill.find(id) == myToFill.end()) {
597  myLastNodeID = id;
598  // assume we are loading multiple files...
599  // ... so we won't report duplicate nodes
600  bool ok = true;
601  double tlat, tlon;
602  std::istringstream lon(attrs.get<std::string>(SUMO_ATTR_LON, toString(id).c_str(), ok));
603  if (!ok) {
604  return;
605  }
606  lon >> tlon;
607  if (lon.fail()) {
608  WRITE_ERROR("Node's '" + toString(id) + "' lon information is not numeric.");
609  return;
610  }
611  std::istringstream lat(attrs.get<std::string>(SUMO_ATTR_LAT, toString(id).c_str(), ok));
612  if (!ok) {
613  return;
614  }
615  lat >> tlat;
616  if (lat.fail()) {
617  WRITE_ERROR("Node's '" + toString(id) + "' lat information is not numeric.");
618  return;
619  }
620  NIOSMNode* toAdd = new NIOSMNode(id, tlon, tlat);
621  myIsInValidNodeTag = true;
622 
623  std::set<NIOSMNode*, CompareNodes>::iterator similarNode = myUniqueNodes.find(toAdd);
624  if (similarNode == myUniqueNodes.end()) {
625  myUniqueNodes.insert(toAdd);
626  } else {
627  delete toAdd;
628  toAdd = *similarNode;
629  WRITE_MESSAGE("Found duplicate nodes. Substituting " + toString(id) + " with " + toString(toAdd->id));
630  }
631  myToFill[id] = toAdd;
632  }
633  }
634  if (element == SUMO_TAG_TAG && myIsInValidNodeTag) {
635  if (myHierarchyLevel != 3) {
636  WRITE_ERROR("Tag element on wrong XML hierarchy level.");
637  return;
638  }
639  bool ok = true;
640  std::string key = attrs.get<std::string>(SUMO_ATTR_K, toString(myLastNodeID).c_str(), ok, false);
641  // we check whether the key is relevant (and we really need to transcode the value) to avoid hitting #1636
642  if (key == "highway" || key == "ele" || key == "crossing") {
643  std::string value = attrs.get<std::string>(SUMO_ATTR_V, toString(myLastNodeID).c_str(), ok, false);
644  if (key == "highway" && value.find("traffic_signal") != std::string::npos) {
645  myToFill[myLastNodeID]->tlsControlled = true;
646  } else if (key == "crossing" && value.find("traffic_signals") != std::string::npos) {
647  myToFill[myLastNodeID]->tlsControlled = true;
648  } else if (myImportElevation && key == "ele") {
649  try {
650  myToFill[myLastNodeID]->ele = TplConvert::_2SUMOReal(value.c_str());
651  } catch (...) {
652  WRITE_WARNING("Value of key '" + key + "' is not numeric ('" + value + "') in node '" +
653  toString(myLastNodeID) + "'.");
654  }
655  }
656  }
657  }
658 }
659 
660 
661 void
663  if (element == SUMO_TAG_NODE && myHierarchyLevel == 2) {
664  myLastNodeID = -1;
665  myIsInValidNodeTag = false;
666  }
668 }
669 
670 
671 // ---------------------------------------------------------------------------
672 // definitions of NIImporter_OpenStreetMap::EdgesHandler-methods
673 // ---------------------------------------------------------------------------
675  const std::map<long long int, NIOSMNode*>& osmNodes,
676  std::map<long long int, Edge*>& toFill) :
677  SUMOSAXHandler("osm - file"),
678  myOSMNodes(osmNodes),
679  myEdgeMap(toFill) {
680  mySpeedMap["signals"] = MAXSPEED_UNGIVEN;
681  mySpeedMap["none"] = 300.;
682  mySpeedMap["no"] = 300.;
683  mySpeedMap["walk"] = 5.;
684  mySpeedMap["DE:rural"] = 100.;
685  mySpeedMap["DE:urban"] = 50.;
686  mySpeedMap["DE:living_street"] = 10.;
687 
688 }
689 
690 
692 }
693 
694 
695 void
697  const SUMOSAXAttributes& attrs) {
698  myParentElements.push_back(element);
699  // parse "way" elements
700  if (element == SUMO_TAG_WAY) {
701  bool ok = true;
702  long long int id = attrs.get<long long int>(SUMO_ATTR_ID, 0, ok);
703  std::string action = attrs.hasAttribute("action") ? attrs.getStringSecure("action", "") : "";
704  if (action == "delete") {
705  myCurrentEdge = 0;
706  return;
707  }
708  if (!ok) {
709  myCurrentEdge = 0;
710  return;
711  }
712  myCurrentEdge = new Edge(id);
713  }
714  // parse "nd" (node) elements
715  if (element == SUMO_TAG_ND) {
716  bool ok = true;
717  long long int ref = attrs.get<long long int>(SUMO_ATTR_REF, 0, ok);
718  if (ok) {
719  std::map<long long int, NIOSMNode*>::const_iterator node = myOSMNodes.find(ref);
720  if (node == myOSMNodes.end()) {
721  WRITE_WARNING("The referenced geometry information (ref='" + toString(ref) + "') is not known");
722  return;
723  } else {
724  ref = node->second->id; // node may have been substituted
725  if (myCurrentEdge->myCurrentNodes.size() == 0 ||
726  myCurrentEdge->myCurrentNodes.back() != ref) { // avoid consecutive duplicates
727  myCurrentEdge->myCurrentNodes.push_back(ref);
728  }
729  }
730  }
731  }
732  // parse values
733  if (element == SUMO_TAG_TAG && myParentElements.size() > 2 && myParentElements[myParentElements.size() - 2] == SUMO_TAG_WAY) {
734  if (myCurrentEdge == 0) {
735  return;
736  }
737  bool ok = true;
738  std::string key = attrs.get<std::string>(SUMO_ATTR_K, toString(myCurrentEdge->id).c_str(), ok, false);
739  if (key.size() > 8 && StringUtils::startsWith(key, "cycleway:")) {
740  // handle special busway keys
741  const std::string cyclewaySpec = key.substr(9);
742  key = "cycleway";
743  if (cyclewaySpec == "right") {
745  } else if (cyclewaySpec == "left") {
747  } else if (cyclewaySpec == "both") {
749  } else {
750  key = "ignore";
751  }
752  if ((myCurrentEdge->myCyclewayType & WAY_BOTH) != 0) {
753  // now we have some info on directionality
755  }
756  } else if (key.size() > 6 && StringUtils::startsWith(key, "busway:")) {
757  // handle special busway keys
758  const std::string buswaySpec = key.substr(7);
759  key = "busway";
760  if (buswaySpec == "right") {
762  } else if (buswaySpec == "left") {
764  } else if (buswaySpec == "both") {
766  } else {
767  key = "ignore";
768  }
769  }
770 
771  // we check whether the key is relevant (and we really need to transcode the value) to avoid hitting #1636
772  if (!StringUtils::endsWith(key, "way") && !StringUtils::startsWith(key, "lanes") && key != "maxspeed" && key != "junction" && key != "name" && key != "tracks" && key != "layer") {
773  return;
774  }
775  std::string value = attrs.get<std::string>(SUMO_ATTR_V, toString(myCurrentEdge->id).c_str(), ok, false);
776 
777  if (key == "highway" || key == "railway" || key == "waterway" || key == "cycleway" || key == "busway") {
779  // special cycleway stuff
780  if (key == "cycleway") {
781  if (value == "no") {
782  return;
783  } else if (value == "opposite_track") {
785  } else if (value == "opposite_lane") {
787  }
788  }
789  // special busway stuff
790  if (key == "busway") {
791  if (value == "no") {
792  return;
793  } else if (value == "opposite_track") {
795  } else if (value == "opposite_lane") {
797  }
798  // no need to extend the type id
799  return;
800  }
801  // build type id
802  const std::string singleTypeID = key + "." + value;
803  if (myCurrentEdge->myHighWayType != "") {
804  // osm-ways may be used by more than one mode (eg railway.tram + highway.residential. this is relevant for multimodal traffic)
805  // we create a new type for this kind of situation which must then be resolved in insertEdge()
806  std::vector<std::string> types = StringTokenizer(myCurrentEdge->myHighWayType, compoundTypeSeparator).getVector();
807  types.push_back(singleTypeID);
809  } else {
810  myCurrentEdge->myHighWayType = singleTypeID;
811  }
812  } else if (key == "lanes") {
813  try {
814  myCurrentEdge->myNoLanes = TplConvert::_2int(value.c_str());
815  } catch (NumberFormatException&) {
816  // might be a list of values
817  StringTokenizer st(value, ";", true);
818  std::vector<std::string> list = st.getVector();
819  if (list.size() >= 2) {
820  int minLanes = std::numeric_limits<int>::max();
821  try {
822  for (std::vector<std::string>::iterator i = list.begin(); i != list.end(); ++i) {
823  int numLanes = TplConvert::_2int(StringUtils::prune(*i).c_str());
824  minLanes = MIN2(minLanes, numLanes);
825  }
826  myCurrentEdge->myNoLanes = minLanes;
827  WRITE_WARNING("Using minimum lane number from list (" + value + ") for edge '" + toString(myCurrentEdge->id) + "'.");
828  } catch (NumberFormatException&) {
829  WRITE_WARNING("Value of key '" + key + "' is not numeric ('" + value + "') in edge '" +
830  toString(myCurrentEdge->id) + "'.");
831  }
832  }
833  } catch (EmptyData&) {
834  WRITE_WARNING("Value of key '" + key + "' is not numeric ('" + value + "') in edge '" +
835  toString(myCurrentEdge->id) + "'.");
836  }
837  } else if (key == "lanes:forward") {
838  try {
840  } catch (...) {
841  WRITE_WARNING("Value of key '" + key + "' is not numeric ('" + value + "') in edge '" +
842  toString(myCurrentEdge->id) + "'.");
843  }
844  } else if (key == "lanes:backward") {
845  try {
846  // denote backwards count with a negative sign
848  } catch (...) {
849  WRITE_WARNING("Value of key '" + key + "' is not numeric ('" + value + "') in edge '" +
850  toString(myCurrentEdge->id) + "'.");
851  }
852  } else if (key == "maxspeed") {
853  if (mySpeedMap.find(value) != mySpeedMap.end()) {
855  } else {
856  SUMOReal conversion = 1; // OSM default is km/h
857  if (StringUtils::to_lower_case(value).find("km/h") != std::string::npos) {
858  value = StringUtils::prune(value.substr(0, value.find_first_not_of("0123456789")));
859  } else if (StringUtils::to_lower_case(value).find("mph") != std::string::npos) {
860  value = StringUtils::prune(value.substr(0, value.find_first_not_of("0123456789")));
861  conversion = 1.609344; // kilometers per mile
862  }
863  try {
864  myCurrentEdge->myMaxSpeed = TplConvert::_2SUMOReal(value.c_str()) * conversion;
865  } catch (...) {
866  WRITE_WARNING("Value of key '" + key + "' is not numeric ('" + value + "') in edge '" +
867  toString(myCurrentEdge->id) + "'.");
868  }
869  }
870  } else if (key == "junction") {
871  if ((value == "roundabout") && (myCurrentEdge->myIsOneWay == "")) {
872  myCurrentEdge->myIsOneWay = "yes";
873  }
874  } else if (key == "oneway") {
875  myCurrentEdge->myIsOneWay = value;
876  } else if (key == "name") {
877  myCurrentEdge->streetName = value;
878  } else if (key == "layer") {
879  try {
880  myCurrentEdge->myLayer = TplConvert::_2int(value.c_str());
881  } catch (...) {
882  WRITE_WARNING("Value of key '" + key + "' is not numeric ('" + value + "') in edge '" +
883  toString(myCurrentEdge->id) + "'.");
884  }
885  } else if (key == "tracks") {
886  try {
887  if (TplConvert::_2int(value.c_str()) > 1) {
888  myCurrentEdge->myIsOneWay = "false";
889  } else {
890  myCurrentEdge->myIsOneWay = "true";
891  }
892  } catch (...) {
893  WRITE_WARNING("Value of key '" + key + "' is not numeric ('" + value + "') in edge '" +
894  toString(myCurrentEdge->id) + "'.");
895  }
896  }
897  }
898 }
899 
900 
901 void
903  myParentElements.pop_back();
904  if (element == SUMO_TAG_WAY) {
907  } else {
908  delete myCurrentEdge;
909  }
910  myCurrentEdge = 0;
911  }
912 }
913 
914 
915 // ---------------------------------------------------------------------------
916 // definitions of NIImporter_OpenStreetMap::RelationHandler-methods
917 // ---------------------------------------------------------------------------
919  const std::map<long long int, NIOSMNode*>& osmNodes,
920  const std::map<long long int, Edge*>& osmEdges) :
921  SUMOSAXHandler("osm - file"),
922  myOSMNodes(osmNodes),
923  myOSMEdges(osmEdges) {
924  resetValues();
925 }
926 
927 
929 }
930 
931 void
934  myIsRestriction = false;
940 }
941 
942 void
944  const SUMOSAXAttributes& attrs) {
945  myParentElements.push_back(element);
946  // parse "way" elements
947  if (element == SUMO_TAG_RELATION) {
948  bool ok = true;
949  myCurrentRelation = attrs.get<long long int>(SUMO_ATTR_ID, 0, ok);
950  std::string action = attrs.hasAttribute("action") ? attrs.getStringSecure("action", "") : "";
951  if (action == "delete" || !ok) {
953  }
954  return;
955  } else if (myCurrentRelation == INVALID_ID) {
956  return;
957  }
958  // parse member elements
959  if (element == SUMO_TAG_MEMBER) {
960  bool ok = true;
961  std::string role = attrs.hasAttribute("role") ? attrs.getStringSecure("role", "") : "";
962  long long int ref = attrs.get<long long int>(SUMO_ATTR_REF, 0, ok);
963  if (role == "via") {
964  // u-turns for divided ways may be given with 2 via-nodes or 1 via-way
965  std::string memberType = attrs.get<std::string>(SUMO_ATTR_TYPE, 0, ok);
966  if (memberType == "way" && checkEdgeRef(ref)) {
967  myViaWay = ref;
968  } else if (memberType == "node") {
969  if (myOSMNodes.find(ref) != myOSMNodes.end()) {
970  myViaNode = ref;
971  } else {
972  WRITE_WARNING("No node found for reference '" + toString(ref) + "' in relation '" + toString(myCurrentRelation) + "'");
973  }
974  }
975  } else if (role == "from" && checkEdgeRef(ref)) {
976  myFromWay = ref;
977  } else if (role == "to" && checkEdgeRef(ref)) {
978  myToWay = ref;
979  }
980  return;
981  }
982  // parse values
983  if (element == SUMO_TAG_TAG) {
984  bool ok = true;
985  std::string key = attrs.get<std::string>(SUMO_ATTR_K, toString(myCurrentRelation).c_str(), ok, false);
986  // we check whether the key is relevant (and we really need to transcode the value) to avoid hitting #1636
987  if (key == "type" || key == "restriction") {
988  std::string value = attrs.get<std::string>(SUMO_ATTR_V, toString(myCurrentRelation).c_str(), ok, false);
989  if (key == "type" && value == "restriction") {
990  myIsRestriction = true;
991  return;
992  }
993  if (key == "restriction") {
994  // @note: the 'right/left/straight' part is ignored since the information is
995  // redundantly encoded in the 'from', 'to' and 'via' members
996  if (value.substr(0, 5) == "only_") {
998  } else if (value.substr(0, 3) == "no_") {
1000  } else {
1001  WRITE_WARNING("Found unknown restriction type '" + value + "' in relation '" + toString(myCurrentRelation) + "'");
1002  }
1003  return;
1004  }
1005  }
1006  }
1007 }
1008 
1009 
1010 bool
1012  if (myOSMEdges.find(ref) != myOSMEdges.end()) {
1013  return true;
1014  } else {
1015  WRITE_WARNING("No way found for reference '" + toString(ref) + "' in relation '" + toString(myCurrentRelation) + "'");
1016  return false;
1017  }
1018 }
1019 
1020 
1021 void
1023  myParentElements.pop_back();
1024  if (element == SUMO_TAG_RELATION) {
1025  if (myIsRestriction) {
1026  assert(myCurrentRelation != INVALID_ID);
1027  bool ok = true;
1029  WRITE_WARNING("Ignoring restriction relation '" + toString(myCurrentRelation) + "' with unknown type.");
1030  ok = false;
1031  }
1032  if (myFromWay == INVALID_ID) {
1033  WRITE_WARNING("Ignoring restriction relation '" + toString(myCurrentRelation) + "' with unknown from-way.");
1034  ok = false;
1035  }
1036  if (myToWay == INVALID_ID) {
1037  WRITE_WARNING("Ignoring restriction relation '" + toString(myCurrentRelation) + "' with unknown to-way.");
1038  ok = false;
1039  }
1040  if (myViaNode == INVALID_ID && myViaWay == INVALID_ID) {
1041  WRITE_WARNING("Ignoring restriction relation '" + toString(myCurrentRelation) + "' with unknown via.");
1042  ok = false;
1043  }
1044  if (ok && !applyRestriction()) {
1045  WRITE_WARNING("Ignoring restriction relation '" + toString(myCurrentRelation) + "'.");
1046  }
1047  }
1048  // other relations might use similar subelements so reset in any case
1049  resetValues();
1050  }
1051 }
1052 
1053 
1054 bool
1056  // since OSM ways are bidirectional we need the via to figure out which direction was meant
1057  if (myViaNode != INVALID_ID) {
1058  NBNode* viaNode = myOSMNodes.find(myViaNode)->second->node;
1059  if (viaNode == 0) {
1060  WRITE_WARNING("Via-node '" + toString(myViaNode) + "' was not instantiated");
1061  return false;
1062  }
1063  NBEdge* from = findEdgeRef(myFromWay, viaNode->getIncomingEdges());
1064  NBEdge* to = findEdgeRef(myToWay, viaNode->getOutgoingEdges());
1065  if (from == 0) {
1066  WRITE_WARNING("from-edge of restriction relation could not be determined");
1067  return false;
1068  }
1069  if (to == 0) {
1070  WRITE_WARNING("to-edge of restriction relation could not be determined");
1071  return false;
1072  }
1074  from->addEdge2EdgeConnection(to);
1075  } else {
1076  from->removeFromConnections(to, -1, -1, true);
1077  }
1078  } else {
1079  // XXX interpreting via-ways or via-node lists not yet implemented
1080  WRITE_WARNING("direction of restriction relation could not be determined");
1081  return false;
1082  }
1083  return true;
1084 }
1085 
1086 
1087 NBEdge*
1088 NIImporter_OpenStreetMap::RelationHandler::findEdgeRef(long long int wayRef, const std::vector<NBEdge*>& candidates) const {
1089  const std::string prefix = toString(wayRef);
1090  const std::string backPrefix = "-" + prefix;
1091  NBEdge* result = 0;
1092  int found = 0;
1093  for (EdgeVector::const_iterator it = candidates.begin(); it != candidates.end(); ++it) {
1094  if (((*it)->getID().substr(0, prefix.size()) == prefix) ||
1095  ((*it)->getID().substr(0, backPrefix.size()) == backPrefix)) {
1096  result = *it;
1097  found++;
1098  }
1099  }
1100  if (found > 1) {
1101  WRITE_WARNING("Ambigous way reference '" + prefix + "' in restriction relation");
1102  result = 0;
1103  }
1104  return result;
1105 }
1106 
1107 
1108 void
1110  NBNodeCont& nc = nb.getNodeCont();
1111  NBEdgeCont& ec = nb.getEdgeCont();
1112  // reconstruct elevation from layer info
1113  // build a map of raising and lowering forces (attractor and distance)
1114  // for all nodes unknownElevation
1115  std::map<NBNode*, std::vector<std::pair<SUMOReal, SUMOReal> > > layerForces;
1116 
1117  // collect all nodes that belong to a way with layer information
1118  std::set<NBNode*> knownElevation;
1119  for (std::map<long long int, Edge*>::iterator i = myEdges.begin(); i != myEdges.end(); ++i) {
1120  Edge* e = (*i).second;
1121  if (e->myLayer != 0) {
1122  for (std::vector<long long int>::iterator j = e->myCurrentNodes.begin(); j != e->myCurrentNodes.end(); ++j) {
1123  NBNode* node = nc.retrieve(toString(*j));
1124  if (node != 0) {
1125  knownElevation.insert(node);
1126  layerForces[node].push_back(std::make_pair(e->myLayer * layerElevation, POSITION_EPS));
1127  }
1128  }
1129  }
1130  }
1131 #ifdef DEBUG_LAYER_ELEVATION
1132  std::cout << "known elevations:\n";
1133  for (std::set<NBNode*>::iterator it = knownElevation.begin(); it != knownElevation.end(); ++it) {
1134  const std::vector<std::pair<SUMOReal, SUMOReal> >& primaryLayers = layerForces[*it];
1135  std::cout << " node=" << (*it)->getID() << " ele=";
1136  for (std::vector<std::pair<SUMOReal, SUMOReal> >::const_iterator it_ele = primaryLayers.begin(); it_ele != primaryLayers.end(); ++it_ele) {
1137  std::cout << it_ele->first << " ";
1138  }
1139  std::cout << "\n";
1140  }
1141 #endif
1142  // collect all nodes within a grade-dependent range around knownElevation-nodes
1143  std::set<NBNode*> unknownElevation;
1144  for (std::set<NBNode*>::iterator it = knownElevation.begin(); it != knownElevation.end(); ++it) {
1146  SUMOReal eleSum = 0;
1147  const std::vector<std::pair<SUMOReal, SUMOReal> >& primaryLayers = layerForces[*it];
1148  for (std::vector<std::pair<SUMOReal, SUMOReal> >::const_iterator it_ele = primaryLayers.begin(); it_ele != primaryLayers.end(); ++it_ele) {
1149  eleMax = MAX2(eleMax, it_ele->first);
1150  eleSum += it_ele->first;
1151  }
1152  const SUMOReal eleAvg = eleSum / primaryLayers.size();
1153  const SUMOReal maxDist = fabs(eleMax) * 100 / layerElevation;
1154  std::map<NBNode*, SUMOReal> neighbors = getNeighboringNodes(*it, maxDist);
1155  for (std::map<NBNode*, SUMOReal>::iterator it_neigh = neighbors.begin(); it_neigh != neighbors.end(); ++it_neigh) {
1156  unknownElevation.insert(it_neigh->first);
1157  layerForces[it_neigh->first].push_back(std::make_pair(eleAvg, it_neigh->second));
1158  }
1159  }
1160 
1161  // collect forces from ground-level nodes (neither in knownElevation nor unknownElevation)
1162  for (std::set<NBNode*>::iterator it = unknownElevation.begin(); it != unknownElevation.end(); ++it) {
1164  const std::vector<std::pair<SUMOReal, SUMOReal> >& primaryLayers = layerForces[*it];
1165  for (std::vector<std::pair<SUMOReal, SUMOReal> >::const_iterator it_ele = primaryLayers.begin(); it_ele != primaryLayers.end(); ++it_ele) {
1166  eleMax = MAX2(eleMax, it_ele->first);
1167  }
1168  const SUMOReal maxDist = fabs(eleMax) * 100 / layerElevation;
1169  std::map<NBNode*, SUMOReal> neighbors = getNeighboringNodes(*it, maxDist);
1170  for (std::map<NBNode*, SUMOReal>::iterator it_neigh = neighbors.begin(); it_neigh != neighbors.end(); ++it_neigh) {
1171  if (knownElevation.count(it_neigh->first) == 0 && unknownElevation.count(it_neigh->first) == 0) {
1172  layerForces[*it].push_back(std::make_pair(0, it_neigh->second));
1173  }
1174  }
1175  }
1176  // compute the elevation for each node as the weighted average of all forces
1177 #ifdef DEBUG_LAYER_ELEVATION
1178  std::cout << "summation of forces\n";
1179 #endif
1180  std::map<NBNode*, SUMOReal> nodeElevation;
1181  for (std::map<NBNode*, std::vector<std::pair<SUMOReal, SUMOReal> > >::iterator it = layerForces.begin(); it != layerForces.end(); ++it) {
1182  const std::vector<std::pair<SUMOReal, SUMOReal> >& forces = it->second;
1183  if (forces.size() == 1) {
1184  nodeElevation[it->first] = forces.front().first;
1185  } else if (knownElevation.count(it->first) != 0) {
1186  // use the maximum value
1188  for (std::vector<std::pair<SUMOReal, SUMOReal> >::const_iterator it_force = forces.begin(); it_force != forces.end(); ++it_force) {
1189  eleMax = MAX2(eleMax, it_force->first);
1190  }
1191  nodeElevation[it->first] = eleMax;
1192  } else {
1193  // use the weighted sum
1194  SUMOReal distSum = 0;
1195  for (std::vector<std::pair<SUMOReal, SUMOReal> >::const_iterator it_force = forces.begin(); it_force != forces.end(); ++it_force) {
1196  distSum += it_force->second;
1197  }
1198  SUMOReal weightSum = 0;
1199  SUMOReal elevation = 0;
1200 #ifdef DEBUG_LAYER_ELEVATION
1201  std::cout << " node=" << it->first->getID() << " distSum=" << distSum << "\n";
1202 #endif
1203  for (std::vector<std::pair<SUMOReal, SUMOReal> >::const_iterator it_force = forces.begin(); it_force != forces.end(); ++it_force) {
1204  const SUMOReal weight = (distSum - it_force->second) / distSum;
1205  weightSum += weight;
1206  elevation += it_force->first * weight;
1207 
1208 #ifdef DEBUG_LAYER_ELEVATION
1209  std::cout << " force=" << it_force->first << " dist=" << it_force->second << " weight=" << weight << " ele=" << elevation << "\n";
1210 #endif
1211  }
1212  nodeElevation[it->first] = elevation / weightSum;
1213  }
1214  }
1215 #ifdef DEBUG_LAYER_ELEVATION
1216  std::cout << "final elevations:\n";
1217  for (std::map<NBNode*, SUMOReal>::iterator it = nodeElevation.begin(); it != nodeElevation.end(); ++it) {
1218  std::cout << " node=" << (it->first)->getID() << " ele=" << it->second << "\n";;
1219  }
1220 #endif
1221  // apply node elevations and interpolate edge shapes in z-direction
1222  for (std::map<NBNode*, SUMOReal>::iterator it = nodeElevation.begin(); it != nodeElevation.end(); ++it) {
1223  NBNode* n = it->first;
1224  Position pos = n->getPosition();
1225  n->reinit(n->getPosition() + Position(0, 0, it->second), n->getType());
1226  }
1227 
1228  // apply way elevation to all edges that had layer information
1229  for (std::map<std::string, NBEdge*>::const_iterator it = ec.begin(); it != ec.end(); ++it) {
1230  NBEdge* edge = it->second;
1231  const PositionVector& geom = edge->getGeometry();
1232  const SUMOReal length = geom.length2D();
1233  const SUMOReal zFrom = nodeElevation[edge->getFromNode()];
1234  const SUMOReal zTo = nodeElevation[edge->getToNode()];
1235  // XXX if the from- or to-node was part of multiple ways with
1236  // different layers, reconstruct the layer value from origID
1237  SUMOReal dist = 0;
1238  PositionVector newGeom;
1239  for (PositionVector::const_iterator it_pos = geom.begin(); it_pos != geom.end(); ++it_pos) {
1240  if (it_pos != geom.begin()) {
1241  dist += (*it_pos).distanceTo2D(*(it_pos - 1));
1242  }
1243  newGeom.push_back((*it_pos) + Position(0, 0, zFrom + (zTo - zFrom) * dist / length));
1244  }
1245  edge->setGeometry(newGeom);
1246  }
1247 }
1248 
1249 
1250 std::map<NBNode*, SUMOReal>
1252  std::map<NBNode*, SUMOReal> result;
1253  std::set<NBNode*> visited;
1254  std::vector<NBNode*> open;
1255  open.push_back(node);
1256  while (open.size() > 0) {
1257  NBNode* n = open.back();
1258  open.pop_back();
1259  if (visited.count(n) != 0) {
1260  continue;
1261  }
1262  visited.insert(n);
1263  const EdgeVector& edges = n->getEdges();
1264  for (EdgeVector::const_iterator j = edges.begin(); j != edges.end(); ++j) {
1265  NBEdge* e = *j;
1266  NBNode* s = 0;
1267  if (n->hasIncoming(e)) {
1268  s = e->getFromNode();
1269  } else {
1270  s = e->getToNode();
1271  }
1272  const SUMOReal dist = result[n] + e->getGeometry().length2D();
1273  if (result.count(s) == 0) {
1274  result[s] = dist;
1275  } else {
1276  result[s] = MIN2(dist, result[s]);
1277  }
1278  if (dist < maxDist) {
1279  open.push_back(s);
1280  }
1281  }
1282  }
1283  return result;
1284 }
1285 
1286 
1287 /****************************************************************************/
1288 
const std::map< long long int, NIOSMNode * > & myOSMNodes
The previously parsed nodes.
const SUMOReal lat
The latitude the node is located at.
void reconstructLayerElevation(SUMOReal layerElevation, NBNetBuilder &nb)
reconstruct elevation from layer info
An internal definition of a loaded edge.
const bool myImportElevation
whether elevation data should be imported
const std::map< long long int, Edge * > & myOSMEdges
The previously parsed edges.
An internal representation of an OSM-node.
std::vector< std::string > getStringVector(const std::string &name) const
Returns the list of string-vector-value of the named option (only for Option_String) ...
const EdgeVector & getIncomingEdges() const
Returns this node&#39;s incoming edges.
Definition: NBNode.h:240
const long long int id
The edge&#39;s id.
static const SUMOReal UNSPECIFIED_WIDTH
unspecified lane width
Definition: NBEdge.h:203
std::string streetName
The edge&#39;s street name.
NBTypeCont & getTypeCont()
Returns the type container.
Definition: NBNetBuilder.h:169
const SUMOReal SUMO_const_laneWidth
Definition: StdDefs.h:49
std::string next()
const std::map< long long int, NIOSMNode * > & myOSMNodes
The previously parsed nodes.
void myStartElement(int element, const SUMOSAXAttributes &attrs)
Called on the opening of a tag;.
static bool transformCoordinates(Position &from, bool includeInBoundary=true, GeoConvHelper *from_srs=0)
transforms loaded coordinates handles projections, offsets (using GeoConvHelper) and import of height...
const long long int id
The node&#39;s id.
static bool isReadable(std::string path)
Checks whether the given file is readable.
Definition: FileHelpers.cpp:58
static bool endsWith(const std::string &str, const std::string suffix)
Checks whether a given string ends with the suffix.
WayType myBuswayType
Information about the kind of busway along this road.
static SUMOReal _2SUMOReal(const E *const data)
converts a char-type array into the SUMOReal value described by it
Definition: TplConvert.h:290
long long int myFromWay
the origination way for the current restriction
A container for traffic light definitions and built programs.
void reinit(const Position &position, SumoXMLNodeType type, bool updateEdgeGeometries=false)
Resets initial values.
Definition: NBNode.cpp:264
bool applyRestriction() const
try to apply the parsed restriction and return whether successful
void addSidewalk(SUMOReal width)
add a pedestrian sidewalk of the given width and shift existing connctions
Definition: NBEdge.cpp:2673
vehicle is a bicycle
void myEndElement(int element)
Called when a closing tag occurs.
int SVCPermissions
bool getBool(const std::string &name) const
Returns the boolean-value of the named option (only for Option_Bool)
The representation of a single edge during network building.
Definition: NBEdge.h:70
void myStartElement(int element, const SUMOSAXAttributes &attrs)
Called on the opening of a tag;.
static std::string escapeXML(const std::string &orig)
Replaces the standard escapes by their XML entities.
bool getIsOneWay(const std::string &type) const
Returns whether edges are one-way per default for the given type.
Definition: NBTypeCont.cpp:195
long long int myCurrentRelation
The currently parsed relation.
T MAX2(T a, T b)
Definition: StdDefs.h:75
void setPermissions(SVCPermissions permissions, int lane=-1)
set allowed/disallowed classes for the given lane or for all lanes if -1 is given ...
Definition: NBEdge.cpp:2547
SUMOReal getFloat(const std::string &name) const
Returns the SUMOReal-value of the named option (only for Option_Float)
void myEndElement(int element)
Called when a closing tag occurs.
static const SUMOReal UNSPECIFIED_OFFSET
unspecified lane offset
Definition: NBEdge.h:205
SAX-handler base for SUMO-files.
static bool runParser(GenericSAXHandler &handler, const std::string &file, const bool isNet=false)
Runs the given handler on the given file; returns if everything&#39;s ok.
Definition: XMLSubSys.cpp:114
bool hasIncoming(const NBEdge *const e) const
Returns whether the given edge ends at this node.
Definition: NBNode.cpp:1201
std::vector< long long int > myCurrentNodes
The list of nodes this edge is made of.
void setGeometry(const PositionVector &g, bool inner=false)
(Re)sets the edge&#39;s geometry
Definition: NBEdge.cpp:449
virtual bool hasAttribute(int id) const =0
Returns the information whether the named (by its enum-value) attribute is within the current list...
SUMOReal getWidth(const std::string &type) const
Returns the lane width for the given type [m].
Definition: NBTypeCont.cpp:219
#define WRITE_WARNING(msg)
Definition: MsgHandler.h:200
std::string joinToStringSorting(const std::vector< T > &v, const T_BETWEEN &between, std::streamsize accuracy=OUTPUT_ACCURACY)
Definition: ToString.h:204
static OptionsCont & getOptions()
Retrieves the options.
Definition: OptionsCont.cpp:69
std::map< NBNode *, SUMOReal > getNeighboringNodes(NBNode *node, SUMOReal maxDist)
collect neighboring nodes with their road distance
SUMOReal ele
The elevation of this node.
std::set< NIOSMNode *, CompareNodes > & myUniqueNodes
the set of unique nodes (used for duplicate detection/substitution)
NBNode * node
the NBNode that was instantiated
PositionVector reverse() const
reverse position vector
static const SUMOReal MAXSPEED_UNGIVEN
SUMOReal getSidewalkWidth(const std::string &type) const
Returns the lane width for a sidewalk to be added [m].
Definition: NBTypeCont.cpp:225
static void loadNetwork(const OptionsCont &oc, NBNetBuilder &nb)
Loads content of the optionally given OSM file.
Functor which compares two Edges.
WayType myCyclewayType
Information about the kind of cycleway along this road.
const EdgeVector & getOutgoingEdges() const
Returns this node&#39;s outgoing edges.
Definition: NBNode.h:248
const std::string & getID() const
Returns the id.
Definition: Named.h:66
SUMOReal length2D() const
Returns the length.
int myNoLanesForward
number of lanes in forward direction or 0 if unknown, negative if backwards lanes are meant ...
bool addEdge2EdgeConnection(NBEdge *dest)
Adds a connection to another edge.
Definition: NBEdge.cpp:673
const Position & getPosition() const
Returns the position of this node.
Definition: NBNode.h:228
RelationHandler(const std::map< long long int, NIOSMNode * > &osmNodes, const std::map< long long int, Edge * > &osmEdges)
Constructor.
#define max(a, b)
Definition: polyfonts.c:65
void load(const OptionsCont &oc, NBNetBuilder &nb)
SUMOReal getSpeed(const std::string &type) const
Returns the maximal velocity for the given type [m/s].
Definition: NBTypeCont.cpp:183
static bool startsWith(const std::string &str, const std::string prefix)
Checks whether a given string starts with the prefix.
void setFileName(const std::string &name)
Sets the current file name.
SUMOReal getBikeLaneWidth(const std::string &type) const
Returns the lane width for a bike lane to be added [m].
Definition: NBTypeCont.cpp:231
std::map< std::string, NBEdge * >::const_iterator end() const
Returns the pointer to the end of the stored edges.
Definition: NBEdgeCont.h:198
A class which extracts OSM-edges from a parsed OSM-file.
int insertEdge(Edge *e, int index, NBNode *from, NBNode *to, const std::vector< long long int > &passed, NBNetBuilder &nb)
Builds an NBEdge.
bool insert(NBEdge *edge, bool ignorePrunning=false)
Adds an edge to the dictionary.
Definition: NBEdgeCont.cpp:162
std::vector< int > myParentElements
The element stack.
Encapsulated SAX-Attributes.
static StringBijection< TrafficLightType > TrafficLightTypes
A point in 2D or 3D with translation and scaling methods.
Definition: Position.h:46
int getNumLanes(const std::string &type) const
Returns the number of lanes for the given type.
Definition: NBTypeCont.cpp:177
NBEdgeCont & getEdgeCont()
Returns the edge container.
Definition: NBNetBuilder.h:153
A list of positions.
SumoXMLNodeType getType() const
Returns the type of this node.
Definition: NBNode.h:265
int getPriority(const std::string &type) const
Returns the priority for the given type.
Definition: NBTypeCont.cpp:189
void myEndElement(int element)
Called when a closing tag occurs.
const EdgeVector & getEdges() const
Returns all edges which participate in this node.
Definition: NBNode.h:256
Storage for edges, including some functionality operating on multiple edges.
Definition: NBEdgeCont.h:66
T MIN2(T a, T b)
Definition: StdDefs.h:69
#define PROGRESS_BEGIN_MESSAGE(msg)
Definition: MsgHandler.h:202
#define POSITION_EPS
Definition: config.h:187
long long int myLastNodeID
ID of the currently parsed node, for reporting mainly.
NodesHandler(std::map< long long int, NIOSMNode * > &toFill, std::set< NIOSMNode *, CompareNodes > &uniqueNodes, bool importElevation)
Contructor.
std::map< long long int, NIOSMNode * > & myToFill
The nodes container to fill.
bool myIsRestriction
whether the currently parsed relation is a restriction
bool knows(const std::string &type) const
Returns whether the named type is in the container.
Definition: NBTypeCont.cpp:77
std::string toString(const T &t, std::streamsize accuracy=OUTPUT_ACCURACY)
Definition: ToString.h:55
void removeFromConnections(NBEdge *toEdge, int fromLane=-1, int toLane=-1, bool tryLater=false)
Removes the specified connection(s)
Definition: NBEdge.cpp:935
void myStartElement(int element, const SUMOSAXAttributes &attrs)
Called on the opening of a tag;.
double myMaxSpeed
maximum speed in km/h, or MAXSPEED_UNGIVEN
void insert(const std::string &id, int numLanes, SUMOReal maxSpeed, int prio, SVCPermissions permissions, SUMOReal width, bool oneWayIsDefault, SUMOReal sidewalkWidth, SUMOReal bikeLaneWidth)
Adds a type into the list.
Definition: NBTypeCont.cpp:63
bool checkEdgeRef(long long int ref) const
check whether a referenced way has a corresponding edge
bool myIsInValidNodeTag
Hierarchy helper for parsing a node&#39;s tags.
std::map< long long int, Edge * > myEdges
the map from OSM way ids to edge objects
std::vector< std::string > getVector()
std::map< std::string, NBEdge * >::const_iterator begin() const
Returns the pointer to the begin of the stored edges.
Definition: NBEdgeCont.h:190
#define WRITE_ERROR(msg)
Definition: MsgHandler.h:206
int myNoLanes
number of lanes, or -1 if unknown
vehicle is a bus
void addBikeLane(SUMOReal width)
add a bicycle lane of the given width and shift existing connctions
Definition: NBEdge.cpp:2679
static std::string to_lower_case(std::string str)
Transfers the content to lower case.
Definition: StringUtils.cpp:67
static int _2int(const E *const data)
converts a char-type array into the integer value described by it
Definition: TplConvert.h:149
bool tlsControlled
Whether this is a tls controlled junction.
NBNode * getToNode() const
Returns the destination node of the edge.
Definition: NBEdge.h:371
std::map< std::string, std::string > myKnownCompoundTypes
The compound types that have already been mapped to other known types.
static std::string prune(const std::string &str)
Removes trailing and leading whitechars.
Definition: StringUtils.cpp:56
EdgesHandler(const std::map< long long int, NIOSMNode * > &osmNodes, std::map< long long int, Edge * > &toFill)
Constructor.
std::map< long long int, Edge * > & myEdgeMap
A map of built edges.
const SUMOReal lon
The longitude the node is located at.
NBNodeCont & getNodeCont()
Returns the node container.
Definition: NBNetBuilder.h:161
long long int myToWay
the destination way for the current restriction
int myLayer
Information about the relative z-ordering of ways.
Instance responsible for building networks.
Definition: NBNetBuilder.h:112
std::vector< NBEdge * > EdgeVector
Definition: NBCont.h:41
bool getShallBeDiscarded(const std::string &type) const
Returns the information whether edges of this type shall be discarded.
Definition: NBTypeCont.cpp:201
const PositionVector & getGeometry() const
Returns the geometry of the edge.
Definition: NBEdge.h:546
static const std::string compoundTypeSeparator
The separator within newly created compound type names.
std::map< std::string, SUMOReal > mySpeedMap
A map of non-numeric speed descriptions to their numeric values.
virtual std::string getStringSecure(int id, const std::string &def) const =0
Returns the string-value of the named (by its enum-value) attribute.
A storage for options typed value containers)
Definition: OptionsCont.h:99
long long int myViaNode
the via node/way for the current restriction
bool copyRestrictionsAndAttrs(const std::string &fromId, const std::string &toId)
Copy restrictions to a type.
Definition: NBTypeCont.cpp:116
bool insert(const std::string &id, const Position &position, NBDistrict *district=0)
Inserts a node into the map.
Definition: NBNodeCont.cpp:81
NBTrafficLightLogicCont & getTLLogicCont()
Returns the traffic light logics container.
Definition: NBNetBuilder.h:177
LaneSpreadFunction
Numbers representing special SUMO-XML-attribute values Information how the edge&#39;s lateral offset shal...
NBEdge * findEdgeRef(long long int wayRef, const std::vector< NBEdge * > &candidates) const
try to find the way segment among candidates
A class which extracts OSM-nodes from a parsed OSM-file.
Represents a single node (junction) during network building.
Definition: NBNode.h:74
void resetValues()
reset members to their defaults for parsing a new relation
NBNode * insertNodeChecking(long long int id, NBNodeCont &nc, NBTrafficLightLogicCont &tlsc)
Builds an NBNode.
T get(const std::string &str) const
std::string joinToString(const std::vector< T > &v, const T_BETWEEN &between, std::streamsize accuracy=OUTPUT_ACCURACY)
Definition: ToString.h:188
int myHierarchyLevel
The current hierarchy level.
std::string myHighWayType
The type, stored in "highway" key.
bool insert(NBTrafficLightDefinition *logic, bool forceInsert=false)
Adds a logic definition to the dictionary.
Importer for networks stored in OpenStreetMap format.
static const long long int INVALID_ID
#define SUMOReal
Definition: config.h:213
bool myCurrentIsRoad
Information whether this is a road.
bool operator()(const Edge *e1, const Edge *e2) const
Edge * myCurrentEdge
The currently built edge.
std::set< std::string > myUnusableTypes
The compounds types that do not contain known types.
void push_back_noDoublePos(const Position &p)
insert in back a non double position
NBNode * retrieve(const std::string &id) const
Returns the node with the given name.
Definition: NBNodeCont.cpp:110
SVCPermissions getPermissions(const std::string &type) const
Returns allowed vehicle classes for the given type.
Definition: NBTypeCont.cpp:213
Container for nodes during the netbuilding process.
Definition: NBNodeCont.h:63
T get(int attr, const char *objectid, bool &ok, bool report=true) const
Tries to read given attribute assuming it is an int.
#define PROGRESS_DONE_MESSAGE()
Definition: MsgHandler.h:203
std::map< long long int, NIOSMNode * > myOSMNodes
the map from OSM node ids to actual nodes
A traffic light logics which must be computed (only nodes/edges are given)
Definition: NBOwnTLDef.h:54
std::vector< int > myParentElements
The element stack.
#define WRITE_MESSAGE(msg)
Definition: MsgHandler.h:201
std::set< NIOSMNode *, CompareNodes > myUniqueNodes
the set of unique nodes used in NodesHandler, used when freeing memory
A class which extracts relevant relation information from a parsed OSM-file.
std::string myIsOneWay
Information whether this is an one-way road.
TrafficLightType
A storage for available types of edges.
Definition: NBTypeCont.h:62
bool isSet(const std::string &name, bool failOnNonExistant=true) const
Returns the information whether the named option is set.
NBNode * getFromNode() const
Returns the origin node of the edge.
Definition: NBEdge.h:363