1 // positioned.cxx - base class for objects which are positioned
3 // Copyright (C) 2008 James Turner
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.
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.
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.
27 #include <algorithm> // for sort
28 #include <locale> // for char-traits toupper
32 #include <simgear/math/sg_geodesy.hxx>
33 #include <simgear/timing/timestamp.hxx>
35 #include "positioned.hxx"
37 typedef std::multimap<std::string, FGPositioned*> NamedPositionedIndex;
38 typedef std::pair<NamedPositionedIndex::const_iterator, NamedPositionedIndex::const_iterator> NamedIndexRange;
40 using std::lower_bound;
41 using std::upper_bound;
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.
51 bool operator()(const FGPositioned* a, const FGPositioned* b) const
53 if (a->type() == b->type()) return a < b;
54 return a->type() < b->type();
58 class LowerLimitOfType
61 bool operator()(const FGPositioned* a, const FGPositioned::Type b) const
66 bool operator()(const FGPositioned::Type a, const FGPositioned* b) const
71 // The operator below is required by VS2005 in debug mode
72 bool operator()(const FGPositioned* a, const FGPositioned* b) const
74 return a->type() < b->type();
79 typedef std::set<FGPositioned*, OrderByType> BucketEntry;
80 typedef std::map<long int, BucketEntry> SpatialPositionedIndex;
82 static NamedPositionedIndex global_namedIndex;
83 static SpatialPositionedIndex global_spatialIndex;
85 SpatialPositionedIndex::iterator
86 bucketEntryForPositioned(FGPositioned* aPos)
88 int bucketIndex = aPos->bucket().gen_index();
89 SpatialPositionedIndex::iterator it = global_spatialIndex.find(bucketIndex);
90 if (it != global_spatialIndex.end()) {
94 // create a new BucketEntry
95 return global_spatialIndex.insert(it, std::make_pair(bucketIndex, BucketEntry()));
99 addToIndices(FGPositioned* aPos)
102 if (!aPos->ident().empty()) {
103 global_namedIndex.insert(global_namedIndex.begin(),
104 std::make_pair(aPos->ident(), aPos));
107 SpatialPositionedIndex::iterator it = bucketEntryForPositioned(aPos);
108 it->second.insert(aPos);
112 removeFromIndices(FGPositioned* aPos)
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);
125 } // of multimap walk
128 SpatialPositionedIndex::iterator sit = bucketEntryForPositioned(aPos);
129 sit->second.erase(aPos);
133 spatialFilterInBucket(const SGBucket& aBucket, FGPositioned::Filter* aFilter, FGPositioned::List& aResult)
135 SpatialPositionedIndex::const_iterator it;
136 it = global_spatialIndex.find(aBucket.gen_index());
137 if (it == global_spatialIndex.end()) {
141 BucketEntry::const_iterator l = it->second.begin();
142 BucketEntry::const_iterator u = it->second.end();
144 if (!aFilter) { // pass everything
145 aResult.insert(aResult.end(), l, u);
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());
155 for ( ; l != u; ++l) {
156 if ((*aFilter)(*l)) {
157 aResult.push_back(*l);
163 spatialFind(const SGGeod& aPos, double aRange,
164 FGPositioned::Filter* aFilter, FGPositioned::List& aResult)
167 double lat = aPos.getLatitudeDeg(),
168 lon = aPos.getLongitudeDeg();
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 );
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);
183 class RangePredictate
186 RangePredictate(const SGGeod& aOrigin, double aRange) :
187 mOrigin(SGVec3d::fromGeod(aOrigin)),
188 mRangeSqr(aRange * aRange)
191 bool operator()(const FGPositionedRef& aPos)
193 double dSqr = distSqr(aPos->cart(), mOrigin);
194 return (dSqr > mRangeSqr);
203 filterListByRange(const SGGeod& aPos, double aRange, FGPositioned::List& aResult)
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());
211 class DistanceOrdering
214 DistanceOrdering(const SGGeod& aPos) :
215 mPos(SGVec3d::fromGeod(aPos))
218 bool operator()(const FGPositionedRef& a, const FGPositionedRef& b) const
220 double dA = distSqr(a->cart(), mPos),
221 dB = distSqr(b->cart(), mPos);
230 sortByDistance(const SGGeod& aPos, FGPositioned::List& aResult)
232 std::sort(aResult.begin(), aResult.end(), DistanceOrdering(aPos));
235 static FGPositionedRef
236 namedFindClosest(const std::string& aIdent, const SGGeod& aOrigin, FGPositioned::Filter* aFilter)
238 NamedIndexRange range = global_namedIndex.equal_range(aIdent);
239 if (range.first == range.second) {
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;
250 if (aFilter->hasTypeRange() && !aFilter->passType(r->type())) {
254 if (!aFilter->pass(r)) {
257 } // of have a filter
260 } // of short-circuit logic for single-element range
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));
268 for (; it != range.second; ++it) {
269 FGPositioned* r = it->second;
271 if (aFilter->hasTypeRange() && !aFilter->passType(r->type())) {
275 if (!aFilter->pass(r)) {
281 double d2 = distSqr(cartOrigin, r->cart());
291 static FGPositioned::List
292 spatialGetClosest(const SGGeod& aPos, unsigned int aN, double aCutoffNm, FGPositioned::Filter* aFilter)
294 FGPositioned::List result;
295 int radius = 1; // start at 1, radius 0 is handled explicitly
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;
303 // base case, simplifes loop to do it seperately here
304 spatialFilterInBucket(sgBucketOffset(lon, lat, 0, 0), aFilter, result);
306 for (;result.size() < aN; ++radius) {
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);
312 if ((d1 > cutoffM) && (d2 > cutoffM)) {
313 //std::cerr << "spatialGetClosest terminating due to range cutoff" << std::endl;
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);
325 result.insert(result.end(), hits.begin(), hits.end()); // append
328 sortByDistance(aPos, result);
329 if (result.size() > aN) {
330 result.resize(aN); // truncate at requested number of matches
336 //////////////////////////////////////////////////////////////////////////////
341 bool operator()(FGPositioned* a, FGPositioned* b) const
343 return a->name() < b->name();
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.
352 char** searchAirportNamesAndIdents(const std::string& aFilter)
354 const std::ctype<char> &ct = std::use_facet<std::ctype<char> >(std::locale());
355 std::string filter(aFilter);
356 bool hasFilter = !filter.empty();
358 ct.toupper((char *)filter.data(), (char *)filter.data() + filter.size());
361 NamedPositionedIndex::const_iterator it = global_namedIndex.begin();
362 NamedPositionedIndex::const_iterator end = global_namedIndex.end();
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;
370 for (; it != end; ++it) {
371 FGPositioned::Type ty = it->second->type();
372 if ((ty < FGPositioned::AIRPORT) || (ty > FGPositioned::SEAPORT)) {
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) {
384 matches.push_back(it->second);
387 // sort alphabetically on name
388 std::sort(matches.begin(), matches.end(), OrderByName());
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
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];
408 memcpy(dst, matches[i]->name().c_str(), nameLength);
414 memcpy(dst, matches[i]->ident().c_str(), icaoLength);
424 ///////////////////////////////////////////////////////////////////////////////
427 FGPositioned::Filter::hasTypeRange() const
429 assert(minType() <= maxType());
430 return (minType() != INVALID) && (maxType() != INVALID);
434 FGPositioned::Filter::passType(Type aTy) const
436 assert(hasTypeRange());
437 return (minType() <= aTy) && (maxType() >= aTy);
440 ///////////////////////////////////////////////////////////////////////////////
442 FGPositioned::FGPositioned(Type ty, const std::string& aIdent, const SGGeod& aPos, bool aIndexed) :
447 SGReferenced::get(this); // hold an owning ref, for the moment
450 assert(ty != TAXIWAY && ty != PAVEMENT);
455 FGPositioned::~FGPositioned()
457 //std::cout << "destroying:" << mIdent << "/" << nameForType(mType) << std::endl;
458 removeFromIndices(this);
462 FGPositioned::bucket() const
464 return SGBucket(mPosition);
468 FGPositioned::cart() const
470 return SGVec3d::fromGeod(mPosition);
473 const char* FGPositioned::nameForType(Type aTy)
476 case RUNWAY: return "runway";
477 case TAXIWAY: return "taxiway";
478 case PAVEMENT: return "pavement";
479 case PARK_STAND: return "parking stand";
480 case FIX: return "fix";
481 case VOR: return "VOR";
482 case NDB: return "NDB";
483 case ILS: return "ILS";
484 case LOC: return "localiser";
485 case GS: return "glideslope";
486 case OM: return "outer-marker";
487 case MM: return "middle-marker";
488 case IM: return "inner-marker";
489 case AIRPORT: return "airport";
490 case HELIPORT: return "heliport";
491 case SEAPORT: return "seaport";
492 case WAYPOINT: return "waypoint";
493 case DME: return "dme";
494 case TACAN: return "tacan";
500 ///////////////////////////////////////////////////////////////////////////////
501 // search / query functions
504 FGPositioned::findClosestWithIdent(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
506 return namedFindClosest(aIdent, aPos, aFilter);
510 FGPositioned::findWithinRange(const SGGeod& aPos, double aRangeNm, Filter* aFilter)
513 spatialFind(aPos, aRangeNm, aFilter, result);
514 filterListByRange(aPos, aRangeNm, result);
519 FGPositioned::findAllWithIdentSortedByRange(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
522 NamedIndexRange range = global_namedIndex.equal_range(aIdent);
523 for (; range.first != range.second; ++range.first) {
524 if (aFilter && !aFilter->pass(range.first->second)) {
528 result.push_back(range.first->second);
531 sortByDistance(aPos, result);
536 FGPositioned::findClosest(const SGGeod& aPos, double aCutoffNm, Filter* aFilter)
538 FGPositioned::List l(spatialGetClosest(aPos, 1, aCutoffNm, aFilter));
543 assert(l.size() == 1);
548 FGPositioned::findClosestN(const SGGeod& aPos, unsigned int aN, double aCutoffNm, Filter* aFilter)
550 return spatialGetClosest(aPos, aN, aCutoffNm, aFilter);
555 FGPositioned::findNextWithPartialId(FGPositionedRef aCur, const std::string& aId, Filter* aFilter)
557 NamedIndexRange range = global_namedIndex.equal_range(aId);
558 for (; range.first != range.second; ++range.first) {
559 FGPositionedRef candidate = range.first->second;
560 if (aCur == candidate) {
561 aCur = NULL; // found our start point, next match will pass
566 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
570 if(!aFilter->pass(candidate)) {
580 return NULL; // fell out, no match in range
584 FGPositioned::findNextWithPartialId(FGPositionedRef aCur, const std::string& aId, Filter* aFilter)
586 // It is essential to bound our search, to avoid iterating all the way to the end of the database.
587 // Do this by generating a second ID with the final character incremented by 1.
588 // e.g., if the partial ID is "KI", we wish to search "KIxxx" but not "KJ".
589 std::string upperBoundId = aId;
590 upperBoundId[upperBoundId.size()-1]++;
591 NamedPositionedIndex::const_iterator upperBound = global_namedIndex.lower_bound(upperBoundId);
593 NamedIndexRange range = global_namedIndex.equal_range(aId);
594 while (range.first != upperBound) {
595 for (; range.first != range.second; ++range.first) {
596 FGPositionedRef candidate = range.first->second;
597 if (aCur == candidate) {
598 aCur = NULL; // found our start point, next match will pass
603 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
607 if (!aFilter->pass(candidate)) {
617 // Unable to match the filter with this range - try the next range.
618 range = global_namedIndex.equal_range(range.second->first);
621 return NULL; // Reached the end of the valid sequence with no match.