SUMO - Simulation of Urban MObility
NWWriter_OpenDrive.cpp
Go to the documentation of this file.
1 /****************************************************************************/
2 // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
3 // Copyright (C) 2011-2018 German Aerospace Center (DLR) and others.
4 // This program and the accompanying materials
5 // are made available under the terms of the Eclipse Public License v2.0
6 // which accompanies this distribution, and is available at
7 // http://www.eclipse.org/legal/epl-v20.html
8 // SPDX-License-Identifier: EPL-2.0
9 /****************************************************************************/
16 // Exporter writing networks using the openDRIVE format
17 /****************************************************************************/
18 
19 
20 // ===========================================================================
21 // included modules
22 // ===========================================================================
23 #include <config.h>
24 
25 #include <ctime>
26 #include "NWWriter_OpenDrive.h"
29 #include <netbuild/NBEdgeCont.h>
30 #include <netbuild/NBNode.h>
31 #include <netbuild/NBNodeCont.h>
32 #include <netbuild/NBNetBuilder.h>
35 #include <utils/geom/bezier.h>
37 #include <utils/common/StdDefs.h>
40 
41 #define INVALID_ID -1
42 
43 //#define DEBUG_SMOOTH_GEOM
44 #define DEBUGCOND true
45 
46 #define MIN_TURN_DIAMETER 2.0
47 
48 
49 // ===========================================================================
50 // method definitions
51 // ===========================================================================
52 // ---------------------------------------------------------------------------
53 // static methods
54 // ---------------------------------------------------------------------------
55 void
57  // check whether an opendrive-file shall be generated
58  if (!oc.isSet("opendrive-output")) {
59  return;
60  }
61  const NBNodeCont& nc = nb.getNodeCont();
62  const NBEdgeCont& ec = nb.getEdgeCont();
63  const bool origNames = oc.getBool("output.original-names");
64  const bool lefthand = oc.getBool("lefthand");
65  const double straightThresh = DEG2RAD(oc.getFloat("opendrive-output.straight-threshold"));
66  // some internal mapping containers
67  int nodeID = 1;
68  int edgeID = nc.size() * 10; // distinct from node ids
69  StringBijection<int> edgeMap;
70  StringBijection<int> nodeMap;
71  //
72  OutputDevice& device = OutputDevice::getDevice(oc.getString("opendrive-output"));
73  device << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
74  device.openTag("OpenDRIVE");
75  time_t now = time(nullptr);
76  std::string dstr(ctime(&now));
78  // write header
79  device.openTag("header");
80  device.writeAttr("revMajor", "1");
81  device.writeAttr("revMinor", "4");
82  device.writeAttr("name", "");
83  device.writeAttr("version", "1.00");
84  device.writeAttr("date", dstr.substr(0, dstr.length() - 1));
85  device.writeAttr("north", b.ymax());
86  device.writeAttr("south", b.ymin());
87  device.writeAttr("east", b.xmax());
88  device.writeAttr("west", b.xmin());
89  /* @note obsolete in 1.4
90  device.writeAttr("maxRoad", ec.size());
91  device.writeAttr("maxJunc", nc.size());
92  device.writeAttr("maxPrg", 0);
93  */
94  device.closeTag();
95  // write optional geo reference
97  if (gch.usingGeoProjection()) {
98  if (gch.getOffsetBase() == Position(0, 0)) {
99  device.openTag("geoReference");
100  device.writePreformattedTag(" <![CDATA[\n "
101  + gch.getProjString()
102  + "\n]]>\n");
103  device.closeTag();
104  } else {
105  WRITE_WARNING("Could not write OpenDRIVE geoReference. Only unshifted Coordinate systems are supported (offset=" + toString(gch.getOffsetBase()) + ")");
106  }
107  }
108 
109  // write normal edges (road)
110  for (std::map<std::string, NBEdge*>::const_iterator i = ec.begin(); i != ec.end(); ++i) {
111  const NBEdge* e = (*i).second;
112  const int fromNodeID = e->getIncomingEdges().size() > 0 ? getID(e->getFromNode()->getID(), nodeMap, nodeID) : INVALID_ID;
113  const int toNodeID = e->getConnections().size() > 0 ? getID(e->getToNode()->getID(), nodeMap, nodeID) : INVALID_ID;
114  writeNormalEdge(device, e,
115  getID(e->getID(), edgeMap, edgeID),
116  fromNodeID, toNodeID,
117  origNames, straightThresh);
118  }
119  device.lf();
120 
121  // write junction-internal edges (road). In OpenDRIVE these are called 'paths' or 'connecting roads'
122  OutputDevice_String junctionOSS(false, 3);
123  for (std::map<std::string, NBNode*>::const_iterator i = nc.begin(); i != nc.end(); ++i) {
124  NBNode* n = (*i).second;
125  int connectionID = 0; // unique within a junction
126  const int nID = getID(n->getID(), nodeMap, nodeID);
127  if (n->numNormalConnections() > 0) {
128  junctionOSS << " <junction name=\"" << n->getID() << "\" id=\"" << nID << "\">\n";
129  }
130  std::vector<NBEdge*> incoming = (*i).second->getIncomingEdges();
131  if (lefthand) {
132  std::reverse(incoming.begin(), incoming.end());
133  }
134  for (NBEdge* inEdge : incoming) {
135  std::string centerMark = "none";
136  const int inEdgeID = getID(inEdge->getID(), edgeMap, edgeID);
137  // group parallel edges
138  const NBEdge* outEdge = nullptr;
139  bool isOuterEdge = true; // determine where a solid outer border should be drawn
140  int lastFromLane = -1;
141  std::vector<NBEdge::Connection> parallel;
142  std::vector<NBEdge::Connection> connections = inEdge->getConnections();
143  if (lefthand) {
144  std::reverse(connections.begin(), connections.end());
145  }
146  for (const NBEdge::Connection& c : connections) {
147  assert(c.toEdge != 0);
148  if (outEdge != c.toEdge || c.fromLane == lastFromLane) {
149  if (outEdge != nullptr) {
150  if (isOuterEdge) {
151  addPedestrianConnection(inEdge, outEdge, parallel);
152  }
153  connectionID = writeInternalEdge(device, junctionOSS, inEdge, nID,
154  getID(parallel.back().getInternalLaneID(), edgeMap, edgeID),
155  inEdgeID,
156  getID(outEdge->getID(), edgeMap, edgeID),
157  connectionID,
158  parallel, isOuterEdge, straightThresh, centerMark);
159  parallel.clear();
160  isOuterEdge = false;
161  }
162  outEdge = c.toEdge;
163  }
164  lastFromLane = c.fromLane;
165  parallel.push_back(c);
166  }
167  if (isOuterEdge) {
168  addPedestrianConnection(inEdge, outEdge, parallel);
169  }
170  if (!parallel.empty()) {
171  if (!lefthand && (n->geometryLike() || inEdge->isTurningDirectionAt(outEdge))) {
172  centerMark = "solid";
173  }
174  connectionID = writeInternalEdge(device, junctionOSS, inEdge, nID,
175  getID(parallel.back().getInternalLaneID(), edgeMap, edgeID),
176  inEdgeID,
177  getID(outEdge->getID(), edgeMap, edgeID),
178  connectionID,
179  parallel, isOuterEdge, straightThresh, centerMark);
180  parallel.clear();
181  }
182  }
183  if (n->numNormalConnections() > 0) {
184  junctionOSS << " </junction>\n";
185  }
186  }
187  device.lf();
188  // write junctions (junction)
189  device << junctionOSS.getString();
190 
191  for (std::map<std::string, NBNode*>::const_iterator i = nc.begin(); i != nc.end(); ++i) {
192  NBNode* n = (*i).second;
193  const std::vector<NBEdge*>& incoming = n->getIncomingEdges();
194  // check if any connections must be written
195  int numConnections = 0;
196  for (std::vector<NBEdge*>::const_iterator j = incoming.begin(); j != incoming.end(); ++j) {
197  numConnections += (int)((*j)->getConnections().size());
198  }
199  if (numConnections == 0) {
200  continue;
201  }
202  for (std::vector<NBEdge*>::const_iterator j = incoming.begin(); j != incoming.end(); ++j) {
203  const NBEdge* inEdge = *j;
204  const std::vector<NBEdge::Connection>& elv = inEdge->getConnections();
205  for (std::vector<NBEdge::Connection>::const_iterator k = elv.begin(); k != elv.end(); ++k) {
206  const NBEdge::Connection& c = *k;
207  const NBEdge* outEdge = c.toEdge;
208  if (outEdge == nullptr) {
209  continue;
210  }
211  }
212  }
213  }
214 
215  device.closeTag();
216  device.close();
217 }
218 
219 
220 void
222  int edgeID, int fromNodeID, int toNodeID,
223  const bool origNames,
224  const double straightThresh) {
225  // buffer output because some fields are computed out of order
226  OutputDevice_String elevationOSS(false, 3);
227  elevationOSS.setPrecision(8);
228  OutputDevice_String planViewOSS(false, 2);
229  planViewOSS.setPrecision(8);
230  double length = 0;
231 
232  planViewOSS.openTag("planView");
233  // for the shape we need to use the leftmost border of the leftmost lane
234  const std::vector<NBEdge::Lane>& lanes = e->getLanes();
236 #ifdef DEBUG_SMOOTH_GEOM
237  if (DEBUGCOND) {
238  std::cout << "write planview for edge " << e->getID() << "\n";
239  }
240 #endif
241 
242  if (ls.size() == 2 || e->getPermissions() == SVC_PEDESTRIAN) {
243  // foot paths may contain sharp angles
244  length = writeGeomLines(ls, planViewOSS, elevationOSS);
245  } else {
246  bool ok = writeGeomSmooth(ls, e->getSpeed(), planViewOSS, elevationOSS, straightThresh, length);
247  if (!ok) {
248  WRITE_WARNING("Could not compute smooth shape for edge '" + e->getID() + "'.");
249  }
250  }
251  planViewOSS.closeTag();
252 
253  device.openTag("road");
254  device.writeAttr("name", StringUtils::escapeXML(e->getStreetName()));
255  device.setPrecision(8); // length requires higher precision
256  device.writeAttr("length", MAX2(POSITION_EPS, length));
257  device.setPrecision(gPrecision);
258  device.writeAttr("id", edgeID);
259  device.writeAttr("junction", -1);
260  if (fromNodeID != INVALID_ID || toNodeID != INVALID_ID) {
261  device.openTag("link");
262  if (fromNodeID != INVALID_ID) {
263  device.openTag("predecessor");
264  device.writeAttr("elementType", "junction");
265  device.writeAttr("elementId", fromNodeID);
266  device.closeTag();
267  }
268  if (toNodeID != INVALID_ID) {
269  device.openTag("successor");
270  device.writeAttr("elementType", "junction");
271  device.writeAttr("elementId", toNodeID);
272  device.closeTag();
273  }
274  device.closeTag();
275  }
276  device.openTag("type").writeAttr("s", 0).writeAttr("type", "town").closeTag();
277  device << planViewOSS.getString();
278  writeElevationProfile(ls, device, elevationOSS);
279  device << " <lateralProfile/>\n";
280  device << " <lanes>\n";
281  device << " <laneSection s=\"0\">\n";
282  const std::string centerMark = e->getPermissions(e->getNumLanes() - 1) == 0 ? "none" : "solid";
283  writeEmptyCenterLane(device, centerMark, 0.13);
284  device << " <right>\n";
285  for (int j = e->getNumLanes(); --j >= 0;) {
286  device << " <lane id=\"-" << e->getNumLanes() - j << "\" type=\"" << getLaneType(e->getPermissions(j)) << "\" level=\"true\">\n";
287  device << " <link/>\n";
288  // this could be used for geometry-link junctions without u-turn,
289  // predecessor and sucessors would be lane indices,
290  // road predecessor / succesfors would be of type 'road' rather than
291  // 'junction'
292  //device << " <predecessor id=\"-1\"/>\n";
293  //device << " <successor id=\"-1\"/>\n";
294  //device << " </link>\n";
295  device << " <width sOffset=\"0\" a=\"" << e->getLaneWidth(j) << "\" b=\"0\" c=\"0\" d=\"0\"/>\n";
296  std::string markType = "broken";
297  if (j == 0) {
298  markType = "solid";
299  } else if (j > 0
300  && (e->getPermissions(j - 1) & ~(SVC_PEDESTRIAN | SVC_BICYCLE)) == 0) {
301  // solid road mark to the left of sidewalk or bicycle lane
302  markType = "solid";
303  } else if (e->getPermissions(j) == 0) {
304  // solid road mark to the right of a forbidden lane
305  markType = "solid";
306  }
307  device << " <roadMark sOffset=\"0\" type=\"" << markType << "\" weight=\"standard\" color=\"standard\" width=\"0.13\"/>\n";
308  device << " <speed sOffset=\"0\" max=\"" << lanes[j].speed << "\"/>\n";
309  device << " </lane>\n";
310  }
311  device << " </right>\n";
312  device << " </laneSection>\n";
313  device << " </lanes>\n";
314  device << " <objects/>\n";
315  device << " <signals/>\n";
316  if (origNames) {
317  device << " <userData code=\"sumoId\" value=\"" << e->getID() << "\"/>\n";
318  }
319  device.closeTag();
321 }
322 
323 void
324 NWWriter_OpenDrive::addPedestrianConnection(const NBEdge* inEdge, const NBEdge* outEdge, std::vector<NBEdge::Connection>& parallel) {
325  // by default there are no internal lanes for pedestrians. Determine if
326  // one is feasible and does not exist yet.
327  if (outEdge != nullptr
328  && inEdge->getPermissions(0) == SVC_PEDESTRIAN
329  && outEdge->getPermissions(0) == SVC_PEDESTRIAN
330  && (parallel.empty()
331  || parallel.front().fromLane != 0
332  || parallel.front().toLane != 0)) {
333  parallel.insert(parallel.begin(), NBEdge::Connection(0, const_cast<NBEdge*>(outEdge), 0, false));
334  parallel.front().vmax = (inEdge->getLanes()[0].speed + outEdge->getLanes()[0].speed) / (double) 2.0;
335  }
336 }
337 
338 
339 int
340 NWWriter_OpenDrive::writeInternalEdge(OutputDevice& device, OutputDevice& junctionDevice, const NBEdge* inEdge, int nodeID,
341  int edgeID, int inEdgeID, int outEdgeID,
342  int connectionID,
343  const std::vector<NBEdge::Connection>& parallel,
344  const bool isOuterEdge,
345  const double straightThresh,
346  const std::string& centerMark) {
347  assert(parallel.size() != 0);
348  const NBEdge::Connection& cLeft = parallel.back();
349  const NBEdge* outEdge = cLeft.toEdge;
350  PositionVector begShape = getLeftLaneBorder(inEdge, cLeft.fromLane);
351  PositionVector endShape = getLeftLaneBorder(outEdge, cLeft.toLane);
352  //std::cout << "computing reference line for internal lane " << cLeft.getInternalLaneID() << " begLane=" << inEdge->getLaneShape(cLeft.fromLane) << " endLane=" << outEdge->getLaneShape(cLeft.toLane) << "\n";
353 
354  double length;
355  double laneOffset = 0;
356  PositionVector fallBackShape;
357  fallBackShape.push_back(begShape.back());
358  fallBackShape.push_back(endShape.front());
359  const bool turnaround = inEdge->isTurningDirectionAt(outEdge);
360  bool ok = true;
361  PositionVector init = NBNode::bezierControlPoints(begShape, endShape, turnaround, 25, 25, ok, nullptr, straightThresh);
362  if (init.size() == 0) {
363  length = fallBackShape.length2D();
364  // problem with turnarounds is known, method currently returns 'ok' (#2539)
365  if (!ok) {
366  WRITE_WARNING("Could not compute smooth shape from lane '" + inEdge->getLaneID(cLeft.fromLane) + "' to lane '" + outEdge->getLaneID(cLeft.toLane) + "'. Use option 'junctions.scurve-stretch' or increase radius of junction '" + inEdge->getToNode()->getID() + "' to fix this.");
367  } else if (length <= NUMERICAL_EPS) {
368  // left-curving geometry-like edges must use the right
369  // side as reference line and shift
370  begShape = getRightLaneBorder(inEdge, cLeft.fromLane);
371  endShape = getRightLaneBorder(outEdge, cLeft.toLane);
372  init = NBNode::bezierControlPoints(begShape, endShape, turnaround, 25, 25, ok, nullptr, straightThresh);
373  if (init.size() != 0) {
374  length = bezier(init, 12).length2D();
375  laneOffset = outEdge->getLaneWidth(cLeft.toLane);
376  //std::cout << " internalLane=" << cLeft.getInternalLaneID() << " length=" << length << "\n";
377  }
378  }
379  } else {
380  length = bezier(init, 12).length2D();
381  }
382 
383  junctionDevice << " <connection id=\"" << connectionID << "\" incomingRoad=\"" << inEdgeID << "\" connectingRoad=\"" << edgeID << "\" contactPoint=\"start\">\n";
384  device.openTag("road");
385  device.writeAttr("name", cLeft.id);
386  device.setPrecision(8); // length requires higher precision
387  device.writeAttr("length", MAX2(POSITION_EPS, length));
388  device.setPrecision(gPrecision);
389  device.writeAttr("id", edgeID);
390  device.writeAttr("junction", nodeID);
391  device.openTag("link");
392  device.openTag("predecessor");
393  device.writeAttr("elementType", "road");
394  device.writeAttr("elementId", inEdgeID);
395  device.writeAttr("contactPoint", "end");
396  device.closeTag();
397  device.openTag("successor");
398  device.writeAttr("elementType", "road");
399  device.writeAttr("elementId", outEdgeID);
400  device.writeAttr("contactPoint", "start");
401  device.closeTag();
402  device.closeTag();
403  device.openTag("type").writeAttr("s", 0).writeAttr("type", "town").closeTag();
404  device.openTag("planView");
405  device.setPrecision(8); // geometry hdg requires higher precision
406  OutputDevice_String elevationOSS(false, 3);
407  elevationOSS.setPrecision(8);
408 #ifdef DEBUG_SMOOTH_GEOM
409  if (DEBUGCOND) {
410  std::cout << "write planview for internal edge " << cLeft.id << " init=" << init << " fallback=" << fallBackShape
411  << " begShape=" << begShape << " endShape=" << endShape
412  << "\n";
413  }
414 #endif
415  if (init.size() == 0) {
416  writeGeomLines(fallBackShape, device, elevationOSS);
417  } else {
418  writeGeomPP3(device, elevationOSS, init, length);
419  }
420  device.setPrecision(gPrecision);
421  device.closeTag();
422  writeElevationProfile(fallBackShape, device, elevationOSS);
423  device << " <lateralProfile/>\n";
424  device << " <lanes>\n";
425  if (laneOffset != 0) {
426  device << " <laneOffset s=\"0\" a=\"" << laneOffset << "\" b=\"0\" c=\"0\" d=\"0\"/>\n";
427  }
428  device << " <laneSection s=\"0\">\n";
429  writeEmptyCenterLane(device, centerMark, 0);
430  device << " <right>\n";
431  for (int j = (int)parallel.size(); --j >= 0;) {
432  const NBEdge::Connection& c = parallel[j];
433  const int fromIndex = c.fromLane - inEdge->getNumLanes();
434  const int toIndex = c.toLane - outEdge->getNumLanes();
435  device << " <lane id=\"-" << parallel.size() - j << "\" type=\"" << getLaneType(outEdge->getPermissions(c.toLane)) << "\" level=\"true\">\n";
436  device << " <link>\n";
437  device << " <predecessor id=\"" << fromIndex << "\"/>\n";
438  device << " <successor id=\"" << toIndex << "\"/>\n";
439  device << " </link>\n";
440  device << " <width sOffset=\"0\" a=\"" << outEdge->getLaneWidth(c.toLane) << "\" b=\"0\" c=\"0\" d=\"0\"/>\n";
441  std::string markType = "broken";
442  if (inEdge->isTurningDirectionAt(outEdge)) {
443  markType = "none";
444  } else if (c.fromLane == 0 && c.toLane == 0 && isOuterEdge) {
445  // solid road mark at the outer border
446  markType = "solid";
447  } else if (isOuterEdge && j > 0
448  && (outEdge->getPermissions(parallel[j - 1].toLane) & ~(SVC_PEDESTRIAN | SVC_BICYCLE)) == 0) {
449  // solid road mark to the left of sidewalk or bicycle lane
450  markType = "solid";
451  } else if (!inEdge->getToNode()->geometryLike()) {
452  // draw shorter road marks to indicate turning paths
453  LinkDirection dir = inEdge->getToNode()->getDirection(inEdge, outEdge, OptionsCont::getOptions().getBool("lefthand"));
454  if (dir == LINKDIR_LEFT || dir == LINKDIR_RIGHT || dir == LINKDIR_PARTLEFT || dir == LINKDIR_PARTRIGHT) {
455  // XXX <type><line/><type> is not rendered by odrViewer so cannot be validated
456  // device << " <type name=\"broken\" width=\"0.13\">\n";
457  // device << " <line length=\"0.5\" space=\"0.5\" tOffset=\"0\" sOffset=\"0\" rule=\"none\"/>\n";
458  // device << " </type>\n";
459  markType = "none";
460  }
461  }
462  device << " <roadMark sOffset=\"0\" type=\"" << markType << "\" weight=\"standard\" color=\"standard\" width=\"0.13\"/>\n";
463  device << " <speed sOffset=\"0\" max=\"" << c.vmax << "\"/>\n";
464  device << " </lane>\n";
465 
466  junctionDevice << " <laneLink from=\"" << fromIndex << "\" to=\"" << toIndex << "\"/>\n";
467  connectionID++;
468  }
469  device << " </right>\n";
470  device << " </laneSection>\n";
471  device << " </lanes>\n";
472  device << " <objects/>\n";
473  device << " <signals/>\n";
474  device.closeTag();
475  junctionDevice << " </connection>\n";
476 
477  return connectionID;
478 }
479 
480 
481 double
482 NWWriter_OpenDrive::writeGeomLines(const PositionVector& shape, OutputDevice& device, OutputDevice& elevationDevice, double offset) {
483  for (int j = 0; j < (int)shape.size() - 1; ++j) {
484  const Position& p = shape[j];
485  const Position& p2 = shape[j + 1];
486  const double hdg = shape.angleAt2D(j);
487  const double length = p.distanceTo2D(p2);
488  device.openTag("geometry");
489  device.writeAttr("s", offset);
490  device.writeAttr("x", p.x());
491  device.writeAttr("y", p.y());
492  device.writeAttr("hdg", hdg);
493  device.writeAttr("length", length);
494  device.openTag("line").closeTag();
495  device.closeTag();
496  elevationDevice << " <elevation s=\"" << offset << "\" a=\"" << p.z() << "\" b=\"" << (p2.z() - p.z()) / MAX2(POSITION_EPS, length) << "\" c=\"0\" d=\"0\"/>\n";
497  offset += length;
498  }
499  return offset;
500 }
501 
502 
503 void
504 NWWriter_OpenDrive::writeEmptyCenterLane(OutputDevice& device, const std::string& mark, double markWidth) {
505  device << " <center>\n";
506  device << " <lane id=\"0\" type=\"none\" level=\"true\">\n";
507  device << " <link/>\n";
508  device << " <roadMark sOffset=\"0\" type=\"" << mark << "\" weight=\"standard\" color=\"standard\" width=\"" << markWidth << "\"/>\n";
509  device << " </lane>\n";
510  device << " </center>\n";
511 }
512 
513 
514 int
515 NWWriter_OpenDrive::getID(const std::string& origID, StringBijection<int>& map, int& lastID) {
516  if (map.hasString(origID)) {
517  return map.get(origID);
518  }
519  map.insert(origID, lastID++);
520  return lastID - 1;
521 }
522 
523 
524 std::string
526  switch (permissions) {
527  case SVC_PEDESTRIAN:
528  return "sidewalk";
529  //case (SVC_BICYCLE | SVC_PEDESTRIAN):
530  // WRITE_WARNING("Ambiguous lane type (biking+driving) for road '" + roadID + "'");
531  // return "sidewalk";
532  case SVC_BICYCLE:
533  return "biking";
534  case 0:
535  // ambiguous
536  return "none";
537  case SVC_RAIL:
538  case SVC_RAIL_URBAN:
539  case SVC_RAIL_ELECTRIC:
540  return "rail";
541  case SVC_TRAM:
542  return "tram";
543  default: {
544  // complex permissions
545  if (permissions == SVCAll) {
546  return "driving";
547  } else if (isRailway(permissions)) {
548  return "rail";
549  } else if ((permissions & SVC_PASSENGER) != 0) {
550  return "driving";
551  } else {
552  return "restricted";
553  }
554  }
555  }
556 }
557 
558 
560 NWWriter_OpenDrive::getLeftLaneBorder(const NBEdge* edge, int laneIndex, double widthOffset) {
561  const bool lefthand = OptionsCont::getOptions().getBool("lefthand");
562  if (laneIndex == -1) {
563  // leftmost lane
564  laneIndex = lefthand ? 0 : (int)edge->getNumLanes() - 1;
565  }
567  // PositionVector result = edge->getLaneShape(laneIndex);
568  // (and the moveo2side)
569  // However, the lanes in SUMO have a small lateral gap (SUMO_const_laneOffset) to account for markings
570  // In OpenDRIVE this gap does not exists so we have to do all lateral
571  // computations based on the reference line
572  // This assumes that the 'stop line' for all lanes is colinear!
573  const int leftmost = lefthand ? 0 : (int)edge->getNumLanes() - 1;
574  widthOffset -= (edge->getLaneWidth(leftmost) / 2);
575  // collect lane widths from left border of edge to left border of lane to connect to
576  if (lefthand) {
577  for (int i = leftmost; i < laneIndex; i++) {
578  widthOffset += edge->getLaneWidth(i);
579  }
580  } else {
581  for (int i = leftmost; i > laneIndex; i--) {
582  widthOffset += edge->getLaneWidth(i);
583  }
584  }
585  PositionVector result = edge->getLaneShape(leftmost);
586  try {
587  result.move2side(widthOffset);
588  } catch (InvalidArgument&) { }
589  return result;
590 }
591 
593 NWWriter_OpenDrive::getRightLaneBorder(const NBEdge* edge, int laneIndex) {
594  return getLeftLaneBorder(edge, laneIndex, edge->getLaneWidth(laneIndex));
595 }
596 
597 
598 double
600  OutputDevice& device,
601  OutputDevice& elevationDevice,
602  PositionVector init,
603  double length,
604  double offset) {
605  assert(init.size() == 3 || init.size() == 4);
606 
607  // avoid division by 0
608  length = MAX2(POSITION_EPS, length);
609 
610  const Position p = init.front();
611  const double hdg = init.angleAt2D(0);
612 
613  // backup elevation values
614  const PositionVector initZ = init;
615  // translate to u,v coordinates
616  init.add(-p.x(), -p.y(), -p.z());
617  init.rotate2D(-hdg);
618 
619  // parametric coefficients
620  double aU, bU, cU, dU;
621  double aV, bV, cV, dV;
622  double aZ, bZ, cZ, dZ;
623 
624  // unfactor the Bernstein polynomials of degree 2 (or 3) and collect the coefficients
625  if (init.size() == 3) {
626  //f(x, a, b ,c) = a + (2*b - 2*a)*x + (a - 2*b + c)*x*x
627  aU = init[0].x();
628  bU = 2 * init[1].x() - 2 * init[0].x();
629  cU = init[0].x() - 2 * init[1].x() + init[2].x();
630  dU = 0;
631 
632  aV = init[0].y();
633  bV = 2 * init[1].y() - 2 * init[0].y();
634  cV = init[0].y() - 2 * init[1].y() + init[2].y();
635  dV = 0;
636 
637  // elevation is not parameteric on [0:1] but on [0:length]
638  aZ = initZ[0].z();
639  bZ = (2 * initZ[1].z() - 2 * initZ[0].z()) / length;
640  cZ = (initZ[0].z() - 2 * initZ[1].z() + initZ[2].z()) / (length * length);
641  dZ = 0;
642 
643  } else {
644  // f(x, a, b, c, d) = a + (x*((3*b) - (3*a))) + ((x*x)*((3*a) + (3*c) - (6*b))) + ((x*x*x)*((3*b) - (3*c) - a + d))
645  aU = init[0].x();
646  bU = 3 * init[1].x() - 3 * init[0].x();
647  cU = 3 * init[0].x() - 6 * init[1].x() + 3 * init[2].x();
648  dU = -init[0].x() + 3 * init[1].x() - 3 * init[2].x() + init[3].x();
649 
650  aV = init[0].y();
651  bV = 3 * init[1].y() - 3 * init[0].y();
652  cV = 3 * init[0].y() - 6 * init[1].y() + 3 * init[2].y();
653  dV = -init[0].y() + 3 * init[1].y() - 3 * init[2].y() + init[3].y();
654 
655  // elevation is not parameteric on [0:1] but on [0:length]
656  aZ = initZ[0].z();
657  bZ = (3 * initZ[1].z() - 3 * initZ[0].z()) / length;
658  cZ = (3 * initZ[0].z() - 6 * initZ[1].z() + 3 * initZ[2].z()) / (length * length);
659  dZ = (-initZ[0].z() + 3 * initZ[1].z() - 3 * initZ[2].z() + initZ[3].z()) / (length * length * length);
660  }
661 
662  device.openTag("geometry");
663  device.writeAttr("s", offset);
664  device.writeAttr("x", p.x());
665  device.writeAttr("y", p.y());
666  device.writeAttr("hdg", hdg);
667  device.writeAttr("length", length);
668 
669  device.openTag("paramPoly3");
670  device.writeAttr("aU", aU);
671  device.writeAttr("bU", bU);
672  device.writeAttr("cU", cU);
673  device.writeAttr("dU", dU);
674  device.writeAttr("aV", aV);
675  device.writeAttr("bV", bV);
676  device.writeAttr("cV", cV);
677  device.writeAttr("dV", dV);
678  device.closeTag();
679  device.closeTag();
680 
681  // write elevation
682  elevationDevice.openTag("elevation");
683  elevationDevice.writeAttr("s", offset);
684  elevationDevice.writeAttr("a", aZ);
685  elevationDevice.writeAttr("b", bZ);
686  elevationDevice.writeAttr("c", cZ);
687  elevationDevice.writeAttr("d", dZ);
688  elevationDevice.closeTag();
689 
690  return offset + length;
691 }
692 
693 
694 bool
695 NWWriter_OpenDrive::writeGeomSmooth(const PositionVector& shape, double speed, OutputDevice& device, OutputDevice& elevationDevice, double straightThresh, double& length) {
696 #ifdef DEBUG_SMOOTH_GEOM
697  if (DEBUGCOND) {
698  std::cout << "writeGeomSmooth\n n=" << shape.size() << " shape=" << toString(shape) << "\n";
699  }
700 #endif
701  bool ok = true;
702  const double longThresh = speed; // 16.0; // make user-configurable (should match the sampling rate of the source data)
703  const double curveCutout = longThresh / 2; // 8.0; // make user-configurable (related to the maximum turning rate)
704  // the length of the segment that is added for cutting a corner can be bounded by 2*curveCutout (prevent the segment to be classified as 'long')
705  assert(longThresh >= 2 * curveCutout);
706  assert(shape.size() > 2);
707  // add intermediate points wherever there is a strong angular change between long segments
708  // assume the geometry is simplified so as not to contain consecutive colinear points
709  PositionVector shape2 = shape;
710  double maxAngleDiff = 0;
711  double offset = 0;
712  for (int j = 1; j < (int)shape.size() - 1; ++j) {
713  //const double hdg = shape.angleAt2D(j);
714  const Position& p0 = shape[j - 1];
715  const Position& p1 = shape[j];
716  const Position& p2 = shape[j + 1];
717  const double dAngle = fabs(GeomHelper::angleDiff(p0.angleTo2D(p1), p1.angleTo2D(p2)));
718  const double length1 = p0.distanceTo2D(p1);
719  const double length2 = p1.distanceTo2D(p2);
720  maxAngleDiff = MAX2(maxAngleDiff, dAngle);
721 #ifdef DEBUG_SMOOTH_GEOM
722  if (DEBUGCOND) {
723  std::cout << " j=" << j << " dAngle=" << RAD2DEG(dAngle) << " length1=" << length1 << " length2=" << length2 << "\n";
724  }
725 #endif
726  if (dAngle > straightThresh
727  && (length1 > longThresh || j == 1)
728  && (length2 > longThresh || j == (int)shape.size() - 2)) {
729  shape2.insertAtClosest(shape.positionAtOffset2D(offset + length1 - MIN2(length1 - POSITION_EPS, curveCutout)));
730  shape2.insertAtClosest(shape.positionAtOffset2D(offset + length1 + MIN2(length2 - POSITION_EPS, curveCutout)));
731  shape2.removeClosest(p1);
732  }
733  offset += length1;
734  }
735  const int numPoints = (int)shape2.size();
736 #ifdef DEBUG_SMOOTH_GEOM
737  if (DEBUGCOND) {
738  std::cout << " n=" << numPoints << " shape2=" << toString(shape2) << "\n";
739  }
740 #endif
741 
742  if (maxAngleDiff < straightThresh) {
743  length = writeGeomLines(shape2, device, elevationDevice, 0);
744 #ifdef DEBUG_SMOOTH_GEOM
745  if (DEBUGCOND) {
746  std::cout << " special case: all lines. maxAngleDiff=" << maxAngleDiff << "\n";
747  }
748 #endif
749  return ok;
750  }
751 
752  // write the long segments as lines, short segments as curves
753  offset = 0;
754  for (int j = 0; j < numPoints - 1; ++j) {
755  const Position& p0 = shape2[j];
756  const Position& p1 = shape2[j + 1];
757  PositionVector line;
758  line.push_back(p0);
759  line.push_back(p1);
760  const double lineLength = line.length2D();
761  if (lineLength >= longThresh) {
762  offset = writeGeomLines(line, device, elevationDevice, offset);
763 #ifdef DEBUG_SMOOTH_GEOM
764  if (DEBUGCOND) {
765  std::cout << " writeLine=" << toString(line) << "\n";
766  }
767 #endif
768  } else {
769  // find control points
770  PositionVector begShape;
771  PositionVector endShape;
772  if (j == 0 || j == numPoints - 2) {
773  // keep the angle of the first/last segment but end at the front of the shape
774  begShape = line;
775  begShape.add(p0 - begShape.back());
776  } else if (j == 1 || p0.distanceTo2D(shape2[j - 1]) > longThresh) {
777  // use the previous segment if it is long or the first one
778  begShape.push_back(shape2[j - 1]);
779  begShape.push_back(p0);
780  } else {
781  // end at p0 with mean angle of the previous and current segment
782  begShape.push_back(shape2[j - 1]);
783  begShape.push_back(p1);
784  begShape.add(p0 - begShape.back());
785  }
786 
787  if (j == 0 || j == numPoints - 2) {
788  // keep the angle of the first/last segment but start at the end of the shape
789  endShape = line;
790  endShape.add(p1 - endShape.front());
791  } else if (j == numPoints - 3 || p1.distanceTo2D(shape2[j + 2]) > longThresh) {
792  // use the next segment if it is long or the final one
793  endShape.push_back(p1);
794  endShape.push_back(shape2[j + 2]);
795  } else {
796  // start at p1 with mean angle of the current and next segment
797  endShape.push_back(p0);
798  endShape.push_back(shape2[j + 2]);
799  endShape.add(p1 - endShape.front());
800  }
801  const double extrapolateLength = MIN2((double)25, lineLength / 4);
802  PositionVector init = NBNode::bezierControlPoints(begShape, endShape, false, extrapolateLength, extrapolateLength, ok, nullptr, straightThresh);
803  if (init.size() == 0) {
804  // could not compute control points, write line
805  offset = writeGeomLines(line, device, elevationDevice, offset);
806 #ifdef DEBUG_SMOOTH_GEOM
807  if (DEBUGCOND) {
808  std::cout << " writeLine lineLength=" << lineLength << " begShape" << j << "=" << toString(begShape) << " endShape" << j << "=" << toString(endShape) << " init" << j << "=" << toString(init) << "\n";
809  }
810 #endif
811  } else {
812  // write bezier
813  const double curveLength = bezier(init, 12).length2D();
814  offset = writeGeomPP3(device, elevationDevice, init, curveLength, offset);
815 #ifdef DEBUG_SMOOTH_GEOM
816  if (DEBUGCOND) {
817  std::cout << " writeCurve lineLength=" << lineLength << " curveLength=" << curveLength << " begShape" << j << "=" << toString(begShape) << " endShape" << j << "=" << toString(endShape) << " init" << j << "=" << toString(init) << "\n";
818  }
819 #endif
820  }
821  }
822  }
823  length = offset;
824  return ok;
825 }
826 
827 
828 void
830  // check if the shape is flat
831  bool flat = true;
832  double z = shape.size() == 0 ? 0 : shape[0].z();
833  for (int i = 1; i < (int)shape.size(); ++i) {
834  if (fabs(shape[i].z() - z) > NUMERICAL_EPS) {
835  flat = false;
836  break;
837  }
838  }
839  device << " <elevationProfile>\n";
840  if (flat) {
841  device << " <elevation s=\"0\" a=\"" << z << "\" b=\"0\" c=\"0\" d=\"0\"/>\n";
842  } else {
843  device << elevationDevice.getString();
844  }
845  device << " </elevationProfile>\n";
846 
847 }
848 
849 
850 void
852  if (e->getNumLanes() > 1) {
853  // compute 'stop line' of rightmost lane
854  const PositionVector shape0 = e->getLaneShape(0);
855  assert(shape0.size() >= 2);
856  const Position& from = shape0[-2];
857  const Position& to = shape0[-1];
858  PositionVector stopLine;
859  stopLine.push_back(to);
860  stopLine.push_back(to - PositionVector::sideOffset(from, to, -1000.0));
861  // endpoints of all other lanes should be on the stop line
862  for (int lane = 1; lane < e->getNumLanes(); ++lane) {
863  const double dist = stopLine.distance2D(e->getLaneShape(lane)[-1]);
864  if (dist > NUMERICAL_EPS) {
865  WRITE_WARNING("Uneven stop line at lane '" + e->getLaneID(lane) + "' (dist=" + toString(dist) + ") cannot be represented in OpenDRIVE.");
866  }
867  }
868  }
869 }
870 
871 /****************************************************************************/
872 
#define DEBUGCOND
The link is a partial left direction.
double vmax
maximum velocity
Definition: NBEdge.h:221
OutputDevice & writeAttr(const SumoXMLAttr attr, const T &val)
writes a named attribute
Definition: OutputDevice.h:256
double ymin() const
Returns minimum y-coordinate.
Definition: Boundary.cpp:131
double length2D() const
Returns the length.
double xmax() const
Returns maximum x-coordinate.
Definition: Boundary.cpp:125
A structure which describes a connection between edges or lanes.
Definition: NBEdge.h:160
int toLane
The lane the connections yields in.
Definition: NBEdge.h:188
int numNormalConnections() const
return the number of lane-to-lane connections at this junction (excluding crossings) ...
Definition: NBNode.cpp:2992
static void writeEmptyCenterLane(OutputDevice &device, const std::string &mark, double markWidth)
is a pedestrian
std::map< std::string, NBNode * >::const_iterator begin() const
Returns the pointer to the begin of the stored nodes.
Definition: NBNodeCont.h:116
double z() const
Returns the z-position.
Definition: Position.h:67
double distance2D(const Position &p, bool perpendicular=false) const
closest 2D-distance to point p (or -1 if perpendicular is true and the point is beyond this vector) ...
NBEdge * toEdge
The edge the connections yields in.
Definition: NBEdge.h:185
EdgeVector getIncomingEdges() const
Returns the list of incoming edges unsorted.
Definition: NBEdge.cpp:1226
const Boundary & getConvBoundary() const
Returns the converted boundary.
std::map< std::string, NBNode * >::const_iterator end() const
Returns the pointer to the end of the stored nodes.
Definition: NBNodeCont.h:121
vehicle is a not electrified rail
double distanceTo2D(const Position &p2) const
returns the euclidean distance in the x-y-plane
Definition: Position.h:244
int gPrecision
the precision for floating point outputs
Definition: StdDefs.cpp:27
Position positionAtOffset2D(double pos, double lateralOffset=0) const
Returns the position at the given length.
vehicle is a bicycle
static void writeNormalEdge(OutputDevice &device, const NBEdge *e, int edgeID, int fromNodeID, int toNodeID, const bool origNames, const double straightThresh)
write normal edge to device
std::string getString() const
Returns the current content as a string.
double y() const
Returns the y-position.
Definition: Position.h:62
int SVCPermissions
bitset where each bit declares whether a certain SVC may use this edge/lane
bool usingGeoProjection() const
Returns whether a transformation from geo to metric coordinates will be performed.
The representation of a single edge during network building.
Definition: NBEdge.h:65
double x() const
Returns the x-position.
Definition: Position.h:57
vehicle is a light rail
void setPrecision(int precision=gPrecision)
Sets the precison or resets it to default.
double angleTo2D(const Position &other) const
returns the angle in the plane of the vector pointing from here to the other position ...
Definition: Position.h:254
T MAX2(T a, T b)
Definition: StdDefs.h:76
const std::vector< NBEdge::Lane > & getLanes() const
Returns the lane definitions.
Definition: NBEdge.h:589
std::map< std::string, NBEdge * >::const_iterator end() const
Returns the pointer to the end of the stored edges.
Definition: NBEdgeCont.h:193
#define RAD2DEG(x)
Definition: GeomHelper.h:39
bool getBool(const std::string &name) const
Returns the boolean-value of the named option (only for Option_Bool)
const std::string & getProjString() const
Returns the original projection definition.
const std::string & getID() const
Returns the id.
Definition: Named.h:78
bool isRailway(SVCPermissions permissions)
Returns whether an edge with the given permission is a railway edge.
const SVCPermissions SVCAll
all VClasses are allowed
A class that stores a 2D geometrical boundary.
Definition: Boundary.h:42
The link is a (hard) left direction.
vehicle is a (possibly fast moving) electric rail
#define WRITE_WARNING(msg)
Definition: MsgHandler.h:241
static OptionsCont & getOptions()
Retrieves the options.
Definition: OptionsCont.cpp:58
vehicle is a city rail
LinkDirection
The different directions a link between two lanes may take (or a stream between two edges)...
bool isSet(const std::string &name, bool failOnNonExistant=true) const
Returns the information whether the named option is set.
void insert(const std::string str, const T key, bool checkDuplicates=true)
static void writeNetwork(const OptionsCont &oc, NBNetBuilder &nb)
Writes the network into a openDRIVE-file.
static double writeGeomPP3(OutputDevice &device, OutputDevice &elevationDevice, PositionVector init, double length, double offset=0)
write geometry as a single bezier curve (paramPoly3)
std::map< std::string, NBEdge * >::const_iterator begin() const
Returns the pointer to the begin of the stored edges.
Definition: NBEdgeCont.h:185
static methods for processing the coordinates conversion for the current net
Definition: GeoConvHelper.h:53
std::string toString(const T &t, std::streamsize accuracy=gPrecision)
Definition: ToString.h:49
static bool writeGeomSmooth(const PositionVector &shape, double speed, OutputDevice &device, OutputDevice &elevationDevice, double straightThresh, double &length)
int size() const
Returns the number of nodes stored in this container.
Definition: NBNodeCont.h:257
std::string getLaneID(int lane) const
get Lane ID (Secure)
Definition: NBEdge.cpp:3022
int getNumLanes() const
Returns the number of lanes.
Definition: NBEdge.h:420
int fromLane
The lane the connections starts at.
Definition: NBEdge.h:182
A point in 2D or 3D with translation and scaling methods.
Definition: Position.h:39
NBEdgeCont & getEdgeCont()
Definition: NBNetBuilder.h:150
A list of positions.
static PositionVector getRightLaneBorder(const NBEdge *edge, int laneIndex=-1)
T get(const std::string &str) const
std::string getString(const std::string &name) const
Returns the string-value of the named option (only for Option_String)
bool geometryLike() const
whether this is structurally similar to a geometry node
Definition: NBNode.cpp:2882
Storage for edges, including some functionality operating on multiple edges.
Definition: NBEdgeCont.h:61
T MIN2(T a, T b)
Definition: StdDefs.h:70
double xmin() const
Returns minimum x-coordinate.
Definition: Boundary.cpp:119
The link is a (hard) right direction.
#define POSITION_EPS
Definition: config.h:172
const std::string & getStreetName() const
Returns the street name of this edge.
Definition: NBEdge.h:543
static PositionVector getLeftLaneBorder(const NBEdge *edge, int laneIndex=-1, double widthOffset=0)
get the left border of the given lane (the leftmost one by default)
static PositionVector bezierControlPoints(const PositionVector &begShape, const PositionVector &endShape, bool isTurnaround, double extrapolateBeg, double extrapolateEnd, bool &ok, NBNode *recordError=0, double straightThresh=DEG2RAD(5), int shapeFlag=0)
get bezier control points
Definition: NBNode.cpp:503
#define DEG2RAD(x)
Definition: GeomHelper.h:38
static std::string escapeXML(const std::string &orig, const bool maskDoubleHyphen=false)
Replaces the standard escapes by their XML entities.
The link is a partial right direction.
double getFloat(const std::string &name) const
Returns the double-value of the named option (only for Option_Float)
SVCPermissions getPermissions(int lane=-1) const
get the union of allowed classes over all lanes or for a specific lane
Definition: NBEdge.cpp:3331
void move2side(double amount)
move position vector to side using certain ammount
vehicle is a passenger car (a "normal" car)
LinkDirection getDirection(const NBEdge *const incoming, const NBEdge *const outgoing, bool leftHand=false) const
Returns the representation of the described stream&#39;s direction.
Definition: NBNode.cpp:1764
double getSpeed() const
Returns the speed allowed on this edge.
Definition: NBEdge.h:514
double getLaneWidth() const
Returns the default width of lanes of this edge.
Definition: NBEdge.h:530
void rotate2D(double angle)
static std::string getLaneType(SVCPermissions permissions)
static double writeGeomLines(const PositionVector &shape, OutputDevice &device, OutputDevice &elevationDevice, double offset=0)
write geometry as sequence of lines (sumo style)
const PositionVector & getLaneShape(int i) const
Returns the shape of the nth lane.
Definition: NBEdge.cpp:855
const EdgeVector & getIncomingEdges() const
Returns this node&#39;s incoming edges (The edges which yield in this node)
Definition: NBNode.h:250
const std::vector< Connection > & getConnections() const
Returns the connections.
Definition: NBEdge.h:867
NBNodeCont & getNodeCont()
Returns a reference to the node container.
Definition: NBNetBuilder.h:155
Instance responsible for building networks.
Definition: NBNetBuilder.h:109
static OutputDevice & getDevice(const std::string &name)
Returns the described OutputDevice.
static Position sideOffset(const Position &beg, const Position &end, const double amount)
get a side position of position vector using a offset
#define INVALID_ID
A storage for options typed value containers)
Definition: OptionsCont.h:92
double angleAt2D(int pos) const
get angle in certain position of position vector
static const GeoConvHelper & getFinal()
the coordinate transformation for writing the location element and for tracking the original coordina...
const Position getOffsetBase() const
Returns the network base.
static void addPedestrianConnection(const NBEdge *inEdge, const NBEdge *outEdge, std::vector< NBEdge::Connection > &parallel)
bool isTurningDirectionAt(const NBEdge *const edge) const
Returns whether the given edge is the opposite direction to this edge.
Definition: NBEdge.cpp:2684
Represents a single node (junction) during network building.
Definition: NBNode.h:68
Static storage of an output device and its base (abstract) implementation.
Definition: OutputDevice.h:64
bool closeTag(const std::string &comment="")
Closes the most recently opened tag and optionally adds a comment.
#define NUMERICAL_EPS
Definition: config.h:148
NBNode * getFromNode() const
Returns the origin node of the edge.
Definition: NBEdge.h:434
Container for nodes during the netbuilding process.
Definition: NBNodeCont.h:60
bool hasString(const std::string &str) const
static double angleDiff(const double angle1, const double angle2)
Returns the difference of the second angle to the first angle in radiants.
Definition: GeomHelper.cpp:167
static void checkLaneGeometries(const NBEdge *e)
check if the lane geometries are compatible with OpenDRIVE assumptions (colinear stop line) ...
void add(double xoff, double yoff, double zoff)
double ymax() const
Returns maximum y-coordinate.
Definition: Boundary.cpp:137
static int writeInternalEdge(OutputDevice &device, OutputDevice &junctionDevice, const NBEdge *inEdge, int nodeID, int edgeID, int inEdgeID, int outEdgeID, int connectionID, const std::vector< NBEdge::Connection > &parallel, const bool isOuterEdge, const double straightThresh, const std::string &centerMark)
write internal edge to device, return next connectionID
static int getID(const std::string &origID, StringBijection< int > &map, int &lastID)
NBNode * getToNode() const
Returns the destination node of the edge.
Definition: NBEdge.h:441
static void writeElevationProfile(const PositionVector &shape, OutputDevice &device, const OutputDevice_String &elevationDevice)
OutputDevice & openTag(const std::string &xmlElement)
Opens an XML tag.
void lf()
writes a line feed if applicable
Definition: OutputDevice.h:234
An output device that encapsulates an ofstream.
void bezier(int npts, double b[], int cpts, double p[])
Definition: bezier.cpp:90