SUMO - Simulation of Urban MObility
NBHeightMapper.cpp
Go to the documentation of this file.
1 /****************************************************************************/
9 // Set z-values for all network positions based on data from a height map
10 /****************************************************************************/
11 // SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/
12 // Copyright (C) 2011-2016 DLR (http://www.dlr.de/) and contributors
13 /****************************************************************************/
14 //
15 // This file is part of SUMO.
16 // SUMO is free software: you can redistribute it and/or modify
17 // it under the terms of the GNU General Public License as published by
18 // the Free Software Foundation, either version 3 of the License, or
19 // (at your option) any later version.
20 //
21 /****************************************************************************/
22 
23 
24 // ===========================================================================
25 // included modules
26 // ===========================================================================
27 #ifdef _MSC_VER
28 #include <windows_config.h>
29 #else
30 #include <config.h>
31 #endif
32 
33 #include <string>
35 #include <utils/common/ToString.h>
38 #include <utils/geom/GeomHelper.h>
39 #include "NBHeightMapper.h"
41 #include <utils/common/RGBColor.h>
42 
43 #ifdef HAVE_GDAL
44 #include <ogrsf_frmts.h>
45 #include <ogr_api.h>
46 #include <gdal_priv.h>
47 #endif
48 
49 #ifdef CHECK_MEMORY_LEAKS
50 #include <foreign/nvwa/debug_new.h>
51 #endif // CHECK_MEMORY_LEAKS
52 
53 // ===========================================================================
54 // static members
55 // ===========================================================================
57 
58 // ===========================================================================
59 // method definitions
60 // ===========================================================================
61 
62 
64  myRTree(&Triangle::addSelf), myRaster(0) {
65 }
66 
67 
69  clearData();
70 }
71 
72 
73 const NBHeightMapper&
75  return Singleton;
76 }
77 
78 
79 bool
81  return myRaster != 0 || myTriangles.size() > 0;
82 }
83 
84 
86 NBHeightMapper::getZ(const Position& geo) const {
87  if (!ready()) {
88  WRITE_WARNING("Cannot supply height since no height data was loaded");
89  return 0;
90  }
91  if (myRaster != 0) {
92  SUMOReal result = -1e6;
93  if (myBoundary.around(geo)) {
94  const int xSize = int((myBoundary.xmax() - myBoundary.xmin()) / mySizeOfPixel.x() + .5);
95  const int iX = int((geo.x() - myBoundary.xmin()) / mySizeOfPixel.x() + .5);
96  const int iY = int((geo.y() - myBoundary.ymax()) / mySizeOfPixel.y() + .5);
97  result = myRaster[iY * xSize + iX];
98  }
99  if (result > -1e5 && result < 1e5) {
100  return result;
101  }
102  }
103  // coordinates in degrees hence a small search window
104  float minB[2];
105  float maxB[2];
106  minB[0] = (float)geo.x() - 0.00001f;
107  minB[1] = (float)geo.y() - 0.00001f;
108  maxB[0] = (float)geo.x() + 0.00001f;
109  maxB[1] = (float)geo.y() + 0.00001f;
110  QueryResult queryResult;
111  int hits = myRTree.Search(minB, maxB, queryResult);
112  Triangles result = queryResult.triangles;
113  assert(hits == (int)result.size());
114  UNUSED_PARAMETER(hits); // only used for assertion
115 
116  for (Triangles::iterator it = result.begin(); it != result.end(); it++) {
117  const Triangle* triangle = *it;
118  if (triangle->contains(geo)) {
119  return triangle->getZ(geo);
120  }
121  }
122  WRITE_WARNING("Could not get height data for coordinate " + toString(geo));
123  return 0;
124 }
125 
126 
127 void
129  Triangle* triangle = new Triangle(corners);
130  myTriangles.push_back(triangle);
131  Boundary b = corners.getBoxBoundary();
132  const float cmin[2] = {(float) b.xmin(), (float) b.ymin()};
133  const float cmax[2] = {(float) b.xmax(), (float) b.ymax()};
134  myRTree.Insert(cmin, cmax, triangle);
135 }
136 
137 
138 void
140  if (oc.isSet("heightmap.geotiff")) {
141  // parse file(s)
142  std::vector<std::string> files = oc.getStringVector("heightmap.geotiff");
143  for (std::vector<std::string>::const_iterator file = files.begin(); file != files.end(); ++file) {
144  PROGRESS_BEGIN_MESSAGE("Parsing from GeoTIFF '" + *file + "'");
145  int numFeatures = Singleton.loadTiff(*file);
147  " done (parsed " + toString(numFeatures) +
148  " features, Boundary: " + toString(Singleton.getBoundary()) + ").");
149  }
150  }
151  if (oc.isSet("heightmap.shapefiles")) {
152  // parse file(s)
153  std::vector<std::string> files = oc.getStringVector("heightmap.shapefiles");
154  for (std::vector<std::string>::const_iterator file = files.begin(); file != files.end(); ++file) {
155  PROGRESS_BEGIN_MESSAGE("Parsing from shape-file '" + *file + "'");
156  int numFeatures = Singleton.loadShapeFile(*file);
158  " done (parsed " + toString(numFeatures) +
159  " features, Boundary: " + toString(Singleton.getBoundary()) + ").");
160  }
161  }
162 }
163 
164 
165 int
166 NBHeightMapper::loadShapeFile(const std::string& file) {
167 #ifdef HAVE_GDAL
168 #if GDAL_VERSION_MAJOR < 2
169  OGRRegisterAll();
170  OGRDataSource* ds = OGRSFDriverRegistrar::Open(file.c_str(), FALSE);
171 #else
172  GDALAllRegister();
173  GDALDataset* ds = (GDALDataset*) GDALOpen(file.c_str(), GA_ReadOnly);
174 #endif
175  if (ds == NULL) {
176  throw ProcessError("Could not open shape file '" + file + "'.");
177  }
178 
179  // begin file parsing
180  OGRLayer* layer = ds->GetLayer(0);
181  layer->ResetReading();
182 
183  // triangle coordinates are stored in WGS84 and later matched with network coordinates in WGS84
184  // build coordinate transformation
185  OGRSpatialReference* sr_src = layer->GetSpatialRef();
186  OGRSpatialReference sr_dest;
187  sr_dest.SetWellKnownGeogCS("WGS84");
188  OGRCoordinateTransformation* toWGS84 = OGRCreateCoordinateTransformation(sr_src, &sr_dest);
189  if (toWGS84 == 0) {
190  WRITE_WARNING("Could not create geocoordinates converter; check whether proj.4 is installed.");
191  }
192 
193  int numFeatures = 0;
194  OGRFeature* feature;
195  layer->ResetReading();
196  while ((feature = layer->GetNextFeature()) != NULL) {
197  OGRGeometry* geom = feature->GetGeometryRef();
198  assert(geom != 0);
199 
200  // @todo gracefull handling of shapefiles with unexpected contents or any error handling for that matter
201  assert(std::string(geom->getGeometryName()) == std::string("POLYGON"));
202  // try transform to wgs84
203  geom->transform(toWGS84);
204  OGRLinearRing* cgeom = ((OGRPolygon*) geom)->getExteriorRing();
205  // assume TIN with with 4 points and point0 == point3
206  assert(cgeom->getNumPoints() == 4);
207  PositionVector corners;
208  for (int j = 0; j < 3; j++) {
209  Position pos((SUMOReal) cgeom->getX(j), (SUMOReal) cgeom->getY(j), (SUMOReal) cgeom->getZ(j));
210  corners.push_back(pos);
211  myBoundary.add(pos);
212  }
213  addTriangle(corners);
214  numFeatures++;
215 
216  /*
217  OGRwkbGeometryType gtype = geom->getGeometryType();
218  switch (gtype) {
219  case wkbPolygon: {
220  break;
221  }
222  case wkbPoint: {
223  WRITE_WARNING("got wkbPoint");
224  break;
225  }
226  case wkbLineString: {
227  WRITE_WARNING("got wkbLineString");
228  break;
229  }
230  case wkbMultiPoint: {
231  WRITE_WARNING("got wkbMultiPoint");
232  break;
233  }
234  case wkbMultiLineString: {
235  WRITE_WARNING("got wkbMultiLineString");
236  break;
237  }
238  case wkbMultiPolygon: {
239  WRITE_WARNING("got wkbMultiPolygon");
240  break;
241  }
242  default:
243  WRITE_WARNING("Unsupported shape type occured");
244  break;
245  }
246  */
247  OGRFeature::DestroyFeature(feature);
248  }
249 #if GDAL_VERSION_MAJOR < 2
250  OGRDataSource::DestroyDataSource(ds);
251 #else
252  GDALClose(ds);
253 #endif
254  OCTDestroyCoordinateTransformation(toWGS84);
255  OGRCleanupAll();
256  return numFeatures;
257 #else
258  WRITE_ERROR("Cannot load shape file since SUMO was compiled without GDAL support.");
259  return 0;
260 #endif
261 }
262 
263 
264 int
265 NBHeightMapper::loadTiff(const std::string& file) {
266 #ifdef HAVE_GDAL
267  GDALAllRegister();
268  GDALDataset* poDataset = (GDALDataset*)GDALOpen(file.c_str(), GA_ReadOnly);
269  if (poDataset == 0) {
270  WRITE_ERROR("Cannot load GeoTIFF file.");
271  return 0;
272  }
273  const int xSize = poDataset->GetRasterXSize();
274  const int ySize = poDataset->GetRasterYSize();
275  double adfGeoTransform[6];
276  if (poDataset->GetGeoTransform(adfGeoTransform) == CE_None) {
277  Position topLeft(adfGeoTransform[0], adfGeoTransform[3]);
278  mySizeOfPixel.set(adfGeoTransform[1], adfGeoTransform[5]);
279  const double horizontalSize = xSize * mySizeOfPixel.x();
280  const double verticalSize = ySize * mySizeOfPixel.y();
281  myBoundary.add(topLeft);
282  myBoundary.add(topLeft.x() + horizontalSize, topLeft.y() + verticalSize);
283  } else {
284  WRITE_ERROR("Could not parse geo information from " + file + ".");
285  return 0;
286  }
287  const int picSize = xSize * ySize;
288  myRaster = (int16_t*)CPLMalloc(sizeof(int16_t) * picSize);
289  for (int i = 1; i <= poDataset->GetRasterCount(); i++) {
290  GDALRasterBand* poBand = poDataset->GetRasterBand(i);
291  if (poBand->GetColorInterpretation() != GCI_GrayIndex) {
292  WRITE_ERROR("Unknown color band in " + file + ".");
293  clearData();
294  break;
295  }
296  if (poBand->GetRasterDataType() != GDT_Int16) {
297  WRITE_ERROR("Unknown data type in " + file + ".");
298  clearData();
299  break;
300  }
301  assert(xSize == poBand->GetXSize() && ySize == poBand->GetYSize());
302  if (poBand->RasterIO(GF_Read, 0, 0, xSize, ySize, myRaster, xSize, ySize, GDT_Int16, 0, 0) == CE_Failure) {
303  WRITE_ERROR("Failure in reading " + file + ".");
304  clearData();
305  break;
306  }
307  }
308  GDALClose(poDataset);
309  return picSize;
310 #else
311  WRITE_ERROR("Cannot load GeoTIFF file since SUMO was compiled without GDAL support.");
312  return 0;
313 #endif
314 }
315 
316 
317 void
319  for (Triangles::iterator it = myTriangles.begin(); it != myTriangles.end(); it++) {
320  delete *it;
321  }
322  myTriangles.clear();
323 #ifdef HAVE_GDAL
324  if (myRaster != 0) {
325  CPLFree(myRaster);
326  myRaster = 0;
327  }
328 #endif
329  myBoundary.reset();
330 }
331 
332 
333 // ===========================================================================
334 // Triangle member methods
335 // ===========================================================================
337  myCorners(corners) {
338  assert(myCorners.size() == 3);
339  // @todo assert non-colinearity
340 }
341 
342 
343 void
345  queryResult.triangles.push_back(this);
346 }
347 
348 
349 bool
351  return myCorners.around(pos);
352 }
353 
354 
355 SUMOReal
357  // en.wikipedia.org/wiki/Line-plane_intersection
358  Position p0 = myCorners.front();
359  Position line(0, 0, 1);
360  p0.sub(geo); // p0 - l0
361  Position normal = normalVector();
362  return p0.dotProduct(normal) / line.dotProduct(normal);
363 }
364 
365 
366 Position
368  // @todo maybe cache result to avoid multiple computations?
369  Position side1 = myCorners[1] - myCorners[0];
370  Position side2 = myCorners[2] - myCorners[0];
371  return side1.crossProduct(side2);
372 }
373 
374 
375 /****************************************************************************/
376 
void sub(SUMOReal dx, SUMOReal dy)
Substracts the given position from this one.
Definition: Position.h:139
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) ...
SUMOReal getZ(const Position &geo) const
returns the projection of the give geoCoordinate (WGS84) onto triangle plane
Triangles myTriangles
bool ready() const
returns whether the NBHeightMapper has data
bool around(const Position &p, SUMOReal offset=0) const
Returns whether the boundary contains the given coordinate.
Definition: Boundary.cpp:148
Position normalVector() const
returns the normal vector for this triangles plane
int loadShapeFile(const std::string &file)
load height data from Arcgis-shape file and returns the number of parsed features ...
SUMOReal getZ(const Position &geo) const
returns height for the given geo coordinate (WGS84)
SUMOReal ymin() const
Returns minimum y-coordinate.
Definition: Boundary.cpp:124
SUMOReal xmin() const
Returns minimum x-coordinate.
Definition: Boundary.cpp:112
Triangle(const PositionVector &corners)
void addTriangle(PositionVector corners)
adds one triangles worth of height data
void clearData()
clears loaded data
static NBHeightMapper Singleton
the singleton instance
bool around(const Position &p, SUMOReal offset=0) const
Returns the information whether the position vector describes a polygon lying around the given point...
NBHeightMapper()
private constructor and destructor (Singleton)
SUMOReal x() const
Returns the x-position.
Definition: Position.h:63
#define UNUSED_PARAMETER(x)
Definition: StdDefs.h:39
SUMOReal xmax() const
Returns maximum x-coordinate.
Definition: Boundary.cpp:118
A class that stores a 2D geometrical boundary.
Definition: Boundary.h:48
#define WRITE_WARNING(msg)
Definition: MsgHandler.h:200
int loadTiff(const std::string &file)
load height data from GeoTIFF file and returns the number of non void pixels
static const NBHeightMapper & get()
return the singleton instance (maybe 0)
class for cirumventing the const-restriction of RTree::Search-context
static void loadIfSet(OptionsCont &oc)
loads heigh map data if any loading options are set
TRIANGLE_RTREE_QUAL myRTree
The RTree for spatial queries.
Position crossProduct(const Position &pos)
returns the cross product between this point and the second one
Definition: Position.h:249
A point in 2D or 3D with translation and scaling methods.
Definition: Position.h:46
signed short int16_t
Definition: stdint.h:76
A list of positions.
std::vector< const Triangle * > Triangles
#define PROGRESS_BEGIN_MESSAGE(msg)
Definition: MsgHandler.h:202
static MsgHandler * getMessageInstance()
Returns the instance to add normal messages to.
Definition: MsgHandler.cpp:62
int16_t * myRaster
raster height information in m
bool contains(const Position &pos) const
checks whether pos lies within triangle (only checks x,y)
std::string toString(const T &t, std::streamsize accuracy=OUTPUT_ACCURACY)
Definition: ToString.h:55
Position mySizeOfPixel
dimensions of one pixel in raster data
Boundary myBoundary
convex boundary of all known triangles;
#define WRITE_ERROR(msg)
Definition: MsgHandler.h:206
void add(SUMOReal x, SUMOReal y)
Makes the boundary include the given coordinate.
Definition: Boundary.cpp:76
void reset()
Resets the boundary.
Definition: Boundary.cpp:66
SUMOReal dotProduct(const Position &pos)
returns the dot product (scalar product) between this point and the second one
Definition: Position.h:257
SUMOReal y() const
Returns the y-position.
Definition: Position.h:68
PositionVector myCorners
the corners of the triangle
A storage for options typed value containers)
Definition: OptionsCont.h:108
void set(SUMOReal x, SUMOReal y)
Definition: Position.h:78
void addSelf(const QueryResult &queryResult) const
callback for RTree search
#define SUMOReal
Definition: config.h:214
SUMOReal ymax() const
Returns maximum y-coordinate.
Definition: Boundary.cpp:130
const Boundary & getBoundary()
returns the convex boundary of all known triangles
Boundary getBoxBoundary() const
Returns a boundary enclosing this list of lines.
Set z-values for all network positions based on data from a height map.
bool isSet(const std::string &name, bool failOnNonExistant=true) const
Returns the information whether the named option is set.
void endProcessMsg(std::string msg)
Ends a process information.
Definition: MsgHandler.cpp:131