]> git.mxchange.org Git - flightgear.git/blob - src/Navaids/positioned.cxx
07af55b1cfb5e141f3fd09b28bb74311c9cc306f
[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>
28
29 #include <simgear/math/sg_geodesy.hxx>
30
31 #include "positioned.hxx"
32
33 typedef std::multimap<std::string, FGPositioned*> NamedPositionedIndex;
34 typedef std::pair<NamedPositionedIndex::const_iterator, NamedPositionedIndex::const_iterator> NamedIndexRange;
35
36 /**
37  * Order positioned elements by type, then pointer address. This allows us to
38  * use range searches (lower_ and upper_bound) to grab items of a particular
39  * type out of bucket efficently.
40  */
41 class OrderByType
42 {
43 public:
44   bool operator()(const FGPositioned* a, const FGPositioned* b) const
45   {
46     if (a->type() == b->type()) return a < b;
47     return a->type() < b->type();
48   }
49 };
50
51 typedef std::set<FGPositioned*, OrderByType> BucketEntry;
52 typedef std::map<long int, BucketEntry> SpatialPositionedIndex;
53
54 static NamedPositionedIndex global_namedIndex;
55 static SpatialPositionedIndex global_spatialIndex;
56
57 SpatialPositionedIndex::iterator
58 bucketEntryForPositioned(FGPositioned* aPos)
59 {
60   int bucketIndex = aPos->bucket().gen_index();
61   SpatialPositionedIndex::iterator it = global_spatialIndex.find(bucketIndex);
62   if (it != global_spatialIndex.end()) {
63     return it;
64   }
65   
66   // create a new BucketEntry
67   return global_spatialIndex.insert(it, std::make_pair(bucketIndex, BucketEntry()));
68 }
69
70 static void
71 addToIndices(FGPositioned* aPos)
72 {
73   assert(aPos);
74   global_namedIndex.insert(global_namedIndex.begin(), 
75     std::make_pair(aPos->ident(), aPos));
76     
77   SpatialPositionedIndex::iterator it = bucketEntryForPositioned(aPos);
78   it->second.insert(aPos);
79 }
80
81 static void
82 removeFromIndices(FGPositioned* aPos)
83 {
84   assert(aPos);
85   
86   NamedPositionedIndex::iterator it = global_namedIndex.find(aPos->ident());
87   while (it != global_namedIndex.end() && (it->first == aPos->ident())) {
88     if (it->second == aPos) {
89       global_namedIndex.erase(it);
90       break;
91     }
92     
93     ++it;
94   }
95   
96   SpatialPositionedIndex::iterator sit = bucketEntryForPositioned(aPos);
97   sit->second.erase(aPos);
98 }
99
100 static void
101 spatialFilterInBucket(const SGBucket& aBucket, FGPositioned::Filter* aFilter, FGPositioned::List& aResult)
102 {
103   SpatialPositionedIndex::const_iterator it;
104   it = global_spatialIndex.find(aBucket.gen_index());
105   if (it == global_spatialIndex.end()) {
106     return;
107   }
108   
109   BucketEntry::const_iterator l = it->second.begin();
110   BucketEntry::const_iterator u = it->second.end();
111
112   if (!aFilter) { // pass everything
113     aResult.insert(aResult.end(), l, u);
114     return;
115   }
116
117   for ( ; l != u; ++l) {
118     if ((*aFilter)(*l)) {
119       aResult.push_back(*l);
120     }
121   }
122 }
123
124 static void
125 spatialFind(const SGGeod& aPos, double aRange, 
126   FGPositioned::Filter* aFilter, FGPositioned::List& aResult)
127 {
128   SGBucket buck(aPos);
129   double lat = aPos.getLatitudeDeg(),
130     lon = aPos.getLongitudeDeg();
131   
132   int bx = (int)( aRange*SG_NM_TO_METER / buck.get_width_m() / 2);
133   int by = (int)( aRange*SG_NM_TO_METER / buck.get_height_m() / 2 );
134     
135   // loop over bucket range 
136   for ( int i=-bx; i<=bx; i++) {
137     for ( int j=-by; j<=by; j++) {
138       spatialFilterInBucket(sgBucketOffset(lon, lat, i, j), aFilter, aResult);
139     } // of j-iteration
140   } // of i-iteration  
141 }
142
143 /*
144 class LowerLimitOfType
145 {
146 public:
147   bool operator()(const FGPositioned* a, const FGPositioned::Type b) const
148   {
149     return a->type() < b;
150   }
151   
152   bool operator()(const FGPositioned::Type a, const FGPositioned* b) const
153   {
154     return a < b->type();
155   }
156 };
157
158
159 static void
160 spatialFindTyped(const SGGeod& aPos, double aRange, FGPositioned::Type aLower, FGPositioned::Type aUpper, FGPositioned::List& aResult)
161 {
162   SGBucket buck(aPos);
163   double lat = aPos.getLatitudeDeg(),
164     lon = aPos.getLongitudeDeg();
165   
166   int bx = (int)( aRange*SG_NM_TO_METER / buck.get_width_m() / 2);
167   int by = (int)( aRange*SG_NM_TO_METER / buck.get_height_m() / 2 );
168     
169   // loop over bucket range 
170   for ( int i=-bx; i<=bx; i++) {
171     for ( int j=-by; j<=by; j++) {
172       buck = sgBucketOffset(lon, lat, i, j);
173       
174       SpatialPositionedIndex::const_iterator it;
175       it = global_spatialIndex.find(buck.gen_index());
176       if (it == global_spatialIndex.end()) {
177         continue;
178       }
179       
180       BucketEntry::const_iterator l = std::lower_bound(it->second.begin(), it->second.end(), aLower, LowerLimitOfType());
181       BucketEntry::const_iterator u = std::upper_bound(l, it->second.end(), aUpper, LowerLimitOfType());
182       
183       for ( ; l != u; ++l) {
184         aResult.push_back(*l);
185       }
186       
187     } // of j-iteration
188   } // of i-iteration  
189 }
190 */
191
192 /**
193  */
194 class RangePredictate
195 {
196 public:
197   RangePredictate(const SGGeod& aOrigin, double aRange) :
198     mOrigin(aOrigin),
199     mRange(aRange)
200   { ; }
201   
202   bool operator()(const FGPositionedRef& aPos)
203   {
204     double d, az1, az2;
205     SGGeodesy::inverse(aPos->geod(), mOrigin, az1, az2, d);
206     return (d > mRange);
207   }
208   
209 private:
210   SGGeod mOrigin;
211   double mRange;
212 };
213
214 static void
215 filterListByRange(const SGGeod& aPos, double aRange, FGPositioned::List& aResult)
216 {
217   RangePredictate pred(aPos, aRange * SG_NM_TO_METER);
218   FGPositioned::List::iterator newEnd; 
219   newEnd = std::remove_if(aResult.begin(), aResult.end(), pred);
220   aResult.erase(newEnd, aResult.end());
221 }
222
223 class DistanceOrdering
224 {
225 public:
226   DistanceOrdering(const SGGeod& aPos) :
227     mPos(aPos)
228   { }
229   
230   bool operator()(const FGPositionedRef& a, const FGPositionedRef& b) const
231   {
232     double dA, dB, az1, az2;
233     SGGeodesy::inverse(mPos, a->geod(), az1, az2, dA);
234     SGGeodesy::inverse(mPos, b->geod(), az1, az2, dB);
235     return dA < dB;
236   }
237
238 private:
239   SGGeod mPos;
240 };
241
242 static void
243 sortByDistance(const SGGeod& aPos, FGPositioned::List& aResult)
244 {
245   std::sort(aResult.begin(), aResult.end(), DistanceOrdering(aPos));
246 }
247
248 static FGPositionedRef
249 namedFindClosest(const std::string& aIdent, const SGGeod& aOrigin, FGPositioned::Filter* aFilter)
250 {
251   NamedIndexRange range = global_namedIndex.equal_range(aIdent);
252   if (range.first == range.second) {
253     return NULL;
254   }
255   
256 // common case, only one result. looks a bit ugly because these are
257 // sequential iterators, not random-access ones
258   NamedPositionedIndex::const_iterator check = range.first;
259   if (++check == range.second) {
260     // excellent, only one match in the range - all we care about is the type
261     if (aFilter && !aFilter->pass(range.first->second)) {
262       return NULL; // type check failed
263     }
264     
265     return range.first->second;
266   } // of short-circuit logic for single-element range
267   
268 // multiple matches, we need to actually check the distance to each one
269   double minDist = HUGE_VAL;
270   FGPositionedRef result;
271   NamedPositionedIndex::const_iterator it = range.first;
272     
273   for (; it != range.second; ++it) {
274   // filter by type
275     FGPositioned::Type ty = it->second->type();
276     if (aFilter && !aFilter->pass(range.first->second)) {
277       continue;
278     }
279     
280   // find distance
281     double d, az1, az2;
282     SGGeodesy::inverse(aOrigin, it->second->geod(), az2, az2, d);
283     if (d < minDist) {
284       minDist = d;
285       result = it->second;
286     }
287   }
288   
289   return result;
290 }
291
292 static FGPositioned::List
293 spatialGetClosest(const SGGeod& aPos, unsigned int aN, double aCutoffNm, FGPositioned::Filter* aFilter)
294 {
295   FGPositioned::List result;
296   int radius = 1; // start at 1, radius 0 is handled explicitly
297   SGBucket buck;
298   double lat = aPos.getLatitudeDeg(),
299     lon = aPos.getLongitudeDeg();
300   // final cutoff is in metres, and scaled to account for testing the corners
301   // of the 'box' instead of the centre of each edge
302   double cutoffM = aCutoffNm * SG_NM_TO_METER * 1.5;
303   
304   // base case, simplifes loop to do it seperately here
305   spatialFilterInBucket(sgBucketOffset(lon, lat, 0, 0), aFilter, result);
306
307   for (;result.size() < aN; ++radius) {
308     // cutoff check
309     double az1, az2, d1, d2;
310     SGGeodesy::inverse(aPos, sgBucketOffset(lon, lat, -radius, -radius).get_center(), az1, az2, d1);
311     SGGeodesy::inverse(aPos, sgBucketOffset(lon, lat, radius, radius).get_center(), az1, az2, d2);  
312       
313     if ((d1 > cutoffM) && (d2 > cutoffM)) {
314       //std::cerr << "spatialGetClosest terminating due to range cutoff" << std::endl;
315       break;
316     }
317     
318     FGPositioned::List hits;
319     for ( int i=-radius; i<=radius; i++) {
320       spatialFilterInBucket(sgBucketOffset(lon, lat, i, -radius), aFilter, hits);
321       spatialFilterInBucket(sgBucketOffset(lon, lat, -radius, i), aFilter, hits);
322       spatialFilterInBucket(sgBucketOffset(lon, lat, i, radius), aFilter, hits);
323       spatialFilterInBucket(sgBucketOffset(lon, lat, radius, i), aFilter, hits);
324     }
325
326     result.insert(result.end(), hits.begin(), hits.end()); // append
327   } // of outer loop
328   
329   if (result.size() > aN) {
330     result.resize(aN); // truncate at requested number of matches
331   }
332   
333   sortByDistance(aPos, result);
334   return result;
335 }
336
337 ///////////////////////////////////////////////////////////////////////////////
338
339 FGPositioned::FGPositioned(Type ty, const std::string& aIdent, double aLat, double aLon, double aElev) :
340   mType(ty),
341   mPosition(SGGeod::fromDegFt(aLon, aLat, aElev)),
342   mIdent(aIdent)
343 {
344   addToIndices(this);
345   SGReferenced::get(this); // hold an owning ref, for the moment
346 }
347
348 FGPositioned::FGPositioned(Type ty, const std::string& aIdent, const SGGeod& aPos) :
349   mType(ty),
350   mPosition(aPos),
351   mIdent(aIdent)
352 {
353   addToIndices(this);
354   SGReferenced::get(this); // hold an owning ref, for the moment
355 }
356
357 FGPositioned::~FGPositioned()
358 {
359   removeFromIndices(this);
360 }
361
362 SGBucket
363 FGPositioned::bucket() const
364 {
365   return SGBucket(mPosition);
366 }
367
368 const char* FGPositioned::nameForType(Type aTy)
369 {
370  switch (aTy) {
371  case FIX: return "fix";
372  case VOR: return "VOR";
373  case NDB: return "NDB";
374  case OM: return "outer-marker";
375  case MM: return "middle-marker";
376  case IM: return "inner-marker";
377  case AIRPORT: return "airport";
378  case HELIPORT: return "heliport";
379  case SEAPORT: return "seaport";
380  case WAYPOINT: return "waypoint";
381  default:
382   return "unknown";
383  }
384 }
385
386 ///////////////////////////////////////////////////////////////////////////////
387 // search / query functions
388
389 FGPositionedRef
390 FGPositioned::findClosestWithIdent(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
391 {
392   return namedFindClosest(aIdent, aPos, aFilter);
393 }
394
395 FGPositioned::List
396 FGPositioned::findWithinRange(const SGGeod& aPos, double aRangeNm, Filter* aFilter)
397 {
398   List result;
399   spatialFind(aPos, aRangeNm, aFilter, result);
400   filterListByRange(aPos, aRangeNm, result);
401   return result;
402 }
403
404 FGPositioned::List
405 FGPositioned::findAllWithIdentSortedByRange(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
406 {
407   List result;
408   NamedIndexRange range = global_namedIndex.equal_range(aIdent);
409   for (; range.first != range.second; ++range.first) {
410     if (aFilter && !aFilter->pass(range.first->second)) {
411       continue;
412     }
413     
414     result.push_back(range.first->second);
415   }
416   
417   sortByDistance(aPos, result);
418   return result;
419 }
420
421 FGPositionedRef
422 FGPositioned::findClosest(const SGGeod& aPos, double aCutoffNm, Filter* aFilter)
423 {
424    FGPositioned::List l(spatialGetClosest(aPos, 1, aCutoffNm, aFilter));
425    if (l.empty()) {
426       return NULL;
427    }
428    
429    assert(l.size() == 1);
430    return l.front();
431 }
432
433 FGPositioned::List
434 FGPositioned::findClosestN(const SGGeod& aPos, unsigned int aN, double aCutoffNm, Filter* aFilter)
435 {
436   return spatialGetClosest(aPos, aN, aCutoffNm, aFilter);
437 }
438
439 FGPositionedRef
440 FGPositioned::findNextWithPartialId(FGPositionedRef aCur, const std::string& aId, Filter* aFilter)
441 {
442   NamedIndexRange range = global_namedIndex.equal_range(aId);
443   for (; range.first != range.second; ++range.first) {
444     FGPositionedRef candidate = range.first->second;
445     if (aCur == candidate) {
446       aCur = NULL; // found our start point, next match will pass
447       continue;
448     }
449     
450     if (aFilter && !aFilter->pass(candidate)) {
451       continue;
452     }
453   
454     if (!aCur) {
455       return candidate;
456     }
457   }
458   
459   return NULL; // fell out, no match in range
460 }
461