]> git.mxchange.org Git - flightgear.git/blob - src/Navaids/positioned.cxx
Directly associate runways objects with their ILS navrecord (if one exists)
[flightgear.git] / src / Navaids / positioned.cxx
1 // positioned.cxx - base class for objects which are positioned 
2 //
3 // Copyright (C) 2008 James Turner
4 //
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License as
7 // published by the Free Software Foundation; either version 2 of the
8 // License, or (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful, but
11 // WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 //
19 // $Id$
20
21 #ifdef HAVE_CONFIG_H
22 #  include "config.h"
23 #endif
24
25 #include <map>
26 #include <set>
27 #include <algorithm> // for sort
28 #include <locale> // for char-traits toupper
29
30 #include <iostream>
31
32 #include <simgear/math/sg_geodesy.hxx>
33 #include <simgear/timing/timestamp.hxx>
34
35 #include "positioned.hxx"
36
37 typedef std::multimap<std::string, FGPositioned*> NamedPositionedIndex;
38 typedef std::pair<NamedPositionedIndex::const_iterator, NamedPositionedIndex::const_iterator> NamedIndexRange;
39
40 using std::lower_bound;
41 using std::upper_bound;
42
43 /**
44  * Order positioned elements by type, then pointer address. This allows us to
45  * use range searches (lower_ and upper_bound) to grab items of a particular
46  * type out of bucket efficently.
47  */
48 class OrderByType
49 {
50 public:
51   bool operator()(const FGPositioned* a, const FGPositioned* b) const
52   {
53     if (a->type() == b->type()) return a < b;
54     return a->type() < b->type();
55   }
56 };
57
58 class LowerLimitOfType
59 {
60 public:
61   bool operator()(const FGPositioned* a, const FGPositioned::Type b) const
62   {
63     return a->type() < b;
64   }
65
66   bool operator()(const FGPositioned::Type a, const FGPositioned* b) const
67   {
68     return a < b->type();
69   }
70
71   // The operator below is required by VS2005 in debug mode
72   bool operator()(const FGPositioned* a, const FGPositioned* b) const
73   {
74     return a->type() < b->type();
75   }
76 };
77
78
79 typedef std::set<FGPositioned*, OrderByType> BucketEntry;
80 typedef std::map<long int, BucketEntry> SpatialPositionedIndex;
81
82 static NamedPositionedIndex global_namedIndex;
83 static SpatialPositionedIndex global_spatialIndex;
84
85 SpatialPositionedIndex::iterator
86 bucketEntryForPositioned(FGPositioned* aPos)
87 {
88   int bucketIndex = aPos->bucket().gen_index();
89   SpatialPositionedIndex::iterator it = global_spatialIndex.find(bucketIndex);
90   if (it != global_spatialIndex.end()) {
91     return it;
92   }
93   
94   // create a new BucketEntry
95   return global_spatialIndex.insert(it, std::make_pair(bucketIndex, BucketEntry()));
96 }
97
98 static void
99 addToIndices(FGPositioned* aPos)
100 {
101   assert(aPos);
102   if (!aPos->ident().empty()) {
103     global_namedIndex.insert(global_namedIndex.begin(), 
104       std::make_pair(aPos->ident(), aPos));
105   }
106     
107   SpatialPositionedIndex::iterator it = bucketEntryForPositioned(aPos);
108   it->second.insert(aPos);
109 }
110
111 static void
112 removeFromIndices(FGPositioned* aPos)
113 {
114   assert(aPos);
115   
116   if (!aPos->ident().empty()) {
117     NamedPositionedIndex::iterator it = global_namedIndex.find(aPos->ident());
118     while (it != global_namedIndex.end() && (it->first == aPos->ident())) {
119       if (it->second == aPos) {
120         global_namedIndex.erase(it);
121         break;
122       }
123       
124       ++it;
125     } // of multimap walk
126   }
127   
128   SpatialPositionedIndex::iterator sit = bucketEntryForPositioned(aPos);
129   sit->second.erase(aPos);
130 }
131
132 static void
133 spatialFilterInBucket(const SGBucket& aBucket, FGPositioned::Filter* aFilter, FGPositioned::List& aResult)
134 {
135   SpatialPositionedIndex::const_iterator it;
136   it = global_spatialIndex.find(aBucket.gen_index());
137   if (it == global_spatialIndex.end()) {
138     return;
139   }
140   
141   BucketEntry::const_iterator l = it->second.begin();
142   BucketEntry::const_iterator u = it->second.end();
143
144   if (!aFilter) { // pass everything
145     aResult.insert(aResult.end(), l, u);
146     return;
147   }
148
149   if (aFilter->hasTypeRange()) {
150     // avoid many calls to the filter hook
151     l = lower_bound(it->second.begin(), it->second.end(), aFilter->minType(), LowerLimitOfType());
152     u = upper_bound(l, it->second.end(), aFilter->maxType(), LowerLimitOfType());
153   }
154
155   for ( ; l != u; ++l) {
156     if ((*aFilter)(*l)) {
157       aResult.push_back(*l);
158     }
159   }
160 }
161
162 static void
163 spatialFind(const SGGeod& aPos, double aRange, 
164   FGPositioned::Filter* aFilter, FGPositioned::List& aResult)
165 {
166   SGBucket buck(aPos);
167   double lat = aPos.getLatitudeDeg(),
168     lon = aPos.getLongitudeDeg();
169   
170   int bx = (int)( aRange*SG_NM_TO_METER / buck.get_width_m() / 2);
171   int by = (int)( aRange*SG_NM_TO_METER / buck.get_height_m() / 2 );
172     
173   // loop over bucket range 
174   for ( int i=-bx; i<=bx; i++) {
175     for ( int j=-by; j<=by; j++) {
176       spatialFilterInBucket(sgBucketOffset(lon, lat, i, j), aFilter, aResult);
177     } // of j-iteration
178   } // of i-iteration  
179 }
180
181 /**
182  */
183 class RangePredictate
184 {
185 public:
186   RangePredictate(const SGGeod& aOrigin, double aRange) :
187     mOrigin(SGVec3d::fromGeod(aOrigin)),
188     mRangeSqr(aRange * aRange)
189   { ; }
190   
191   bool operator()(const FGPositionedRef& aPos)
192   {
193     double dSqr = distSqr(aPos->cart(), mOrigin);
194     return (dSqr > mRangeSqr);
195   }
196   
197 private:
198   SGVec3d mOrigin;
199   double mRangeSqr;
200 };
201
202 static void
203 filterListByRange(const SGGeod& aPos, double aRange, FGPositioned::List& aResult)
204 {
205   RangePredictate pred(aPos, aRange * SG_NM_TO_METER);
206   FGPositioned::List::iterator newEnd; 
207   newEnd = std::remove_if(aResult.begin(), aResult.end(), pred);
208   aResult.erase(newEnd, aResult.end());
209 }
210
211 class DistanceOrdering
212 {
213 public:
214   DistanceOrdering(const SGGeod& aPos) :
215     mPos(SGVec3d::fromGeod(aPos))
216   { }
217   
218   bool operator()(const FGPositionedRef& a, const FGPositionedRef& b) const
219   {
220     double dA = distSqr(a->cart(), mPos),
221       dB = distSqr(b->cart(), mPos);
222     return dA < dB;
223   }
224
225 private:
226   SGVec3d mPos;
227 };
228
229 static void
230 sortByDistance(const SGGeod& aPos, FGPositioned::List& aResult)
231 {
232   std::sort(aResult.begin(), aResult.end(), DistanceOrdering(aPos));
233 }
234
235 static FGPositionedRef
236 namedFindClosest(const std::string& aIdent, const SGGeod& aOrigin, FGPositioned::Filter* aFilter)
237 {
238   NamedIndexRange range = global_namedIndex.equal_range(aIdent);
239   if (range.first == range.second) {
240     return NULL;
241   }
242   
243 // common case, only one result. looks a bit ugly because these are
244 // sequential iterators, not random-access ones
245   NamedPositionedIndex::const_iterator check = range.first;
246   if (++check == range.second) {
247     // excellent, only one match in the range
248     FGPositioned* r = range.first->second;
249     if (aFilter) {
250       if (aFilter->hasTypeRange() && !aFilter->passType(r->type())) {
251         return NULL;
252       }
253       
254       if (!aFilter->pass(r)) {
255         return NULL;
256       }
257     } // of have a filter
258   
259     return r;
260   } // of short-circuit logic for single-element range
261   
262 // multiple matches, we need to actually check the distance to each one
263   double minDist = HUGE_VAL;
264   FGPositionedRef result;
265   NamedPositionedIndex::const_iterator it = range.first;
266   SGVec3d cartOrigin(SGVec3d::fromGeod(aOrigin));
267   
268   for (; it != range.second; ++it) {
269     FGPositioned* r = it->second;
270     if (aFilter) {
271       if (aFilter->hasTypeRange() && !aFilter->passType(r->type())) {
272         continue;
273       }
274       
275       if (!aFilter->pass(r)) {
276         continue;
277       }
278     }
279     
280   // find distance
281     double d2 = distSqr(cartOrigin, r->cart());
282     if (d2 < minDist) {
283       minDist = d2;
284       result = r;
285     }
286   }
287   
288   return result;
289 }
290
291 static FGPositioned::List
292 spatialGetClosest(const SGGeod& aPos, unsigned int aN, double aCutoffNm, FGPositioned::Filter* aFilter)
293 {
294   FGPositioned::List result;
295   int radius = 1; // start at 1, radius 0 is handled explicitly
296   SGBucket buck;
297   double lat = aPos.getLatitudeDeg(),
298     lon = aPos.getLongitudeDeg();
299   // final cutoff is in metres, and scaled to account for testing the corners
300   // of the 'box' instead of the centre of each edge
301   double cutoffM = aCutoffNm * SG_NM_TO_METER * 1.5;
302   
303   // base case, simplifes loop to do it seperately here
304   spatialFilterInBucket(sgBucketOffset(lon, lat, 0, 0), aFilter, result);
305
306   for (;result.size() < aN; ++radius) {
307     // cutoff check
308     double az1, az2, d1, d2;
309     SGGeodesy::inverse(aPos, sgBucketOffset(lon, lat, -radius, -radius).get_center(), az1, az2, d1);
310     SGGeodesy::inverse(aPos, sgBucketOffset(lon, lat, radius, radius).get_center(), az1, az2, d2);  
311       
312     if ((d1 > cutoffM) && (d2 > cutoffM)) {
313       //std::cerr << "spatialGetClosest terminating due to range cutoff" << std::endl;
314       break;
315     }
316     
317     FGPositioned::List hits;
318     for ( int i=-radius; i<=radius; i++) {
319       spatialFilterInBucket(sgBucketOffset(lon, lat, i, -radius), aFilter, hits);
320       spatialFilterInBucket(sgBucketOffset(lon, lat, -radius, i), aFilter, hits);
321       spatialFilterInBucket(sgBucketOffset(lon, lat, i, radius), aFilter, hits);
322       spatialFilterInBucket(sgBucketOffset(lon, lat, radius, i), aFilter, hits);
323     }
324
325     result.insert(result.end(), hits.begin(), hits.end()); // append
326   } // of outer loop
327   
328   sortByDistance(aPos, result);
329   if (result.size() > aN) {
330     result.resize(aN); // truncate at requested number of matches
331   }
332   
333   return result;
334 }
335
336 //////////////////////////////////////////////////////////////////////////////
337
338 class OrderByName
339 {
340 public:
341   bool operator()(FGPositioned* a, FGPositioned* b) const
342   {
343     return a->name() < b->name();
344   }
345 };
346
347 /**
348  * A special purpose helper (imported by FGAirport::searchNamesAndIdents) to
349  * implement the AirportList dialog. It's unfortunate that it needs to reside
350  * here, but for now it's least ugly solution.
351  */
352 char** searchAirportNamesAndIdents(const std::string& aFilter)
353 {
354   const std::ctype<char> &ct = std::use_facet<std::ctype<char> >(std::locale());
355   std::string filter(aFilter);
356   bool hasFilter = !filter.empty();
357   if (hasFilter) {
358     ct.toupper((char *)filter.data(), (char *)filter.data() + filter.size());
359   }
360   
361   NamedPositionedIndex::const_iterator it = global_namedIndex.begin();
362   NamedPositionedIndex::const_iterator end = global_namedIndex.end();
363   
364   // note this is a vector of raw pointers, not smart pointers, because it
365   // may get very large and smart-pointer-atomicity-locking then becomes a
366   // bottleneck for this case.
367   std::vector<FGPositioned*> matches;
368   std::string upper;
369   
370   for (; it != end; ++it) {
371     FGPositioned::Type ty = it->second->type();
372     if ((ty < FGPositioned::AIRPORT) || (ty > FGPositioned::SEAPORT)) {
373       continue;
374     }
375     
376     if (hasFilter && (it->second->ident().find(aFilter) == std::string::npos)) {
377       upper = it->second->name(); // string copy, sadly
378       ct.toupper((char *)upper.data(), (char *)upper.data() + upper.size());
379       if (upper.find(aFilter) == std::string::npos) {
380         continue;
381       }
382     }
383     
384     matches.push_back(it->second);
385   }
386   
387   // sort alphabetically on name
388   std::sort(matches.begin(), matches.end(), OrderByName());
389   
390   // convert results to format comptible with puaList
391   unsigned int numMatches = matches.size();
392   char** result = new char*[numMatches + 1];
393   result[numMatches] = NULL; // end-of-list marker
394   
395   // nasty code to avoid excessive string copying and allocations.
396   // We format results as follows (note whitespace!):
397   //   ' name-of-airport-chars   (ident)'
398   // so the total length is:
399   //    1 + strlen(name) + 4 + 4 (for the ident) + 1 + 1 (for the null)
400   // which gives a grand total of 11 + the length of the name.
401   // note the ident is sometimes only three letters for non-ICAO small strips
402   for (unsigned int i=0; i<numMatches; ++i) {
403     int nameLength = matches[i]->name().size();
404     int icaoLength = matches[i]->ident().size();
405     char* entry = new char[nameLength + 11];
406     char* dst = entry;
407     *dst++ = ' ';
408     memcpy(dst, matches[i]->name().c_str(), nameLength);
409     dst += nameLength;
410     *dst++ = ' ';
411     *dst++ = ' ';
412     *dst++ = ' ';
413     *dst++ = '(';
414     memcpy(dst, matches[i]->ident().c_str(), icaoLength);
415     dst += icaoLength;
416     *dst++ = ')';
417     *dst++ = 0;
418     result[i] = entry;
419   }
420   
421   return result;
422 }
423
424 ///////////////////////////////////////////////////////////////////////////////
425
426 bool
427 FGPositioned::Filter::hasTypeRange() const
428 {
429   assert(minType() <= maxType());
430   return (minType() != INVALID) && (maxType() != INVALID);
431 }
432
433 bool
434 FGPositioned::Filter::passType(Type aTy) const
435 {
436   assert(hasTypeRange());
437   return (minType() <= aTy) && (maxType() >= aTy);
438 }
439
440 ///////////////////////////////////////////////////////////////////////////////
441
442 FGPositioned::FGPositioned(Type ty, const std::string& aIdent, const SGGeod& aPos, bool aIndexed) :
443   mType(ty),
444   mPosition(aPos),
445   mIdent(aIdent)
446 {  
447   SGReferenced::get(this); // hold an owning ref, for the moment
448   
449   if (aIndexed) {
450     assert(ty != TAXIWAY);
451     addToIndices(this);
452   }
453 }
454
455 FGPositioned::~FGPositioned()
456 {
457   //std::cout << "destroying:" << mIdent << "/" << nameForType(mType) << std::endl;
458   removeFromIndices(this);
459 }
460
461 SGBucket
462 FGPositioned::bucket() const
463 {
464   return SGBucket(mPosition);
465 }
466
467 SGVec3d
468 FGPositioned::cart() const
469 {
470   return SGVec3d::fromGeod(mPosition);
471 }
472
473 const char* FGPositioned::nameForType(Type aTy)
474 {
475  switch (aTy) {
476  case RUNWAY: return "runway";
477  case TAXIWAY: return "taxiway";
478  case PARK_STAND: return "parking stand";
479  case FIX: return "fix";
480  case VOR: return "VOR";
481  case NDB: return "NDB";
482  case ILS: return "ILS";
483  case LOC: return "localiser";
484  case GS: return "glideslope";
485  case OM: return "outer-marker";
486  case MM: return "middle-marker";
487  case IM: return "inner-marker";
488  case AIRPORT: return "airport";
489  case HELIPORT: return "heliport";
490  case SEAPORT: return "seaport";
491  case WAYPOINT: return "waypoint";
492  case DME: return "dme";
493  case TACAN: return "tacan";
494  default:
495   return "unknown";
496  }
497 }
498
499 ///////////////////////////////////////////////////////////////////////////////
500 // search / query functions
501
502 FGPositionedRef
503 FGPositioned::findClosestWithIdent(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
504 {
505   return namedFindClosest(aIdent, aPos, aFilter);
506 }
507
508 FGPositioned::List
509 FGPositioned::findWithinRange(const SGGeod& aPos, double aRangeNm, Filter* aFilter)
510 {
511   List result;
512   spatialFind(aPos, aRangeNm, aFilter, result);
513   filterListByRange(aPos, aRangeNm, result);
514   return result;
515 }
516
517 FGPositioned::List
518 FGPositioned::findAllWithIdentSortedByRange(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
519 {
520   List result;
521   NamedIndexRange range = global_namedIndex.equal_range(aIdent);
522   for (; range.first != range.second; ++range.first) {
523     if (aFilter && !aFilter->pass(range.first->second)) {
524       continue;
525     }
526     
527     result.push_back(range.first->second);
528   }
529   
530   sortByDistance(aPos, result);
531   return result;
532 }
533
534 FGPositionedRef
535 FGPositioned::findClosest(const SGGeod& aPos, double aCutoffNm, Filter* aFilter)
536 {
537    FGPositioned::List l(spatialGetClosest(aPos, 1, aCutoffNm, aFilter));
538    if (l.empty()) {
539       return NULL;
540    }
541    
542    assert(l.size() == 1);
543    return l.front();
544 }
545
546 FGPositioned::List
547 FGPositioned::findClosestN(const SGGeod& aPos, unsigned int aN, double aCutoffNm, Filter* aFilter)
548 {
549   return spatialGetClosest(aPos, aN, aCutoffNm, aFilter);
550 }
551
552 /*
553 FGPositionedRef
554 FGPositioned::findNextWithPartialId(FGPositionedRef aCur, const std::string& aId, Filter* aFilter)
555 {
556   NamedIndexRange range = global_namedIndex.equal_range(aId);
557   for (; range.first != range.second; ++range.first) {
558     FGPositionedRef candidate = range.first->second;
559     if (aCur == candidate) {
560       aCur = NULL; // found our start point, next match will pass
561       continue;
562     }
563     
564     if (aFilter) {
565       if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
566         continue;
567       }
568
569       if(!aFilter->pass(candidate)) {
570         continue;
571       }
572     }
573   
574     if (!aCur) {
575       return candidate;
576     }
577   }
578   
579   return NULL; // fell out, no match in range
580 }*/
581
582 FGPositionedRef
583 FGPositioned::findNextWithPartialId(FGPositionedRef aCur, const std::string& aId, Filter* aFilter)
584 {
585   // It is essential to bound our search, to avoid iterating all the way to the end of the database.
586   // Do this by generating a second ID with the final character incremented by 1.
587   // e.g., if the partial ID is "KI", we wish to search "KIxxx" but not "KJ".
588   std::string upperBoundId = aId;
589   upperBoundId[upperBoundId.size()-1]++;
590   NamedPositionedIndex::const_iterator upperBound = global_namedIndex.lower_bound(upperBoundId);
591
592   NamedIndexRange range = global_namedIndex.equal_range(aId);
593   while (range.first != upperBound) {
594     for (; range.first != range.second; ++range.first) {
595       FGPositionedRef candidate = range.first->second;
596       if (aCur == candidate) {
597         aCur = NULL; // found our start point, next match will pass
598         continue;
599       }
600
601       if (aFilter) {
602         if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
603           continue;
604         }
605
606         if (!aFilter->pass(candidate)) {
607           continue;
608         }
609       }
610
611       if (!aCur) {
612         return candidate;
613       }
614     }
615
616     // Unable to match the filter with this range - try the next range.
617     range = global_namedIndex.equal_range(range.second->first);
618   }
619
620   return NULL; // Reached the end of the valid sequence with no match.  
621 }
622   
623