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.
25 #include "positioned.hxx"
29 #include <algorithm> // for sort
32 #include <boost/algorithm/string/case_conv.hpp>
33 #include <boost/algorithm/string/predicate.hpp>
35 #include <osg/Math> // for osg::isNaN
37 #include <simgear/timing/timestamp.hxx>
38 #include <simgear/debug/logstream.hxx>
39 #include <simgear/structure/exception.hxx>
40 #include <simgear/math/SGGeometry.hxx>
44 typedef std::multimap<std::string, FGPositioned*> NamedPositionedIndex;
45 typedef std::pair<NamedPositionedIndex::const_iterator, NamedPositionedIndex::const_iterator> NamedIndexRange;
47 using std::lower_bound;
48 using std::upper_bound;
50 static NamedPositionedIndex global_identIndex;
51 static NamedPositionedIndex global_nameIndex;
53 //////////////////////////////////////////////////////////////////////////////
58 const double LEAF_SIZE = SG_NM_TO_METER * 8.0;
59 const double LEAF_SIZE_SQR = LEAF_SIZE * LEAF_SIZE;
62 * Decorate an object with a double value, and use that value to order
63 * items, for the purpoises of the STL algorithms
69 Ordered(const T& v, double x) :
75 Ordered(const Ordered<T>& a) :
81 Ordered<T>& operator=(const Ordered<T>& a)
88 bool operator<(const Ordered<T>& other) const
90 return _order < other._order;
93 bool operator>(const Ordered<T>& other) const
95 return _order > other._order;
110 typedef Ordered<Node*> OrderedNode;
111 typedef std::greater<OrderedNode> FNPQCompare;
114 * the priority queue is fundamental to our search algorithm. When searching,
115 * we know the front of the queue is the nearest unexpanded node (to the search
116 * location). The default STL pqueue returns the 'largest' item from top(), so
117 * to get the smallest, we need to replace the default Compare functor (less<>)
120 typedef std::priority_queue<OrderedNode, std::vector<OrderedNode>, FNPQCompare> FindNearestPQueue;
122 typedef Ordered<FGPositioned*> OrderedPositioned;
123 typedef std::vector<OrderedPositioned> FindNearestResults;
125 Node* global_spatialOctree = NULL;
128 * Octree node base class, tracks its bounding box and provides various
129 * queries relating to it
134 bool contains(const SGVec3d& aPos) const
136 return intersects(aPos, _box);
139 double distSqrToNearest(const SGVec3d& aPos) const
141 return distSqr(aPos, _box.getClosestPoint(aPos));
144 virtual void insert(FGPositioned* aP) = 0;
146 virtual void visit(const SGVec3d& aPos, double aCutoff,
147 FGPositioned::Filter* aFilter,
148 FindNearestResults& aResults, FindNearestPQueue&) = 0;
150 Node(const SGBoxd &aBox) :
158 class Leaf : public Node
161 Leaf(const SGBoxd& aBox) :
166 const FGPositioned::List& members() const
169 virtual void insert(FGPositioned* aP)
171 _members.push_back(aP);
174 virtual void visit(const SGVec3d& aPos, double aCutoff,
175 FGPositioned::Filter* aFilter,
176 FindNearestResults& aResults, FindNearestPQueue&)
178 int previousResultsSize = aResults.size();
181 for (unsigned int i=0; i<_members.size(); ++i) {
182 FGPositioned* p = _members[i];
183 double d2 = distSqr(aPos, p->cart());
189 if (aFilter->hasTypeRange() && !aFilter->passType(p->type())) {
193 if (!aFilter->pass(p)) {
196 } // of have a filter
199 aResults.push_back(OrderedPositioned(p, d2));
202 if (addedCount == 0) {
206 // keep aResults sorted
207 // sort the new items, usually just one or two items
208 std::sort(aResults.begin() + previousResultsSize, aResults.end());
210 // merge the two sorted ranges together - in linear time
211 std::inplace_merge(aResults.begin(),
212 aResults.begin() + previousResultsSize, aResults.end());
215 FGPositioned::List _members;
218 class Branch : public Node
221 Branch(const SGBoxd& aBox) :
224 memset(children, 0, sizeof(Node*) * 8);
227 virtual void insert(FGPositioned* aP)
229 SGVec3d cart(aP->cart());
230 assert(contains(cart));
233 SGVec3d center(_box.getCenter());
234 // tests must match indices in SGbox::getCorner
235 if (cart.x() < center.x()) {
239 if (cart.y() < center.y()) {
243 if (cart.z() < center.z()) {
247 Node* child = children[childIndex];
248 if (!child) { // lazy building of children
249 SGBoxd cb(boxForChild(childIndex));
250 double d2 = dot(cb.getSize(), cb.getSize());
251 if (d2 < LEAF_SIZE_SQR) {
252 child = new Leaf(cb);
254 child = new Branch(cb);
257 children[childIndex] = child;
263 virtual void visit(const SGVec3d& aPos, double aCutoff,
264 FGPositioned::Filter*,
265 FindNearestResults&, FindNearestPQueue& aQ)
267 for (unsigned int i=0; i<8; ++i) {
272 double d2 = children[i]->distSqrToNearest(aPos);
274 continue; // exceeded cutoff
277 aQ.push(Ordered<Node*>(children[i], d2));
278 } // of child iteration
284 * Return the box for a child touching the specified corner
286 SGBoxd boxForChild(unsigned int aCorner) const
288 SGBoxd r(_box.getCenter());
289 r.expandBy(_box.getCorner(aCorner));
296 void findNearestN(const SGVec3d& aPos, unsigned int aN, double aCutoffM, FGPositioned::Filter* aFilter, FGPositioned::List& aResults)
299 FindNearestPQueue pq;
300 FindNearestResults results;
301 pq.push(Ordered<Node*>(global_spatialOctree, 0));
302 double cut = aCutoffM * aCutoffM;
304 while (!pq.empty()) {
305 if (!results.empty()) {
306 // terminate the search if we have sufficent results, and we are
307 // sure no node still on the queue contains a closer match
308 double furthestResultOrder = results.back().order();
309 if ((results.size() >= aN) && (furthestResultOrder < pq.top().order())) {
314 Node* nd = pq.top().get();
317 nd->visit(aPos, cut, aFilter, results, pq);
318 } // of queue iteration
320 // depending on leaf population, we may have (slighty) more results
322 unsigned int numResults = std::min((unsigned int) results.size(), aN);
324 aResults.resize(numResults);
325 for (unsigned int r=0; r<numResults; ++r) {
326 aResults[r] = results[r].get();
330 void findAllWithinRange(const SGVec3d& aPos, double aRangeM, FGPositioned::Filter* aFilter, FGPositioned::List& aResults)
333 FindNearestPQueue pq;
334 FindNearestResults results;
335 pq.push(Ordered<Node*>(global_spatialOctree, 0));
336 double rng = aRangeM * aRangeM;
338 while (!pq.empty()) {
339 Node* nd = pq.top().get();
342 nd->visit(aPos, rng, aFilter, results, pq);
343 } // of queue iteration
345 unsigned int numResults = results.size();
347 aResults.resize(numResults);
348 for (unsigned int r=0; r<numResults; ++r) {
349 aResults[r] = results[r].get();
353 } // of namespace Octree
355 //////////////////////////////////////////////////////////////////////////////
358 addToIndices(FGPositioned* aPos)
361 if (!aPos->ident().empty()) {
362 std::string u(boost::to_upper_copy(aPos->ident()));
364 global_identIndex.insert(global_identIndex.begin(),
365 std::make_pair(u, aPos));
368 if (!aPos->name().empty()) {
369 std::string u(boost::to_upper_copy(aPos->name()));
371 global_nameIndex.insert(global_nameIndex.begin(),
372 std::make_pair(u, aPos));
375 if (!Octree::global_spatialOctree) {
376 double RADIUS_EARTH_M = 7000 * 1000.0; // 7000km is plenty
377 SGVec3d earthExtent(RADIUS_EARTH_M, RADIUS_EARTH_M, RADIUS_EARTH_M);
378 Octree::global_spatialOctree = new Octree::Branch(SGBox<double>(-earthExtent, earthExtent));
380 Octree::global_spatialOctree->insert(aPos);
384 removeFromIndices(FGPositioned* aPos)
388 if (!aPos->ident().empty()) {
389 std::string u(boost::to_upper_copy(aPos->ident()));
390 NamedPositionedIndex::iterator it = global_identIndex.find(u);
391 while (it != global_identIndex.end() && (it->first == u)) {
392 if (it->second == aPos) {
393 global_identIndex.erase(it);
398 } // of multimap walk
401 if (!aPos->name().empty()) {
402 std::string u(boost::to_upper_copy(aPos->name()));
403 NamedPositionedIndex::iterator it = global_nameIndex.find(u);
404 while (it != global_nameIndex.end() && (it->first == u)) {
405 if (it->second == aPos) {
406 global_nameIndex.erase(it);
411 } // of multimap walk
415 //////////////////////////////////////////////////////////////////////////////
420 bool operator()(FGPositioned* a, FGPositioned* b) const
422 return a->name() < b->name();
426 void findInIndex(NamedPositionedIndex& aIndex, const std::string& aFind, std::vector<FGPositioned*>& aResult)
428 NamedPositionedIndex::const_iterator it = aIndex.begin();
429 NamedPositionedIndex::const_iterator end = aIndex.end();
431 bool haveFilter = !aFind.empty();
433 for (; it != end; ++it) {
434 FGPositioned::Type ty = it->second->type();
435 if ((ty < FGPositioned::AIRPORT) || (ty > FGPositioned::SEAPORT)) {
439 if (haveFilter && it->first.find(aFind) == std::string::npos) {
443 aResult.push_back(it->second);
444 } // of index iteration
448 * A special purpose helper (imported by FGAirport::searchNamesAndIdents) to
449 * implement the AirportList dialog. It's unfortunate that it needs to reside
450 * here, but for now it's least ugly solution.
452 char** searchAirportNamesAndIdents(const std::string& aFilter)
454 // note this is a vector of raw pointers, not smart pointers, because it
455 // may get very large and smart-pointer-atomicity-locking then becomes a
456 // bottleneck for this case.
457 std::vector<FGPositioned*> matches;
458 if (!aFilter.empty()) {
459 std::string filter = boost::to_upper_copy(aFilter);
460 findInIndex(global_identIndex, filter, matches);
461 findInIndex(global_nameIndex, filter, matches);
464 findInIndex(global_identIndex, std::string(), matches);
467 // sort alphabetically on name
468 std::sort(matches.begin(), matches.end(), OrderByName());
470 // convert results to format comptible with puaList
471 unsigned int numMatches = matches.size();
472 char** result = new char*[numMatches + 1];
473 result[numMatches] = NULL; // end-of-list marker
475 // nasty code to avoid excessive string copying and allocations.
476 // We format results as follows (note whitespace!):
477 // ' name-of-airport-chars (ident)'
478 // so the total length is:
479 // 1 + strlen(name) + 4 + strlen(icao) + 1 + 1 (for the null)
480 // which gives a grand total of 7 + name-length + icao-length.
481 // note the ident can be three letters (non-ICAO local strip), four
482 // (default ICAO) or more (extended format ICAO)
483 for (unsigned int i=0; i<numMatches; ++i) {
484 int nameLength = matches[i]->name().size();
485 int icaoLength = matches[i]->ident().size();
486 char* entry = new char[7 + nameLength + icaoLength];
489 memcpy(dst, matches[i]->name().c_str(), nameLength);
495 memcpy(dst, matches[i]->ident().c_str(), icaoLength);
505 static void validateSGGeod(const SGGeod& geod)
507 if (osg::isNaN(geod.getLatitudeDeg()) ||
508 osg::isNaN(geod.getLongitudeDeg()))
510 throw sg_range_exception("position is invalid, NaNs");
514 ///////////////////////////////////////////////////////////////////////////////
517 FGPositioned::Filter::hasTypeRange() const
519 assert(minType() <= maxType());
520 return (minType() != INVALID) && (maxType() != INVALID);
524 FGPositioned::Filter::passType(Type aTy) const
526 assert(hasTypeRange());
527 return (minType() <= aTy) && (maxType() >= aTy);
530 static FGPositioned::List
531 findAll(const NamedPositionedIndex& aIndex,
532 const std::string& aName,
533 FGPositioned::Filter* aFilter,
536 FGPositioned::List result;
541 std::string name = boost::to_upper_copy(aName);
542 NamedPositionedIndex::const_iterator upperBound;
545 upperBound = aIndex.upper_bound(name);
547 std::string upperBoundId = name;
548 upperBoundId[upperBoundId.size()-1]++;
549 upperBound = aIndex.lower_bound(upperBoundId);
552 NamedPositionedIndex::const_iterator it = aIndex.lower_bound(name);
554 for (; it != upperBound; ++it) {
555 FGPositionedRef candidate = it->second;
557 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
561 if (!aFilter->pass(candidate)) {
566 result.push_back(candidate);
572 ///////////////////////////////////////////////////////////////////////////////
574 FGPositioned::FGPositioned(Type ty, const std::string& aIdent, const SGGeod& aPos) :
581 void FGPositioned::init(bool aIndexed)
583 SGReferenced::get(this); // hold an owning ref, for the moment
584 mCart = SGVec3d::fromGeod(mPosition);
587 assert(mType != TAXIWAY && mType != PAVEMENT);
592 FGPositioned::~FGPositioned()
594 //std::cout << "destroying:" << mIdent << "/" << nameForType(mType) << std::endl;
595 removeFromIndices(this);
599 FGPositioned::createUserWaypoint(const std::string& aIdent, const SGGeod& aPos)
601 FGPositioned* wpt = new FGPositioned(WAYPOINT, aIdent, aPos);
607 FGPositioned::cart() const
612 FGPositioned::Type FGPositioned::typeFromName(const std::string& aName)
614 if (aName.empty() || (aName == "")) {
623 const NameTypeEntry names[] = {
624 {"airport", AIRPORT},
632 {"waypoint", WAYPOINT},
641 std::string lowerName(boost::to_lower_copy(aName));
643 for (const NameTypeEntry* n = names; (n->_name != NULL); ++n) {
644 if (::strcmp(n->_name, lowerName.c_str()) == 0) {
649 SG_LOG(SG_GENERAL, SG_WARN, "FGPositioned::typeFromName: couldn't match:" << aName);
653 const char* FGPositioned::nameForType(Type aTy)
656 case RUNWAY: return "runway";
657 case TAXIWAY: return "taxiway";
658 case PAVEMENT: return "pavement";
659 case PARK_STAND: return "parking stand";
660 case FIX: return "fix";
661 case VOR: return "VOR";
662 case NDB: return "NDB";
663 case ILS: return "ILS";
664 case LOC: return "localiser";
665 case GS: return "glideslope";
666 case OM: return "outer-marker";
667 case MM: return "middle-marker";
668 case IM: return "inner-marker";
669 case AIRPORT: return "airport";
670 case HELIPORT: return "heliport";
671 case SEAPORT: return "seaport";
672 case WAYPOINT: return "waypoint";
673 case DME: return "dme";
674 case TACAN: return "tacan";
680 ///////////////////////////////////////////////////////////////////////////////
681 // search / query functions
684 FGPositioned::findClosestWithIdent(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
686 validateSGGeod(aPos);
688 FGPositioned::List r(findAll(global_identIndex, aIdent, aFilter, true));
690 return FGPositionedRef();
693 sortByRange(r, aPos);
698 FGPositioned::findWithinRange(const SGGeod& aPos, double aRangeNm, Filter* aFilter)
700 validateSGGeod(aPos);
703 Octree::findAllWithinRange(SGVec3d::fromGeod(aPos),
704 aRangeNm * SG_NM_TO_METER, aFilter, result);
709 FGPositioned::findAllWithIdent(const std::string& aIdent, Filter* aFilter, bool aExact)
711 return findAll(global_identIndex, aIdent, aFilter, aExact);
715 FGPositioned::findAllWithName(const std::string& aName, Filter* aFilter, bool aExact)
717 return findAll(global_nameIndex, aName, aFilter, aExact);
721 FGPositioned::findClosest(const SGGeod& aPos, double aCutoffNm, Filter* aFilter)
723 validateSGGeod(aPos);
725 List l(findClosestN(aPos, 1, aCutoffNm, aFilter));
730 assert(l.size() == 1);
735 FGPositioned::findClosestN(const SGGeod& aPos, unsigned int aN, double aCutoffNm, Filter* aFilter)
737 validateSGGeod(aPos);
740 Octree::findNearestN(SGVec3d::fromGeod(aPos), aN, aCutoffNm * SG_NM_TO_METER, aFilter, result);
745 FGPositioned::findNextWithPartialId(FGPositionedRef aCur, const std::string& aId, Filter* aFilter)
751 std::string id(boost::to_upper_copy(aId));
753 // It is essential to bound our search, to avoid iterating all the way to the end of the database.
754 // Do this by generating a second ID with the final character incremented by 1.
755 // e.g., if the partial ID is "KI", we wish to search "KIxxx" but not "KJ".
756 std::string upperBoundId = id;
757 upperBoundId[upperBoundId.size()-1]++;
758 NamedPositionedIndex::const_iterator upperBound = global_identIndex.lower_bound(upperBoundId);
760 NamedIndexRange range = global_identIndex.equal_range(id);
761 while (range.first != upperBound) {
762 for (; range.first != range.second; ++range.first) {
763 FGPositionedRef candidate = range.first->second;
764 if (aCur == candidate) {
765 aCur = NULL; // found our start point, next match will pass
770 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
774 if (!aFilter->pass(candidate)) {
784 // Unable to match the filter with this range - try the next range.
785 range = global_identIndex.equal_range(range.second->first);
788 return NULL; // Reached the end of the valid sequence with no match.
792 FGPositioned::sortByRange(List& aResult, const SGGeod& aPos)
794 validateSGGeod(aPos);
796 SGVec3d cartPos(SGVec3d::fromGeod(aPos));
797 // computer ordering values
798 Octree::FindNearestResults r;
799 List::iterator it = aResult.begin(), lend = aResult.end();
800 for (; it != lend; ++it) {
801 double d2 = distSqr((*it)->cart(), cartPos);
802 r.push_back(Octree::OrderedPositioned(*it, d2));
806 std::sort(r.begin(), r.end());
808 // convert to a plain list
809 unsigned int count = aResult.size();
810 for (unsigned int i=0; i<count; ++i) {
811 aResult[i] = r[i].get();