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>
33 #include <boost/algorithm/string/predicate.hpp>
35 #include <simgear/math/sg_geodesy.hxx>
36 #include <simgear/timing/timestamp.hxx>
37 #include <simgear/debug/logstream.hxx>
38 #include <simgear/structure/exception.hxx>
40 #include "positioned.hxx"
42 typedef std::multimap<std::string, FGPositioned*> NamedPositionedIndex;
43 typedef std::pair<NamedPositionedIndex::const_iterator, NamedPositionedIndex::const_iterator> NamedIndexRange;
45 using std::lower_bound;
46 using std::upper_bound;
49 * Order positioned elements by type, then pointer address. This allows us to
50 * use range searches (lower_ and upper_bound) to grab items of a particular
51 * type out of bucket efficently.
56 bool operator()(const FGPositioned* a, const FGPositioned* b) const
58 if (a->type() == b->type()) return a < b;
59 return a->type() < b->type();
63 class LowerLimitOfType
66 bool operator()(const FGPositioned* a, const FGPositioned::Type b) const
71 bool operator()(const FGPositioned::Type a, const FGPositioned* b) const
76 // The operator below is required by VS2005 in debug mode
77 bool operator()(const FGPositioned* a, const FGPositioned* b) const
79 return a->type() < b->type();
84 typedef std::set<FGPositioned*, OrderByType> BucketEntry;
85 typedef std::map<long int, BucketEntry> SpatialPositionedIndex;
87 static NamedPositionedIndex global_identIndex;
88 static NamedPositionedIndex global_nameIndex;
89 static SpatialPositionedIndex global_spatialIndex;
91 SpatialPositionedIndex::iterator
92 bucketEntryForPositioned(FGPositioned* aPos)
94 int bucketIndex = aPos->bucket().gen_index();
95 SpatialPositionedIndex::iterator it = global_spatialIndex.find(bucketIndex);
96 if (it != global_spatialIndex.end()) {
100 // create a new BucketEntry
101 return global_spatialIndex.insert(it, std::make_pair(bucketIndex, BucketEntry()));
105 addToIndices(FGPositioned* aPos)
108 if (!aPos->ident().empty()) {
109 global_identIndex.insert(global_identIndex.begin(),
110 std::make_pair(aPos->ident(), aPos));
113 if (!aPos->name().empty()) {
114 global_nameIndex.insert(global_nameIndex.begin(),
115 std::make_pair(aPos->name(), aPos));
119 SpatialPositionedIndex::iterator it = bucketEntryForPositioned(aPos);
120 it->second.insert(aPos);
124 removeFromIndices(FGPositioned* aPos)
128 if (!aPos->ident().empty()) {
129 NamedPositionedIndex::iterator it = global_identIndex.find(aPos->ident());
130 while (it != global_identIndex.end() && (it->first == aPos->ident())) {
131 if (it->second == aPos) {
132 global_identIndex.erase(it);
137 } // of multimap walk
140 if (!aPos->name().empty()) {
141 NamedPositionedIndex::iterator it = global_nameIndex.find(aPos->name());
142 while (it != global_nameIndex.end() && (it->first == aPos->name())) {
143 if (it->second == aPos) {
144 global_nameIndex.erase(it);
149 } // of multimap walk
152 SpatialPositionedIndex::iterator sit = bucketEntryForPositioned(aPos);
153 sit->second.erase(aPos);
157 spatialFilterInBucket(const SGBucket& aBucket, FGPositioned::Filter* aFilter, FGPositioned::List& aResult)
159 SpatialPositionedIndex::const_iterator it;
160 it = global_spatialIndex.find(aBucket.gen_index());
161 if (it == global_spatialIndex.end()) {
165 BucketEntry::const_iterator l = it->second.begin();
166 BucketEntry::const_iterator u = it->second.end();
168 if (!aFilter) { // pass everything
169 aResult.insert(aResult.end(), l, u);
173 if (aFilter->hasTypeRange()) {
174 // avoid many calls to the filter hook
175 l = lower_bound(it->second.begin(), it->second.end(), aFilter->minType(), LowerLimitOfType());
176 u = upper_bound(l, it->second.end(), aFilter->maxType(), LowerLimitOfType());
179 for ( ; l != u; ++l) {
180 if ((*aFilter)(*l)) {
181 aResult.push_back(*l);
187 spatialFind(const SGGeod& aPos, double aRange,
188 FGPositioned::Filter* aFilter, FGPositioned::List& aResult)
191 double lat = aPos.getLatitudeDeg(),
192 lon = aPos.getLongitudeDeg();
194 int bx = (int)( aRange*SG_NM_TO_METER / buck.get_width_m() / 2);
195 int by = (int)( aRange*SG_NM_TO_METER / buck.get_height_m() / 2 );
197 // loop over bucket range
198 for ( int i=-bx; i<=bx; i++) {
199 for ( int j=-by; j<=by; j++) {
200 spatialFilterInBucket(sgBucketOffset(lon, lat, i, j), aFilter, aResult);
207 class RangePredictate
210 RangePredictate(const SGGeod& aOrigin, double aRange) :
211 mOrigin(SGVec3d::fromGeod(aOrigin)),
212 mRangeSqr(aRange * aRange)
215 bool operator()(const FGPositionedRef& aPos)
217 double dSqr = distSqr(aPos->cart(), mOrigin);
218 return (dSqr > mRangeSqr);
227 filterListByRange(const SGGeod& aPos, double aRange, FGPositioned::List& aResult)
229 RangePredictate pred(aPos, aRange * SG_NM_TO_METER);
230 FGPositioned::List::iterator newEnd;
231 newEnd = std::remove_if(aResult.begin(), aResult.end(), pred);
232 aResult.erase(newEnd, aResult.end());
235 class DistanceOrdering
238 DistanceOrdering(const SGGeod& aPos) :
239 mPos(SGVec3d::fromGeod(aPos))
242 bool operator()(const FGPositionedRef& a, const FGPositionedRef& b) const
245 throw sg_exception("empty reference passed to DistanceOrdering");
248 double dA = distSqr(a->cart(), mPos),
249 dB = distSqr(b->cart(), mPos);
258 sortByDistance(const SGGeod& aPos, FGPositioned::List& aResult)
260 std::sort(aResult.begin(), aResult.end(), DistanceOrdering(aPos));
263 static FGPositionedRef
264 namedFindClosest(const NamedPositionedIndex& aIndex, const std::string& aName,
265 const SGGeod& aOrigin, FGPositioned::Filter* aFilter)
267 NamedIndexRange range = aIndex.equal_range(aName);
268 if (range.first == range.second) {
272 // common case, only one result. looks a bit ugly because these are
273 // sequential iterators, not random-access ones
274 NamedPositionedIndex::const_iterator check = range.first;
275 if (++check == range.second) {
276 // excellent, only one match in the range
277 FGPositioned* r = range.first->second;
279 if (aFilter->hasTypeRange() && !aFilter->passType(r->type())) {
283 if (!aFilter->pass(r)) {
286 } // of have a filter
289 } // of short-circuit logic for single-element range
291 // multiple matches, we need to actually check the distance to each one
292 double minDist = HUGE_VAL;
293 FGPositionedRef result;
294 NamedPositionedIndex::const_iterator it = range.first;
295 SGVec3d cartOrigin(SGVec3d::fromGeod(aOrigin));
297 for (; it != range.second; ++it) {
298 FGPositioned* r = it->second;
300 if (aFilter->hasTypeRange() && !aFilter->passType(r->type())) {
304 if (!aFilter->pass(r)) {
310 double d2 = distSqr(cartOrigin, r->cart());
320 static FGPositioned::List
321 spatialGetClosest(const SGGeod& aPos, unsigned int aN, double aCutoffNm, FGPositioned::Filter* aFilter)
323 FGPositioned::List result;
324 int radius = 1; // start at 1, radius 0 is handled explicitly
326 double lat = aPos.getLatitudeDeg(),
327 lon = aPos.getLongitudeDeg();
328 // final cutoff is in metres, and scaled to account for testing the corners
329 // of the 'box' instead of the centre of each edge
330 double cutoffM = aCutoffNm * SG_NM_TO_METER * 1.5;
332 // base case, simplifes loop to do it seperately here
333 spatialFilterInBucket(sgBucketOffset(lon, lat, 0, 0), aFilter, result);
335 for (;result.size() < aN; ++radius) {
337 double az1, az2, d1, d2;
338 SGGeodesy::inverse(aPos, sgBucketOffset(lon, lat, -radius, -radius).get_center(), az1, az2, d1);
339 SGGeodesy::inverse(aPos, sgBucketOffset(lon, lat, radius, radius).get_center(), az1, az2, d2);
341 if ((d1 > cutoffM) && (d2 > cutoffM)) {
342 //std::cerr << "spatialGetClosest terminating due to range cutoff" << std::endl;
346 FGPositioned::List hits;
347 for ( int i=-radius; i<=radius; i++) {
348 spatialFilterInBucket(sgBucketOffset(lon, lat, i, -radius), aFilter, hits);
349 spatialFilterInBucket(sgBucketOffset(lon, lat, -radius, i), aFilter, hits);
350 spatialFilterInBucket(sgBucketOffset(lon, lat, i, radius), aFilter, hits);
351 spatialFilterInBucket(sgBucketOffset(lon, lat, radius, i), aFilter, hits);
354 result.insert(result.end(), hits.begin(), hits.end()); // append
357 sortByDistance(aPos, result);
358 if (result.size() > aN) {
359 result.resize(aN); // truncate at requested number of matches
365 //////////////////////////////////////////////////////////////////////////////
370 bool operator()(FGPositioned* a, FGPositioned* b) const
372 return a->name() < b->name();
377 * A special purpose helper (imported by FGAirport::searchNamesAndIdents) to
378 * implement the AirportList dialog. It's unfortunate that it needs to reside
379 * here, but for now it's least ugly solution.
381 char** searchAirportNamesAndIdents(const std::string& aFilter)
383 const std::ctype<char> &ct = std::use_facet<std::ctype<char> >(std::locale());
384 std::string filter(aFilter);
385 bool hasFilter = !filter.empty();
387 ct.toupper((char *)filter.data(), (char *)filter.data() + filter.size());
390 NamedPositionedIndex::const_iterator it = global_identIndex.begin();
391 NamedPositionedIndex::const_iterator end = global_identIndex.end();
393 // note this is a vector of raw pointers, not smart pointers, because it
394 // may get very large and smart-pointer-atomicity-locking then becomes a
395 // bottleneck for this case.
396 std::vector<FGPositioned*> matches;
399 for (; it != end; ++it) {
400 FGPositioned::Type ty = it->second->type();
401 if ((ty < FGPositioned::AIRPORT) || (ty > FGPositioned::SEAPORT)) {
405 if (hasFilter && (it->second->ident().find(aFilter) == std::string::npos)) {
406 upper = it->second->name(); // string copy, sadly
407 ct.toupper((char *)upper.data(), (char *)upper.data() + upper.size());
408 if (upper.find(aFilter) == std::string::npos) {
413 matches.push_back(it->second);
416 // sort alphabetically on name
417 std::sort(matches.begin(), matches.end(), OrderByName());
419 // convert results to format comptible with puaList
420 unsigned int numMatches = matches.size();
421 char** result = new char*[numMatches + 1];
422 result[numMatches] = NULL; // end-of-list marker
424 // nasty code to avoid excessive string copying and allocations.
425 // We format results as follows (note whitespace!):
426 // ' name-of-airport-chars (ident)'
427 // so the total length is:
428 // 1 + strlen(name) + 4 + 4 (for the ident) + 1 + 1 (for the null)
429 // which gives a grand total of 11 + the length of the name.
430 // note the ident is sometimes only three letters for non-ICAO small strips
431 for (unsigned int i=0; i<numMatches; ++i) {
432 int nameLength = matches[i]->name().size();
433 int icaoLength = matches[i]->ident().size();
434 char* entry = new char[nameLength + 11];
437 memcpy(dst, matches[i]->name().c_str(), nameLength);
443 memcpy(dst, matches[i]->ident().c_str(), icaoLength);
453 ///////////////////////////////////////////////////////////////////////////////
456 FGPositioned::Filter::hasTypeRange() const
458 assert(minType() <= maxType());
459 return (minType() != INVALID) && (maxType() != INVALID);
463 FGPositioned::Filter::passType(Type aTy) const
465 assert(hasTypeRange());
466 return (minType() <= aTy) && (maxType() >= aTy);
469 static FGPositioned::List
470 findAllSortedByRange(const NamedPositionedIndex& aIndex,
471 const std::string& aName, const SGGeod& aPos, FGPositioned::Filter* aFilter)
473 FGPositioned::List result;
474 NamedIndexRange range = aIndex.equal_range(aName);
475 for (; range.first != range.second; ++range.first) {
476 FGPositioned* candidate = range.first->second;
478 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
482 if (!aFilter->pass(candidate)) {
487 result.push_back(range.first->second);
490 sortByDistance(aPos, result);
494 static FGPositionedRef
495 findWithPartial(const NamedPositionedIndex& aIndex, const std::string& aName,
496 FGPositioned::Filter* aFilter, int aOffset, bool& aNext)
498 // see comment in findNextWithPartialId concerning upperBoundId
499 std::string upperBoundId = aName;
500 upperBoundId[upperBoundId.size()-1]++;
501 NamedPositionedIndex::const_iterator upperBound = aIndex.lower_bound(upperBoundId);
503 NamedIndexRange range = aIndex.equal_range(aName);
504 FGPositionedRef result;
506 while (range.first != upperBound) {
507 for (; range.first != range.second; ++range.first) {
508 FGPositionedRef candidate = range.first->second;
510 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
514 if (!aFilter->pass(candidate)) {
522 } else if (aOffset == 0) {
523 // okay, found our result. we need to go around once more to set aNext
526 --aOffset; // seen one more valid result, decrement the count
530 // Unable to match the filter with this range - try the next range.
531 range = aIndex.equal_range(range.second->first);
534 // if we fell out, we reached the end of the valid range. We might have a
535 // valid result, but we definitiely don't have a next result.
540 ///////////////////////////////////////////////////////////////////////////////
542 FGPositioned::FGPositioned(Type ty, const std::string& aIdent, const SGGeod& aPos, bool aIndexed) :
547 SGReferenced::get(this); // hold an owning ref, for the moment
550 assert(ty != TAXIWAY && ty != PAVEMENT);
555 FGPositioned::~FGPositioned()
557 //std::cout << "destroying:" << mIdent << "/" << nameForType(mType) << std::endl;
558 removeFromIndices(this);
562 FGPositioned::createUserWaypoint(const std::string& aIdent, const SGGeod& aPos)
564 return new FGPositioned(WAYPOINT, aIdent, aPos, true);
568 FGPositioned::bucket() const
570 return SGBucket(mPosition);
574 FGPositioned::cart() const
576 return SGVec3d::fromGeod(mPosition);
579 FGPositioned::Type FGPositioned::typeFromName(const std::string& aName)
581 if (aName.empty() || (aName == "")) {
590 const NameTypeEntry names[] = {
591 {"airport", AIRPORT},
599 {"waypoint", WAYPOINT},
607 std::string lowerName(boost::to_lower_copy(aName));
609 for (const NameTypeEntry* n = names; (n->_name != NULL); ++n) {
610 if (::strcmp(n->_name, lowerName.c_str()) == 0) {
615 SG_LOG(SG_GENERAL, SG_WARN, "FGPositioned::typeFromName: couldn't match:" << aName);
619 const char* FGPositioned::nameForType(Type aTy)
622 case RUNWAY: return "runway";
623 case TAXIWAY: return "taxiway";
624 case PAVEMENT: return "pavement";
625 case PARK_STAND: return "parking stand";
626 case FIX: return "fix";
627 case VOR: return "VOR";
628 case NDB: return "NDB";
629 case ILS: return "ILS";
630 case LOC: return "localiser";
631 case GS: return "glideslope";
632 case OM: return "outer-marker";
633 case MM: return "middle-marker";
634 case IM: return "inner-marker";
635 case AIRPORT: return "airport";
636 case HELIPORT: return "heliport";
637 case SEAPORT: return "seaport";
638 case WAYPOINT: return "waypoint";
639 case DME: return "dme";
640 case TACAN: return "tacan";
646 ///////////////////////////////////////////////////////////////////////////////
647 // search / query functions
650 FGPositioned::findClosestWithIdent(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
652 return namedFindClosest(global_identIndex, aIdent, aPos, aFilter);
656 FGPositioned::findWithinRange(const SGGeod& aPos, double aRangeNm, Filter* aFilter)
659 spatialFind(aPos, aRangeNm, aFilter, result);
660 filterListByRange(aPos, aRangeNm, result);
665 FGPositioned::findAllWithIdentSortedByRange(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
667 return findAllSortedByRange(global_identIndex, aIdent, aPos, aFilter);
671 FGPositioned::findAllWithNameSortedByRange(const std::string& aName, const SGGeod& aPos, Filter* aFilter)
673 return findAllSortedByRange(global_nameIndex, aName, aPos, aFilter);
677 FGPositioned::findClosest(const SGGeod& aPos, double aCutoffNm, Filter* aFilter)
679 FGPositioned::List l(spatialGetClosest(aPos, 1, aCutoffNm, aFilter));
684 assert(l.size() == 1);
689 FGPositioned::findClosestN(const SGGeod& aPos, unsigned int aN, double aCutoffNm, Filter* aFilter)
691 return spatialGetClosest(aPos, aN, aCutoffNm, aFilter);
695 FGPositioned::findNextWithPartialId(FGPositionedRef aCur, const std::string& aId, Filter* aFilter)
697 std::string id(boost::to_upper_copy(aId));
699 // It is essential to bound our search, to avoid iterating all the way to the end of the database.
700 // Do this by generating a second ID with the final character incremented by 1.
701 // e.g., if the partial ID is "KI", we wish to search "KIxxx" but not "KJ".
702 std::string upperBoundId = id;
703 upperBoundId[upperBoundId.size()-1]++;
704 NamedPositionedIndex::const_iterator upperBound = global_identIndex.lower_bound(upperBoundId);
706 NamedIndexRange range = global_identIndex.equal_range(id);
707 while (range.first != upperBound) {
708 for (; range.first != range.second; ++range.first) {
709 FGPositionedRef candidate = range.first->second;
710 if (aCur == candidate) {
711 aCur = NULL; // found our start point, next match will pass
716 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
720 if (!aFilter->pass(candidate)) {
730 // Unable to match the filter with this range - try the next range.
731 range = global_identIndex.equal_range(range.second->first);
734 return NULL; // Reached the end of the valid sequence with no match.
738 FGPositioned::findWithPartialId(const std::string& aId, Filter* aFilter, int aOffset, bool& aNext)
740 return findWithPartial(global_identIndex, aId, aFilter, aOffset, aNext);
745 FGPositioned::findWithPartialName(const std::string& aName, Filter* aFilter, int aOffset, bool& aNext)
747 return findWithPartial(global_nameIndex, aName, aFilter, aOffset, aNext);
751 * Wrapper filter which proxies to an inner filter, but also ensures the
752 * ident starts with supplied partial ident.
754 class PartialIdentFilter : public FGPositioned::Filter
757 PartialIdentFilter(const std::string& ident, FGPositioned::Filter* filter) :
760 _ident = boost::to_upper_copy(ident);
763 virtual bool pass(FGPositioned* aPos) const
765 if (!_inner->pass(aPos)) {
769 return (boost::algorithm::starts_with(aPos->ident(), _ident));
772 virtual FGPositioned::Type minType() const
773 { return _inner->minType(); }
775 virtual FGPositioned::Type maxType() const
776 { return _inner->maxType(); }
780 FGPositioned::Filter* _inner;
783 static FGPositionedRef
784 findClosestWithPartial(const SGGeod& aPos, FGPositioned::Filter* aFilter, int aOffset, bool& aNext)
786 // why aOffset +2 ? at offset=3, we want the fourth search result, but also
787 // to know if the fifth result exists (to set aNext flag for iterative APIs)
788 FGPositioned::List matches =
789 spatialGetClosest(aPos, aOffset + 2, 1000.0, aFilter);
791 if ((int) matches.size() <= aOffset) {
792 SG_LOG(SG_GENERAL, SG_INFO, "findClosestWithPartial, couldn't match enough with prefix");
794 return NULL; // couldn't find a match within the cutoff distance
797 aNext = ((int) matches.size() >= (aOffset + 2));
798 return matches[aOffset];
803 FGPositioned::findClosestWithPartialId(const SGGeod& aPos, const std::string& aId, Filter* aFilter, int aOffset, bool& aNext)
805 PartialIdentFilter pf(aId, aFilter);
806 return findClosestWithPartial(aPos, &pf, aOffset, aNext);
810 * Wrapper filter which proxies to an inner filter, but also ensures the
811 * name starts with supplied partial name.
813 class PartialNameFilter : public FGPositioned::Filter
816 PartialNameFilter(const std::string& nm, FGPositioned::Filter* filter) :
822 virtual bool pass(FGPositioned* aPos) const
824 if (!_inner->pass(aPos)) {
828 return (boost::algorithm::istarts_with(aPos->name(), _name));
831 virtual FGPositioned::Type minType() const
832 { return _inner->minType(); }
834 virtual FGPositioned::Type maxType() const
835 { return _inner->maxType(); }
839 FGPositioned::Filter* _inner;
843 FGPositioned::findClosestWithPartialName(const SGGeod& aPos, const std::string& aName, Filter* aFilter, int aOffset, bool& aNext)
845 PartialNameFilter pf(aName, aFilter);
846 return findClosestWithPartial(aPos, &pf, aOffset, aNext);