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