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