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 <boost/algorithm/string/case_conv.hpp>
34 #include <simgear/math/sg_geodesy.hxx>
35 #include <simgear/timing/timestamp.hxx>
36 #include <simgear/debug/logstream.hxx>
38 #include "positioned.hxx"
40 typedef std::multimap<std::string, FGPositioned*> NamedPositionedIndex;
41 typedef std::pair<NamedPositionedIndex::const_iterator, NamedPositionedIndex::const_iterator> NamedIndexRange;
43 using std::lower_bound;
44 using std::upper_bound;
47 * Order positioned elements by type, then pointer address. This allows us to
48 * use range searches (lower_ and upper_bound) to grab items of a particular
49 * type out of bucket efficently.
54 bool operator()(const FGPositioned* a, const FGPositioned* b) const
56 if (a->type() == b->type()) return a < b;
57 return a->type() < b->type();
61 class LowerLimitOfType
64 bool operator()(const FGPositioned* a, const FGPositioned::Type b) const
69 bool operator()(const FGPositioned::Type a, const FGPositioned* b) const
74 // The operator below is required by VS2005 in debug mode
75 bool operator()(const FGPositioned* a, const FGPositioned* b) const
77 return a->type() < b->type();
82 typedef std::set<FGPositioned*, OrderByType> BucketEntry;
83 typedef std::map<long int, BucketEntry> SpatialPositionedIndex;
85 static NamedPositionedIndex global_namedIndex;
86 static SpatialPositionedIndex global_spatialIndex;
88 SpatialPositionedIndex::iterator
89 bucketEntryForPositioned(FGPositioned* aPos)
91 int bucketIndex = aPos->bucket().gen_index();
92 SpatialPositionedIndex::iterator it = global_spatialIndex.find(bucketIndex);
93 if (it != global_spatialIndex.end()) {
97 // create a new BucketEntry
98 return global_spatialIndex.insert(it, std::make_pair(bucketIndex, BucketEntry()));
102 addToIndices(FGPositioned* aPos)
105 if (!aPos->ident().empty()) {
106 global_namedIndex.insert(global_namedIndex.begin(),
107 std::make_pair(aPos->ident(), aPos));
110 SpatialPositionedIndex::iterator it = bucketEntryForPositioned(aPos);
111 it->second.insert(aPos);
115 removeFromIndices(FGPositioned* aPos)
119 if (!aPos->ident().empty()) {
120 NamedPositionedIndex::iterator it = global_namedIndex.find(aPos->ident());
121 while (it != global_namedIndex.end() && (it->first == aPos->ident())) {
122 if (it->second == aPos) {
123 global_namedIndex.erase(it);
128 } // of multimap walk
131 SpatialPositionedIndex::iterator sit = bucketEntryForPositioned(aPos);
132 sit->second.erase(aPos);
136 spatialFilterInBucket(const SGBucket& aBucket, FGPositioned::Filter* aFilter, FGPositioned::List& aResult)
138 SpatialPositionedIndex::const_iterator it;
139 it = global_spatialIndex.find(aBucket.gen_index());
140 if (it == global_spatialIndex.end()) {
144 BucketEntry::const_iterator l = it->second.begin();
145 BucketEntry::const_iterator u = it->second.end();
147 if (!aFilter) { // pass everything
148 aResult.insert(aResult.end(), l, u);
152 if (aFilter->hasTypeRange()) {
153 // avoid many calls to the filter hook
154 l = lower_bound(it->second.begin(), it->second.end(), aFilter->minType(), LowerLimitOfType());
155 u = upper_bound(l, it->second.end(), aFilter->maxType(), LowerLimitOfType());
158 for ( ; l != u; ++l) {
159 if ((*aFilter)(*l)) {
160 aResult.push_back(*l);
166 spatialFind(const SGGeod& aPos, double aRange,
167 FGPositioned::Filter* aFilter, FGPositioned::List& aResult)
170 double lat = aPos.getLatitudeDeg(),
171 lon = aPos.getLongitudeDeg();
173 int bx = (int)( aRange*SG_NM_TO_METER / buck.get_width_m() / 2);
174 int by = (int)( aRange*SG_NM_TO_METER / buck.get_height_m() / 2 );
176 // loop over bucket range
177 for ( int i=-bx; i<=bx; i++) {
178 for ( int j=-by; j<=by; j++) {
179 spatialFilterInBucket(sgBucketOffset(lon, lat, i, j), aFilter, aResult);
186 class RangePredictate
189 RangePredictate(const SGGeod& aOrigin, double aRange) :
190 mOrigin(SGVec3d::fromGeod(aOrigin)),
191 mRangeSqr(aRange * aRange)
194 bool operator()(const FGPositionedRef& aPos)
196 double dSqr = distSqr(aPos->cart(), mOrigin);
197 return (dSqr > mRangeSqr);
206 filterListByRange(const SGGeod& aPos, double aRange, FGPositioned::List& aResult)
208 RangePredictate pred(aPos, aRange * SG_NM_TO_METER);
209 FGPositioned::List::iterator newEnd;
210 newEnd = std::remove_if(aResult.begin(), aResult.end(), pred);
211 aResult.erase(newEnd, aResult.end());
214 class DistanceOrdering
217 DistanceOrdering(const SGGeod& aPos) :
218 mPos(SGVec3d::fromGeod(aPos))
221 bool operator()(const FGPositionedRef& a, const FGPositionedRef& b) const
223 double dA = distSqr(a->cart(), mPos),
224 dB = distSqr(b->cart(), mPos);
233 sortByDistance(const SGGeod& aPos, FGPositioned::List& aResult)
235 std::sort(aResult.begin(), aResult.end(), DistanceOrdering(aPos));
238 static FGPositionedRef
239 namedFindClosest(const std::string& aIdent, const SGGeod& aOrigin, FGPositioned::Filter* aFilter)
241 NamedIndexRange range = global_namedIndex.equal_range(aIdent);
242 if (range.first == range.second) {
246 // common case, only one result. looks a bit ugly because these are
247 // sequential iterators, not random-access ones
248 NamedPositionedIndex::const_iterator check = range.first;
249 if (++check == range.second) {
250 // excellent, only one match in the range
251 FGPositioned* r = range.first->second;
253 if (aFilter->hasTypeRange() && !aFilter->passType(r->type())) {
257 if (!aFilter->pass(r)) {
260 } // of have a filter
263 } // of short-circuit logic for single-element range
265 // multiple matches, we need to actually check the distance to each one
266 double minDist = HUGE_VAL;
267 FGPositionedRef result;
268 NamedPositionedIndex::const_iterator it = range.first;
269 SGVec3d cartOrigin(SGVec3d::fromGeod(aOrigin));
271 for (; it != range.second; ++it) {
272 FGPositioned* r = it->second;
274 if (aFilter->hasTypeRange() && !aFilter->passType(r->type())) {
278 if (!aFilter->pass(r)) {
284 double d2 = distSqr(cartOrigin, r->cart());
294 static FGPositioned::List
295 spatialGetClosest(const SGGeod& aPos, unsigned int aN, double aCutoffNm, FGPositioned::Filter* aFilter)
297 FGPositioned::List result;
298 int radius = 1; // start at 1, radius 0 is handled explicitly
300 double lat = aPos.getLatitudeDeg(),
301 lon = aPos.getLongitudeDeg();
302 // final cutoff is in metres, and scaled to account for testing the corners
303 // of the 'box' instead of the centre of each edge
304 double cutoffM = aCutoffNm * SG_NM_TO_METER * 1.5;
306 // base case, simplifes loop to do it seperately here
307 spatialFilterInBucket(sgBucketOffset(lon, lat, 0, 0), aFilter, result);
309 for (;result.size() < aN; ++radius) {
311 double az1, az2, d1, d2;
312 SGGeodesy::inverse(aPos, sgBucketOffset(lon, lat, -radius, -radius).get_center(), az1, az2, d1);
313 SGGeodesy::inverse(aPos, sgBucketOffset(lon, lat, radius, radius).get_center(), az1, az2, d2);
315 if ((d1 > cutoffM) && (d2 > cutoffM)) {
316 //std::cerr << "spatialGetClosest terminating due to range cutoff" << std::endl;
320 FGPositioned::List hits;
321 for ( int i=-radius; i<=radius; i++) {
322 spatialFilterInBucket(sgBucketOffset(lon, lat, i, -radius), aFilter, hits);
323 spatialFilterInBucket(sgBucketOffset(lon, lat, -radius, i), aFilter, hits);
324 spatialFilterInBucket(sgBucketOffset(lon, lat, i, radius), aFilter, hits);
325 spatialFilterInBucket(sgBucketOffset(lon, lat, radius, i), aFilter, hits);
328 result.insert(result.end(), hits.begin(), hits.end()); // append
331 sortByDistance(aPos, result);
332 if (result.size() > aN) {
333 result.resize(aN); // truncate at requested number of matches
339 //////////////////////////////////////////////////////////////////////////////
344 bool operator()(FGPositioned* a, FGPositioned* b) const
346 return a->name() < b->name();
351 * A special purpose helper (imported by FGAirport::searchNamesAndIdents) to
352 * implement the AirportList dialog. It's unfortunate that it needs to reside
353 * here, but for now it's least ugly solution.
355 char** searchAirportNamesAndIdents(const std::string& aFilter)
357 const std::ctype<char> &ct = std::use_facet<std::ctype<char> >(std::locale());
358 std::string filter(aFilter);
359 bool hasFilter = !filter.empty();
361 ct.toupper((char *)filter.data(), (char *)filter.data() + filter.size());
364 NamedPositionedIndex::const_iterator it = global_namedIndex.begin();
365 NamedPositionedIndex::const_iterator end = global_namedIndex.end();
367 // note this is a vector of raw pointers, not smart pointers, because it
368 // may get very large and smart-pointer-atomicity-locking then becomes a
369 // bottleneck for this case.
370 std::vector<FGPositioned*> matches;
373 for (; it != end; ++it) {
374 FGPositioned::Type ty = it->second->type();
375 if ((ty < FGPositioned::AIRPORT) || (ty > FGPositioned::SEAPORT)) {
379 if (hasFilter && (it->second->ident().find(aFilter) == std::string::npos)) {
380 upper = it->second->name(); // string copy, sadly
381 ct.toupper((char *)upper.data(), (char *)upper.data() + upper.size());
382 if (upper.find(aFilter) == std::string::npos) {
387 matches.push_back(it->second);
390 // sort alphabetically on name
391 std::sort(matches.begin(), matches.end(), OrderByName());
393 // convert results to format comptible with puaList
394 unsigned int numMatches = matches.size();
395 char** result = new char*[numMatches + 1];
396 result[numMatches] = NULL; // end-of-list marker
398 // nasty code to avoid excessive string copying and allocations.
399 // We format results as follows (note whitespace!):
400 // ' name-of-airport-chars (ident)'
401 // so the total length is:
402 // 1 + strlen(name) + 4 + 4 (for the ident) + 1 + 1 (for the null)
403 // which gives a grand total of 11 + the length of the name.
404 // note the ident is sometimes only three letters for non-ICAO small strips
405 for (unsigned int i=0; i<numMatches; ++i) {
406 int nameLength = matches[i]->name().size();
407 int icaoLength = matches[i]->ident().size();
408 char* entry = new char[nameLength + 11];
411 memcpy(dst, matches[i]->name().c_str(), nameLength);
417 memcpy(dst, matches[i]->ident().c_str(), icaoLength);
427 ///////////////////////////////////////////////////////////////////////////////
430 FGPositioned::Filter::hasTypeRange() const
432 assert(minType() <= maxType());
433 return (minType() != INVALID) && (maxType() != INVALID);
437 FGPositioned::Filter::passType(Type aTy) const
439 assert(hasTypeRange());
440 return (minType() <= aTy) && (maxType() >= aTy);
443 ///////////////////////////////////////////////////////////////////////////////
445 FGPositioned::FGPositioned(Type ty, const std::string& aIdent, const SGGeod& aPos, bool aIndexed) :
450 SGReferenced::get(this); // hold an owning ref, for the moment
453 assert(ty != TAXIWAY && ty != PAVEMENT);
458 FGPositioned::~FGPositioned()
460 //std::cout << "destroying:" << mIdent << "/" << nameForType(mType) << std::endl;
461 removeFromIndices(this);
465 FGPositioned::createUserWaypoint(const std::string& aIdent, const SGGeod& aPos)
467 return new FGPositioned(WAYPOINT, aIdent, aPos, true);
471 FGPositioned::bucket() const
473 return SGBucket(mPosition);
477 FGPositioned::cart() const
479 return SGVec3d::fromGeod(mPosition);
482 FGPositioned::Type FGPositioned::typeFromName(const std::string& aName)
484 if (aName.empty() || (aName == "")) {
493 const NameTypeEntry names[] = {
494 {"airport", AIRPORT},
502 {"waypoint", WAYPOINT},
508 std::string lowerName(boost::to_lower_copy(aName));
510 for (const NameTypeEntry* n = names; (n->_name != NULL); ++n) {
511 if (::strcmp(n->_name, lowerName.c_str()) == 0) {
516 SG_LOG(SG_GENERAL, SG_WARN, "FGPositioned::typeFromName: couldn't match:" << aName);
520 const char* FGPositioned::nameForType(Type aTy)
523 case RUNWAY: return "runway";
524 case TAXIWAY: return "taxiway";
525 case PAVEMENT: return "pavement";
526 case PARK_STAND: return "parking stand";
527 case FIX: return "fix";
528 case VOR: return "VOR";
529 case NDB: return "NDB";
530 case ILS: return "ILS";
531 case LOC: return "localiser";
532 case GS: return "glideslope";
533 case OM: return "outer-marker";
534 case MM: return "middle-marker";
535 case IM: return "inner-marker";
536 case AIRPORT: return "airport";
537 case HELIPORT: return "heliport";
538 case SEAPORT: return "seaport";
539 case WAYPOINT: return "waypoint";
540 case DME: return "dme";
541 case TACAN: return "tacan";
547 ///////////////////////////////////////////////////////////////////////////////
548 // search / query functions
551 FGPositioned::findClosestWithIdent(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
553 return namedFindClosest(aIdent, aPos, aFilter);
557 FGPositioned::findWithinRange(const SGGeod& aPos, double aRangeNm, Filter* aFilter)
560 spatialFind(aPos, aRangeNm, aFilter, result);
561 filterListByRange(aPos, aRangeNm, result);
566 FGPositioned::findAllWithIdentSortedByRange(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
569 NamedIndexRange range = global_namedIndex.equal_range(aIdent);
570 for (; range.first != range.second; ++range.first) {
571 if (aFilter && !aFilter->pass(range.first->second)) {
575 result.push_back(range.first->second);
578 sortByDistance(aPos, result);
583 FGPositioned::findClosest(const SGGeod& aPos, double aCutoffNm, Filter* aFilter)
585 FGPositioned::List l(spatialGetClosest(aPos, 1, aCutoffNm, aFilter));
590 assert(l.size() == 1);
595 FGPositioned::findClosestN(const SGGeod& aPos, unsigned int aN, double aCutoffNm, Filter* aFilter)
597 return spatialGetClosest(aPos, aN, aCutoffNm, aFilter);
601 FGPositioned::findNextWithPartialId(FGPositionedRef aCur, const std::string& aId, Filter* aFilter)
603 // It is essential to bound our search, to avoid iterating all the way to the end of the database.
604 // Do this by generating a second ID with the final character incremented by 1.
605 // e.g., if the partial ID is "KI", we wish to search "KIxxx" but not "KJ".
606 std::string upperBoundId = aId;
607 upperBoundId[upperBoundId.size()-1]++;
608 NamedPositionedIndex::const_iterator upperBound = global_namedIndex.lower_bound(upperBoundId);
610 NamedIndexRange range = global_namedIndex.equal_range(aId);
611 while (range.first != upperBound) {
612 for (; range.first != range.second; ++range.first) {
613 FGPositionedRef candidate = range.first->second;
614 if (aCur == candidate) {
615 aCur = NULL; // found our start point, next match will pass
620 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
624 if (!aFilter->pass(candidate)) {
634 // Unable to match the filter with this range - try the next range.
635 range = global_namedIndex.equal_range(range.second->first);
638 return NULL; // Reached the end of the valid sequence with no match.
642 FGPositioned::findWithPartialId(const std::string& aId, Filter* aFilter, int aOffset)
644 // see comment in findNextWithPartialId concerning upperBoundId
645 std::string upperBoundId = aId;
646 upperBoundId[upperBoundId.size()-1]++;
647 NamedPositionedIndex::const_iterator upperBound = global_namedIndex.lower_bound(upperBoundId);
649 NamedIndexRange range = global_namedIndex.equal_range(aId);
651 while (range.first != upperBound) {
652 for (; range.first != range.second; ++range.first) {
653 FGPositionedRef candidate = range.first->second;
655 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
659 if (!aFilter->pass(candidate)) {
667 --aOffset; // seen one more valid result, decrement the count
671 // Unable to match the filter with this range - try the next range.
672 range = global_namedIndex.equal_range(range.second->first);
675 return NULL; // Reached the end of the valid sequence with no match.
679 * Wrapper filter which proxies to an inner filter, but also ensures the
680 * ident starts with supplied partial ident.
682 class PartialIdentFilter : public FGPositioned::Filter
685 PartialIdentFilter(const std::string& ident, FGPositioned::Filter* filter) :
690 virtual bool pass(FGPositioned* aPos) const
692 if (!_inner->pass(aPos)) {
696 return (::strncmp(aPos->ident().c_str(), _ident.c_str(), _ident.size()) == 0);
699 virtual FGPositioned::Type minType() const
700 { return _inner->minType(); }
702 virtual FGPositioned::Type maxType() const
703 { return _inner->maxType(); }
707 FGPositioned::Filter* _inner;
711 FGPositioned::findClosestWithPartialId(const SGGeod& aPos, const std::string& aId, Filter* aFilter, int aOffset)
713 PartialIdentFilter pf(aId, aFilter);
714 List matches = spatialGetClosest(aPos, aOffset + 1, 1000.0, &pf);
716 if ((int) matches.size() <= aOffset) {
717 SG_LOG(SG_GENERAL, SG_INFO, "FGPositioned::findClosestWithPartialId, couldn't match enough with prefix:" << aId);
718 return NULL; // couldn't find a match within the cutoff distance
721 return matches[aOffset];