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
33 #include <boost/algorithm/string/case_conv.hpp>
34 #include <boost/algorithm/string/predicate.hpp>
36 #include <osg/Math> // for osg::isNaN
38 #include <simgear/timing/timestamp.hxx>
39 #include <simgear/props/props.hxx>
40 #include <simgear/debug/logstream.hxx>
41 #include <simgear/structure/exception.hxx>
42 #include <simgear/math/SGGeometry.hxx>
43 #include <simgear/sg_inlines.h>
44 #include <simgear/structure/commands.hxx>
46 #include "Airports/simple.hxx"
47 #include "Main/fg_props.hxx"
49 typedef std::multimap<std::string, FGPositioned*> NamedPositionedIndex;
50 typedef std::pair<NamedPositionedIndex::const_iterator, NamedPositionedIndex::const_iterator> NamedIndexRange;
52 using std::lower_bound;
53 using std::upper_bound;
55 static NamedPositionedIndex global_identIndex;
56 static NamedPositionedIndex global_nameIndex;
58 //////////////////////////////////////////////////////////////////////////////
63 const double LEAF_SIZE = SG_NM_TO_METER * 8.0;
64 const double LEAF_SIZE_SQR = LEAF_SIZE * LEAF_SIZE;
67 * Decorate an object with a double value, and use that value to order
68 * items, for the purpoises of the STL algorithms
74 Ordered(const T& v, double x) :
80 Ordered(const Ordered<T>& a) :
86 Ordered<T>& operator=(const Ordered<T>& a)
93 bool operator<(const Ordered<T>& other) const
95 return _order < other._order;
98 bool operator>(const Ordered<T>& other) const
100 return _order > other._order;
115 typedef Ordered<Node*> OrderedNode;
116 typedef std::greater<OrderedNode> FNPQCompare;
119 * the priority queue is fundamental to our search algorithm. When searching,
120 * we know the front of the queue is the nearest unexpanded node (to the search
121 * location). The default STL pqueue returns the 'largest' item from top(), so
122 * to get the smallest, we need to replace the default Compare functor (less<>)
125 typedef std::priority_queue<OrderedNode, std::vector<OrderedNode>, FNPQCompare> FindNearestPQueue;
127 typedef Ordered<FGPositioned*> OrderedPositioned;
128 typedef std::vector<OrderedPositioned> FindNearestResults;
130 Node* global_spatialOctree = NULL;
133 * Octree node base class, tracks its bounding box and provides various
134 * queries relating to it
139 bool contains(const SGVec3d& aPos) const
141 return intersects(aPos, _box);
144 double distSqrToNearest(const SGVec3d& aPos) const
146 return distSqr(aPos, _box.getClosestPoint(aPos));
149 virtual void insert(FGPositioned* aP) = 0;
151 virtual void visit(const SGVec3d& aPos, double aCutoff,
152 FGPositioned::Filter* aFilter,
153 FindNearestResults& aResults, FindNearestPQueue&) = 0;
155 Node(const SGBoxd &aBox) :
163 class Leaf : public Node
166 Leaf(const SGBoxd& aBox) :
171 const FGPositioned::List& members() const
174 virtual void insert(FGPositioned* aP)
176 _members.push_back(aP);
179 virtual void visit(const SGVec3d& aPos, double aCutoff,
180 FGPositioned::Filter* aFilter,
181 FindNearestResults& aResults, FindNearestPQueue&)
183 int previousResultsSize = aResults.size();
186 for (unsigned int i=0; i<_members.size(); ++i) {
187 FGPositioned* p = _members[i];
188 double d2 = distSqr(aPos, p->cart());
194 if (aFilter->hasTypeRange() && !aFilter->passType(p->type())) {
198 if (!aFilter->pass(p)) {
201 } // of have a filter
204 aResults.push_back(OrderedPositioned(p, d2));
207 if (addedCount == 0) {
211 // keep aResults sorted
212 // sort the new items, usually just one or two items
213 std::sort(aResults.begin() + previousResultsSize, aResults.end());
215 // merge the two sorted ranges together - in linear time
216 std::inplace_merge(aResults.begin(),
217 aResults.begin() + previousResultsSize, aResults.end());
220 FGPositioned::List _members;
223 class Branch : public Node
226 Branch(const SGBoxd& aBox) :
229 memset(children, 0, sizeof(Node*) * 8);
232 virtual void insert(FGPositioned* aP)
234 SGVec3d cart(aP->cart());
235 assert(contains(cart));
238 SGVec3d center(_box.getCenter());
239 // tests must match indices in SGbox::getCorner
240 if (cart.x() < center.x()) {
244 if (cart.y() < center.y()) {
248 if (cart.z() < center.z()) {
252 Node* child = children[childIndex];
253 if (!child) { // lazy building of children
254 SGBoxd cb(boxForChild(childIndex));
255 double d2 = dot(cb.getSize(), cb.getSize());
256 if (d2 < LEAF_SIZE_SQR) {
257 child = new Leaf(cb);
259 child = new Branch(cb);
262 children[childIndex] = child;
268 virtual void visit(const SGVec3d& aPos, double aCutoff,
269 FGPositioned::Filter*,
270 FindNearestResults&, FindNearestPQueue& aQ)
272 for (unsigned int i=0; i<8; ++i) {
277 double d2 = children[i]->distSqrToNearest(aPos);
279 continue; // exceeded cutoff
282 aQ.push(Ordered<Node*>(children[i], d2));
283 } // of child iteration
289 * Return the box for a child touching the specified corner
291 SGBoxd boxForChild(unsigned int aCorner) const
293 SGBoxd r(_box.getCenter());
294 r.expandBy(_box.getCorner(aCorner));
301 void findNearestN(const SGVec3d& aPos, unsigned int aN, double aCutoffM, FGPositioned::Filter* aFilter, FGPositioned::List& aResults)
304 FindNearestPQueue pq;
305 FindNearestResults results;
306 pq.push(Ordered<Node*>(global_spatialOctree, 0));
307 double cut = aCutoffM * aCutoffM;
309 while (!pq.empty()) {
310 if (!results.empty()) {
311 // terminate the search if we have sufficent results, and we are
312 // sure no node still on the queue contains a closer match
313 double furthestResultOrder = results.back().order();
314 if ((results.size() >= aN) && (furthestResultOrder < pq.top().order())) {
319 Node* nd = pq.top().get();
322 nd->visit(aPos, cut, aFilter, results, pq);
323 } // of queue iteration
325 // depending on leaf population, we may have (slighty) more results
327 unsigned int numResults = std::min((unsigned int) results.size(), aN);
329 aResults.resize(numResults);
330 for (unsigned int r=0; r<numResults; ++r) {
331 aResults[r] = results[r].get();
335 void findAllWithinRange(const SGVec3d& aPos, double aRangeM, FGPositioned::Filter* aFilter, FGPositioned::List& aResults)
338 FindNearestPQueue pq;
339 FindNearestResults results;
340 pq.push(Ordered<Node*>(global_spatialOctree, 0));
341 double rng = aRangeM * aRangeM;
343 while (!pq.empty()) {
344 Node* nd = pq.top().get();
347 nd->visit(aPos, rng, aFilter, results, pq);
348 } // of queue iteration
350 unsigned int numResults = results.size();
352 aResults.resize(numResults);
353 for (unsigned int r=0; r<numResults; ++r) {
354 aResults[r] = results[r].get();
358 } // of namespace Octree
360 //////////////////////////////////////////////////////////////////////////////
363 addToIndices(FGPositioned* aPos)
366 if (!aPos->ident().empty()) {
367 std::string u(boost::to_upper_copy(aPos->ident()));
369 global_identIndex.insert(global_identIndex.begin(),
370 std::make_pair(u, aPos));
373 if (!aPos->name().empty()) {
374 std::string u(boost::to_upper_copy(aPos->name()));
376 global_nameIndex.insert(global_nameIndex.begin(),
377 std::make_pair(u, aPos));
380 if (!Octree::global_spatialOctree) {
381 double RADIUS_EARTH_M = 7000 * 1000.0; // 7000km is plenty
382 SGVec3d earthExtent(RADIUS_EARTH_M, RADIUS_EARTH_M, RADIUS_EARTH_M);
383 Octree::global_spatialOctree = new Octree::Branch(SGBox<double>(-earthExtent, earthExtent));
385 Octree::global_spatialOctree->insert(aPos);
389 removeFromIndices(FGPositioned* aPos)
393 if (!aPos->ident().empty()) {
394 std::string u(boost::to_upper_copy(aPos->ident()));
395 NamedPositionedIndex::iterator it = global_identIndex.find(u);
396 while (it != global_identIndex.end() && (it->first == u)) {
397 if (it->second == aPos) {
398 global_identIndex.erase(it);
403 } // of multimap walk
406 if (!aPos->name().empty()) {
407 std::string u(boost::to_upper_copy(aPos->name()));
408 NamedPositionedIndex::iterator it = global_nameIndex.find(u);
409 while (it != global_nameIndex.end() && (it->first == u)) {
410 if (it->second == aPos) {
411 global_nameIndex.erase(it);
416 } // of multimap walk
420 //////////////////////////////////////////////////////////////////////////////
425 bool operator()(FGPositioned* a, FGPositioned* b) const
427 return a->name() < b->name();
431 void findInIndex(NamedPositionedIndex& aIndex, const std::string& aFind, std::vector<FGPositioned*>& aResult)
433 NamedPositionedIndex::const_iterator it = aIndex.begin();
434 NamedPositionedIndex::const_iterator end = aIndex.end();
436 bool haveFilter = !aFind.empty();
438 for (; it != end; ++it) {
439 FGPositioned::Type ty = it->second->type();
440 if ((ty < FGPositioned::AIRPORT) || (ty > FGPositioned::SEAPORT)) {
444 if (haveFilter && it->first.find(aFind) == std::string::npos) {
448 aResult.push_back(it->second);
449 } // of index iteration
453 * A special purpose helper (imported by FGAirport::searchNamesAndIdents) to
454 * implement the AirportList dialog. It's unfortunate that it needs to reside
455 * here, but for now it's least ugly solution.
457 char** searchAirportNamesAndIdents(const std::string& aFilter)
459 // note this is a vector of raw pointers, not smart pointers, because it
460 // may get very large and smart-pointer-atomicity-locking then becomes a
461 // bottleneck for this case.
462 std::vector<FGPositioned*> matches;
463 if (!aFilter.empty()) {
464 std::string filter = boost::to_upper_copy(aFilter);
465 findInIndex(global_identIndex, filter, matches);
466 findInIndex(global_nameIndex, filter, matches);
469 findInIndex(global_identIndex, std::string(), matches);
472 // sort alphabetically on name
473 std::sort(matches.begin(), matches.end(), OrderByName());
475 // convert results to format comptible with puaList
476 unsigned int numMatches = matches.size();
477 char** result = new char*[numMatches + 1];
478 result[numMatches] = NULL; // end-of-list marker
480 // nasty code to avoid excessive string copying and allocations.
481 // We format results as follows (note whitespace!):
482 // ' name-of-airport-chars (ident)'
483 // so the total length is:
484 // 1 + strlen(name) + 4 + strlen(icao) + 1 + 1 (for the null)
485 // which gives a grand total of 7 + name-length + icao-length.
486 // note the ident can be three letters (non-ICAO local strip), four
487 // (default ICAO) or more (extended format ICAO)
488 for (unsigned int i=0; i<numMatches; ++i) {
489 int nameLength = matches[i]->name().size();
490 int icaoLength = matches[i]->ident().size();
491 char* entry = new char[7 + nameLength + icaoLength];
494 memcpy(dst, matches[i]->name().c_str(), nameLength);
500 memcpy(dst, matches[i]->ident().c_str(), icaoLength);
510 static void validateSGGeod(const SGGeod& geod)
512 if (osg::isNaN(geod.getLatitudeDeg()) ||
513 osg::isNaN(geod.getLongitudeDeg()))
515 throw sg_range_exception("position is invalid, NaNs");
519 ///////////////////////////////////////////////////////////////////////////////
522 FGPositioned::Filter::hasTypeRange() const
524 assert(minType() <= maxType());
525 return (minType() != INVALID) && (maxType() != INVALID);
529 FGPositioned::Filter::passType(Type aTy) const
531 assert(hasTypeRange());
532 return (minType() <= aTy) && (maxType() >= aTy);
535 static FGPositioned::List
536 findAll(const NamedPositionedIndex& aIndex,
537 const std::string& aName,
538 FGPositioned::Filter* aFilter,
541 FGPositioned::List result;
546 std::string name = boost::to_upper_copy(aName);
547 NamedPositionedIndex::const_iterator upperBound;
550 upperBound = aIndex.upper_bound(name);
552 std::string upperBoundId = name;
553 upperBoundId[upperBoundId.size()-1]++;
554 upperBound = aIndex.lower_bound(upperBoundId);
557 NamedPositionedIndex::const_iterator it = aIndex.lower_bound(name);
559 for (; it != upperBound; ++it) {
560 FGPositionedRef candidate = it->second;
562 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
566 if (!aFilter->pass(candidate)) {
571 result.push_back(candidate);
577 ///////////////////////////////////////////////////////////////////////////////
579 FGPositioned::FGPositioned(Type ty, const std::string& aIdent, const SGGeod& aPos) :
586 void FGPositioned::init(bool aIndexed)
588 SGReferenced::get(this); // hold an owning ref, for the moment
589 mCart = SGVec3d::fromGeod(mPosition);
592 assert(mType != TAXIWAY && mType != PAVEMENT);
597 FGPositioned::~FGPositioned()
599 //std::cout << "destroying:" << mIdent << "/" << nameForType(mType) << std::endl;
600 removeFromIndices(this);
604 FGPositioned::createUserWaypoint(const std::string& aIdent, const SGGeod& aPos)
606 FGPositioned* wpt = new FGPositioned(WAYPOINT, aIdent, aPos);
612 FGPositioned::cart() const
617 FGPositioned::Type FGPositioned::typeFromName(const std::string& aName)
619 if (aName.empty() || (aName == "")) {
628 const NameTypeEntry names[] = {
629 {"airport", AIRPORT},
641 {"tower", FREQ_TOWER},
642 {"ground", FREQ_GROUND},
643 {"approach", FREQ_APP_DEP},
644 {"departure", FREQ_APP_DEP},
646 {"gnd", FREQ_GROUND},
648 {"waypoint", WAYPOINT},
657 std::string lowerName(boost::to_lower_copy(aName));
659 for (const NameTypeEntry* n = names; (n->_name != NULL); ++n) {
660 if (::strcmp(n->_name, lowerName.c_str()) == 0) {
665 SG_LOG(SG_GENERAL, SG_WARN, "FGPositioned::typeFromName: couldn't match:" << aName);
669 const char* FGPositioned::nameForType(Type aTy)
672 case RUNWAY: return "runway";
673 case TAXIWAY: return "taxiway";
674 case PAVEMENT: return "pavement";
675 case PARK_STAND: return "parking stand";
676 case FIX: return "fix";
677 case VOR: return "VOR";
678 case NDB: return "NDB";
679 case ILS: return "ILS";
680 case LOC: return "localiser";
681 case GS: return "glideslope";
682 case OM: return "outer-marker";
683 case MM: return "middle-marker";
684 case IM: return "inner-marker";
685 case AIRPORT: return "airport";
686 case HELIPORT: return "heliport";
687 case SEAPORT: return "seaport";
688 case WAYPOINT: return "waypoint";
689 case DME: return "dme";
690 case TACAN: return "tacan";
691 case FREQ_TOWER: return "tower";
692 case FREQ_ATIS: return "atis";
693 case FREQ_AWOS: return "awos";
694 case FREQ_GROUND: return "ground";
695 case FREQ_CLEARANCE: return "clearance";
696 case FREQ_UNICOM: return "unicom";
697 case FREQ_APP_DEP: return "approach-departure";
703 ///////////////////////////////////////////////////////////////////////////////
704 // search / query functions
707 FGPositioned::findClosestWithIdent(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
709 validateSGGeod(aPos);
711 FGPositioned::List r(findAll(global_identIndex, aIdent, aFilter, true));
713 return FGPositionedRef();
716 sortByRange(r, aPos);
721 FGPositioned::findWithinRange(const SGGeod& aPos, double aRangeNm, Filter* aFilter)
723 validateSGGeod(aPos);
726 Octree::findAllWithinRange(SGVec3d::fromGeod(aPos),
727 aRangeNm * SG_NM_TO_METER, aFilter, result);
732 FGPositioned::findAllWithIdent(const std::string& aIdent, Filter* aFilter, bool aExact)
734 return findAll(global_identIndex, aIdent, aFilter, aExact);
738 FGPositioned::findAllWithName(const std::string& aName, Filter* aFilter, bool aExact)
740 return findAll(global_nameIndex, aName, aFilter, aExact);
744 FGPositioned::findClosest(const SGGeod& aPos, double aCutoffNm, Filter* aFilter)
746 validateSGGeod(aPos);
748 List l(findClosestN(aPos, 1, aCutoffNm, aFilter));
753 assert(l.size() == 1);
758 FGPositioned::findClosestN(const SGGeod& aPos, unsigned int aN, double aCutoffNm, Filter* aFilter)
760 validateSGGeod(aPos);
763 Octree::findNearestN(SGVec3d::fromGeod(aPos), aN, aCutoffNm * SG_NM_TO_METER, aFilter, result);
768 FGPositioned::findNextWithPartialId(FGPositionedRef aCur, const std::string& aId, Filter* aFilter)
774 std::string id(boost::to_upper_copy(aId));
776 // It is essential to bound our search, to avoid iterating all the way to the end of the database.
777 // Do this by generating a second ID with the final character incremented by 1.
778 // e.g., if the partial ID is "KI", we wish to search "KIxxx" but not "KJ".
779 std::string upperBoundId = id;
780 upperBoundId[upperBoundId.size()-1]++;
781 NamedPositionedIndex::const_iterator upperBound = global_identIndex.lower_bound(upperBoundId);
783 NamedIndexRange range = global_identIndex.equal_range(id);
784 while (range.first != upperBound) {
785 for (; range.first != range.second; ++range.first) {
786 FGPositionedRef candidate = range.first->second;
787 if (aCur == candidate) {
788 aCur = NULL; // found our start point, next match will pass
793 if (aFilter->hasTypeRange() && !aFilter->passType(candidate->type())) {
797 if (!aFilter->pass(candidate)) {
807 // Unable to match the filter with this range - try the next range.
808 range = global_identIndex.equal_range(range.second->first);
811 return NULL; // Reached the end of the valid sequence with no match.
815 FGPositioned::sortByRange(List& aResult, const SGGeod& aPos)
817 validateSGGeod(aPos);
819 SGVec3d cartPos(SGVec3d::fromGeod(aPos));
820 // computer ordering values
821 Octree::FindNearestResults r;
822 List::iterator it = aResult.begin(), lend = aResult.end();
823 for (; it != lend; ++it) {
824 double d2 = distSqr((*it)->cart(), cartPos);
825 r.push_back(Octree::OrderedPositioned(*it, d2));
829 std::sort(r.begin(), r.end());
831 // convert to a plain list
832 unsigned int count = aResult.size();
833 for (unsigned int i=0; i<count; ++i) {
834 aResult[i] = r[i].get();
838 FGPositioned::TypeFilter::TypeFilter(Type aTy)
843 void FGPositioned::TypeFilter::addType(Type aTy)
845 if (aTy == INVALID) {
850 types.push_back(aTy);
854 FGPositioned::TypeFilter::pass(FGPositioned* aPos) const
860 std::vector<Type>::const_iterator it = types.begin(),
862 for (; it != end; ++it) {
863 return aPos->type() == *it;