]> git.mxchange.org Git - flightgear.git/blob - src/Navaids/airways.cxx
Bug #1166, slow POI parsing.
[flightgear.git] / src / Navaids / airways.cxx
1 // airways.cxx - storage of airways network, and routing between nodes
2 // Written by James Turner, started 2009.
3 //
4 // Copyright (C) 2009  Curtis L. Olson
5 //
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License as
8 // published by the Free Software Foundation; either version 2 of the
9 // License, or (at your option) any later version.
10 //
11 // This program is distributed in the hope that it will be useful, but
12 // WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // General Public License for more details.
15 //
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19
20 #ifndef HAVE_CONFIG_H
21 # include "config.h"
22 #endif
23
24 #include "airways.hxx"
25
26 #include <algorithm>
27 #include <set>
28
29 #include <simgear/sg_inlines.h>
30 #include <simgear/structure/exception.hxx>
31 #include <simgear/misc/sgstream.hxx>
32 #include <simgear/misc/sg_path.hxx>
33
34 #include <boost/foreach.hpp>
35 #include <boost/tuple/tuple.hpp>
36
37 #include <Main/globals.hxx>
38 #include <Navaids/positioned.hxx>
39 #include <Navaids/waypoint.hxx>
40 #include <Navaids/NavDataCache.hxx>
41
42 using std::make_pair;
43 using std::string;
44 using std::set;
45 using std::vector;
46
47 //#define DEBUG_AWY_SEARCH 1
48
49 namespace flightgear
50 {
51
52 //////////////////////////////////////////////////////////////////////////////
53
54 class AStarOpenNode : public SGReferenced
55 {
56 public:
57   AStarOpenNode(FGPositionedRef aNode, double aLegDist, 
58     int aAirway,
59     FGPositionedRef aDest, AStarOpenNode* aPrev) :
60     node(aNode),
61     airway(aAirway),
62     previous(aPrev)
63   { 
64     distanceFromStart = aLegDist;
65     if (previous) {
66       distanceFromStart +=  previous->distanceFromStart;
67     }
68     
69                 directDistanceToDestination = SGGeodesy::distanceM(node->geod(), aDest->geod());
70   }
71   
72   virtual ~AStarOpenNode()
73   {
74   }
75   
76   FGPositionedRef node;
77   int airway;
78   SGSharedPtr<AStarOpenNode> previous;
79   double distanceFromStart; // aka 'g(x)'
80   double directDistanceToDestination; // aka 'h(x)'
81   
82   /**
83          * aka 'f(x)'
84          */
85         double totalCost() const {
86                 return distanceFromStart + directDistanceToDestination;
87         }
88 };
89
90 typedef SGSharedPtr<AStarOpenNode> AStarOpenNodeRef;
91
92 ////////////////////////////////////////////////////////////////////////////
93
94 Airway::Network* Airway::lowLevel()
95 {
96   static Network* static_lowLevel = NULL;
97   
98   if (!static_lowLevel) {
99     static_lowLevel = new Network;
100     static_lowLevel->_networkID = 1;
101   }
102   
103   return static_lowLevel;
104 }
105
106 Airway::Network* Airway::highLevel()
107 {
108   static Network* static_highLevel = NULL;
109   if (!static_highLevel) {
110     static_highLevel = new Network;
111     static_highLevel->_networkID = 2;
112   }
113   
114   return static_highLevel;
115 }
116
117 Airway::Airway(const std::string& aIdent, double aTop, double aBottom) :
118   _ident(aIdent),
119   _topAltitudeFt(aTop),
120   _bottomAltitudeFt(aBottom)
121 {
122 }
123
124 void Airway::load(const SGPath& path)
125 {
126   std::string identStart, identEnd, name;
127   double latStart, lonStart, latEnd, lonEnd;
128   int type, base, top;
129   //int airwayIndex = 0;
130   //FGNode *n;
131
132   sg_gzifstream in( path.str() );
133   if ( !in.is_open() ) {
134     SG_LOG( SG_NAVAID, SG_ALERT, "Cannot open file: " << path.str() );
135     throw sg_io_exception("Could not open airways data", sg_location(path.str()));
136   }
137 // toss the first two lines of the file
138   in >> skipeol;
139   in >> skipeol;
140
141 // read in each remaining line of the file
142   while (!in.eof()) {
143     in >> identStart;
144
145     if (identStart == "99") {
146       break;
147     }
148     
149     in >> latStart >> lonStart >> identEnd >> latEnd >> lonEnd >> type >> base >> top >> name;
150     in >> skipeol;
151
152     // type = 1; low-altitude
153     // type = 2; high-altitude
154     Network* net = (type == 1) ? lowLevel() : highLevel();
155   
156     SGGeod startPos(SGGeod::fromDeg(lonStart, latStart)),
157       endPos(SGGeod::fromDeg(lonEnd, latEnd));
158     
159     int awy = net->findAirway(name, top, base);
160     net->addEdge(awy, startPos, identStart, endPos, identEnd);
161   } // of file line iteration
162 }
163
164 int Airway::Network::findAirway(const std::string& aName, double aTop, double aBase)
165 {
166   return NavDataCache::instance()->findAirway(_networkID, aName);
167 }
168
169 void Airway::Network::addEdge(int aWay, const SGGeod& aStartPos,
170   const std::string& aStartIdent, 
171   const SGGeod& aEndPos, const std::string& aEndIdent)
172 {
173   FGPositionedRef start = FGPositioned::findClosestWithIdent(aStartIdent, aStartPos);
174   FGPositionedRef end = FGPositioned::findClosestWithIdent(aEndIdent, aEndPos);
175     
176   if (!start) {
177     SG_LOG(SG_NAVAID, SG_DEBUG, "unknown airways start pt: '" << aStartIdent << "'");
178     start = FGPositioned::createUserWaypoint(aStartIdent, aStartPos);
179     return;
180   }
181   
182   if (!end) {
183     SG_LOG(SG_NAVAID, SG_DEBUG, "unknown airways end pt: '" << aEndIdent << "'");
184     end = FGPositioned::createUserWaypoint(aEndIdent, aEndPos);
185     return;
186   }
187   
188   NavDataCache::instance()->insertEdge(_networkID, aWay, start->guid(), end->guid());
189 }
190
191 //////////////////////////////////////////////////////////////////////////////
192
193 static double headingDiffDeg(double a, double b)
194 {
195     double rawDiff = b - a;
196     SG_NORMALIZE_RANGE(rawDiff, -180.0, 180.0);
197     return rawDiff;
198 }
199     
200 bool Airway::Network::inNetwork(PositionedID posID) const
201 {
202   NetworkMembershipDict::iterator it = _inNetworkCache.find(posID);
203   if (it != _inNetworkCache.end()) {
204     return it->second; // cached, easy
205   }
206   
207   bool r =  NavDataCache::instance()->isInAirwayNetwork(_networkID, posID);
208   _inNetworkCache.insert(it, std::make_pair(posID, r));
209   return r;
210 }
211
212 bool Airway::Network::route(WayptRef aFrom, WayptRef aTo, 
213   WayptVec& aPath)
214 {
215   if (!aFrom || !aTo) {
216     throw sg_exception("invalid waypoints to route between");
217   }
218   
219 // find closest nodes on the graph to from/to
220 // if argument waypoints are directly on the graph (which is frequently the
221 // case), note this so we don't duplicate them in the output.
222
223   FGPositionedRef from, to;
224   bool exactTo, exactFrom;
225   boost::tie(from, exactFrom) = findClosestNode(aFrom);
226   boost::tie(to, exactTo) = findClosestNode(aTo);
227   
228 #ifdef DEBUG_AWY_SEARCH
229   SG_LOG(SG_NAVAID, SG_INFO, "from:" << from->ident() << "/" << from->name());
230   SG_LOG(SG_NAVAID, SG_INFO, "to:" << to->ident() << "/" << to->name());
231 #endif
232
233   bool ok = search2(from, to, aPath);
234   if (!ok) {
235     return false;
236   }
237   
238   return cleanGeneratedPath(aFrom, aTo, aPath, exactTo, exactFrom);
239 }
240   
241 bool Airway::Network::cleanGeneratedPath(WayptRef aFrom, WayptRef aTo, WayptVec& aPath,
242                                 bool exactTo, bool exactFrom)
243 {
244   // path cleaning phase : various cases to handle here.
245   // if either the TO or FROM waypoints were 'exact', i.e part of the enroute
246   // structure, we don't want to duplicate them. This happens frequently with
247   // published SIDs and STARs.
248   // secondly, if the waypoints are NOT on the enroute structure, the course to
249   // them may be a significant dog-leg. Check how the leg course deviates
250   // from the direct course FROM->TO, and delete the first/last leg if it's more
251   // than 90 degrees out.
252   // note we delete a maximum of one leg, and no more. This is a heuristic - we
253   // could check the next (previous) legs, but at some point we'll end up
254   // deleting too much.
255   
256   const double MAX_DOG_LEG = 90.0;
257   double enrouteCourse = SGGeodesy::courseDeg(aFrom->position(), aTo->position()),
258   finalLegCourse = SGGeodesy::courseDeg(aPath.back()->position(), aTo->position());
259   
260   bool isDogLeg = fabs(headingDiffDeg(enrouteCourse, finalLegCourse)) > MAX_DOG_LEG;
261   if (exactTo || isDogLeg) {
262     aPath.pop_back();
263   }
264   
265   // edge case - if from and to are equal, which can happen, don't
266   // crash here. This happens routing EGPH -> EGCC; 'DCS' is common
267   // to the EGPH departure and EGCC STAR.
268   if (aPath.empty()) {
269     return true;
270   }
271   
272   double initialLegCourse = SGGeodesy::courseDeg(aFrom->position(), aPath.front()->position());
273   isDogLeg = fabs(headingDiffDeg(enrouteCourse, initialLegCourse)) > MAX_DOG_LEG;
274   if (exactFrom || isDogLeg) {
275     aPath.erase(aPath.begin());
276   }
277
278   return true;
279 }
280
281 std::pair<FGPositionedRef, bool> 
282 Airway::Network::findClosestNode(WayptRef aRef)
283 {
284   return findClosestNode(aRef->position());
285 }
286
287 class InAirwayFilter : public FGPositioned::Filter
288 {
289 public:
290   InAirwayFilter(Airway::Network* aNet) :
291     _net(aNet)
292   { ; }
293   
294   virtual bool pass(FGPositioned* aPos) const
295   {
296     return _net->inNetwork(aPos->guid());
297   }
298   
299   virtual FGPositioned::Type minType() const
300   { return FGPositioned::WAYPOINT; }
301   
302   virtual FGPositioned::Type maxType() const
303   { return FGPositioned::NDB; }
304   
305 private:
306   Airway::Network* _net;
307 };
308
309 std::pair<FGPositionedRef, bool> 
310 Airway::Network::findClosestNode(const SGGeod& aGeod)
311 {
312   InAirwayFilter f(this);
313   FGPositionedRef r = FGPositioned::findClosest(aGeod, 800.0, &f);
314   bool exact = false;
315   
316   if (r && (SGGeodesy::distanceM(aGeod, r->geod()) < 100.0)) {
317     exact = true; // within 100 metres, let's call that exact
318   }
319   
320   return make_pair(r, exact);
321 }
322
323 /////////////////////////////////////////////////////////////////////////////
324
325 typedef vector<AStarOpenNodeRef> OpenNodeHeap;
326
327 static void buildWaypoints(AStarOpenNodeRef aNode, WayptVec& aRoute)
328 {
329 // count the route length, and hence pre-size aRoute
330   int count = 0;
331   AStarOpenNodeRef n = aNode;
332   for (; n != NULL; ++count, n = n->previous) {;}
333   aRoute.resize(count);
334   
335 // run over the route, creating waypoints
336   for (n = aNode; n; n=n->previous) {
337     aRoute[--count] = new NavaidWaypoint(n->node, NULL);
338   }
339 }
340
341 /**
342  * Inefficent (linear) helper to find an open node in the heap
343  */
344 static AStarOpenNodeRef
345 findInOpen(const OpenNodeHeap& aHeap, FGPositioned* aPos)
346 {
347   for (unsigned int i=0; i<aHeap.size(); ++i) {
348     if (aHeap[i]->node == aPos) {
349       return aHeap[i];
350     }
351   }
352   
353   return NULL;
354 }
355
356 class HeapOrder
357 {
358 public:
359   bool operator()(AStarOpenNode* a, AStarOpenNode* b)
360   {
361     return a->totalCost() > b->totalCost();
362   }
363 };
364
365 bool Airway::Network::search2(FGPositionedRef aStart, FGPositionedRef aDest,
366   WayptVec& aRoute)
367 {  
368   typedef set<PositionedID> ClosedNodeSet;
369   
370   OpenNodeHeap openNodes;
371   ClosedNodeSet closedNodes;
372   HeapOrder ordering;
373   
374   openNodes.push_back(new AStarOpenNode(aStart, 0.0, 0, aDest, NULL));
375   
376 // A* open node iteration
377   while (!openNodes.empty()) {
378     std::pop_heap(openNodes.begin(), openNodes.end(), ordering);
379     AStarOpenNodeRef x = openNodes.back();
380     FGPositioned* xp = x->node;    
381     openNodes.pop_back();
382     closedNodes.insert(xp->guid());
383   
384 #ifdef DEBUG_AWY_SEARCH
385     SG_LOG(SG_NAVAID, SG_INFO, "x:" << xp->ident() << ", f(x)=" << x->totalCost());
386 #endif
387     
388   // check if xp is the goal; if so we're done, since there cannot be an open
389   // node with lower f(x) value.
390     if (xp == aDest) {
391       buildWaypoints(x, aRoute);
392       return true;
393     }
394     
395   // adjacent (neighbour) iteration
396     NavDataCache* cache = NavDataCache::instance();
397     BOOST_FOREACH(AirwayEdge other, cache->airwayEdgesFrom(_networkID, xp->guid())) {
398       if (closedNodes.count(other.second)) {
399         continue; // closed, ignore
400       }
401
402       FGPositioned* yp = cache->loadById(other.second);
403       double edgeDistanceM = SGGeodesy::distanceM(xp->geod(), yp->geod());
404       AStarOpenNodeRef y = findInOpen(openNodes, yp);
405       if (y) { // already open
406         double g = x->distanceFromStart + edgeDistanceM;
407         if (g > y->distanceFromStart) {
408           // worse path, ignore
409 #ifdef DEBUG_AWY_SEARCH
410           SG_LOG(SG_NAVAID, SG_INFO, "\tabandoning " << yp->ident() <<
411            " path is worse: g(y)" << y->distanceFromStart << ", g'=" << g);
412 #endif
413           continue;
414         }
415         
416       // we need to update y. Unfortunately this means rebuilding the heap,
417       // since y's score can change arbitrarily
418 #ifdef DEBUG_AWY_SEARCH
419         SG_LOG(SG_NAVAID, SG_INFO, "\tfixing up previous for new path to " << yp->ident() << ", d =" << g);
420 #endif
421         y->previous = x;
422         y->distanceFromStart = g;
423         y->airway = other.first;
424         std::make_heap(openNodes.begin(), openNodes.end(), ordering);
425       } else { // not open, insert a new node for y into the heap
426         y = new AStarOpenNode(yp, edgeDistanceM, other.first, aDest, x);
427 #ifdef DEBUG_AWY_SEARCH
428         SG_LOG(SG_NAVAID, SG_INFO, "\ty=" << yp->ident() << ", f(y)=" << y->totalCost());
429 #endif
430         openNodes.push_back(y);
431         std::push_heap(openNodes.begin(), openNodes.end(), ordering);
432       }
433     } // of neighbour iteration
434   } // of open node iteration
435   
436   SG_LOG(SG_NAVAID, SG_INFO, "A* failed to find route");
437   return false;
438 }
439
440 } // of namespace flightgear