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.
31 #include <simgear/math/sg_geodesy.hxx>
33 #include "positioned.hxx"
35 typedef std::multimap<std::string, FGPositioned*> NamedPositionedIndex;
36 typedef std::pair<NamedPositionedIndex::const_iterator, NamedPositionedIndex::const_iterator> NamedIndexRange;
39 * Order positioned elements by type, then pointer address. This allows us to
40 * use range searches (lower_ and upper_bound) to grab items of a particular
41 * type out of bucket efficently.
46 bool operator()(const FGPositioned* a, const FGPositioned* b) const
48 if (a->type() == b->type()) return a < b;
49 return a->type() < b->type();
53 typedef std::set<FGPositioned*, OrderByType> BucketEntry;
54 typedef std::map<long int, BucketEntry> SpatialPositionedIndex;
56 static NamedPositionedIndex global_namedIndex;
57 static SpatialPositionedIndex global_spatialIndex;
59 SpatialPositionedIndex::iterator
60 bucketEntryForPositioned(FGPositioned* aPos)
62 int bucketIndex = aPos->bucket().gen_index();
63 SpatialPositionedIndex::iterator it = global_spatialIndex.find(bucketIndex);
64 if (it != global_spatialIndex.end()) {
68 // create a new BucketEntry
69 return global_spatialIndex.insert(it, std::make_pair(bucketIndex, BucketEntry()));
73 addToIndices(FGPositioned* aPos)
76 if (!aPos->ident().empty()) {
77 global_namedIndex.insert(global_namedIndex.begin(),
78 std::make_pair(aPos->ident(), aPos));
81 SpatialPositionedIndex::iterator it = bucketEntryForPositioned(aPos);
82 it->second.insert(aPos);
86 removeFromIndices(FGPositioned* aPos)
90 if (!aPos->ident().empty()) {
91 NamedPositionedIndex::iterator it = global_namedIndex.find(aPos->ident());
92 while (it != global_namedIndex.end() && (it->first == aPos->ident())) {
93 if (it->second == aPos) {
94 global_namedIndex.erase(it);
102 SpatialPositionedIndex::iterator sit = bucketEntryForPositioned(aPos);
103 sit->second.erase(aPos);
107 spatialFilterInBucket(const SGBucket& aBucket, FGPositioned::Filter* aFilter, FGPositioned::List& aResult)
109 SpatialPositionedIndex::const_iterator it;
110 it = global_spatialIndex.find(aBucket.gen_index());
111 if (it == global_spatialIndex.end()) {
115 BucketEntry::const_iterator l = it->second.begin();
116 BucketEntry::const_iterator u = it->second.end();
118 if (!aFilter) { // pass everything
119 aResult.insert(aResult.end(), l, u);
123 for ( ; l != u; ++l) {
124 if ((*aFilter)(*l)) {
125 aResult.push_back(*l);
131 spatialFind(const SGGeod& aPos, double aRange,
132 FGPositioned::Filter* aFilter, FGPositioned::List& aResult)
135 double lat = aPos.getLatitudeDeg(),
136 lon = aPos.getLongitudeDeg();
138 int bx = (int)( aRange*SG_NM_TO_METER / buck.get_width_m() / 2);
139 int by = (int)( aRange*SG_NM_TO_METER / buck.get_height_m() / 2 );
141 // loop over bucket range
142 for ( int i=-bx; i<=bx; i++) {
143 for ( int j=-by; j<=by; j++) {
144 spatialFilterInBucket(sgBucketOffset(lon, lat, i, j), aFilter, aResult);
150 class LowerLimitOfType
153 bool operator()(const FGPositioned* a, const FGPositioned::Type b) const
155 return a->type() < b;
158 bool operator()(const FGPositioned::Type a, const FGPositioned* b) const
160 return a < b->type();
166 spatialFindTyped(const SGGeod& aPos, double aRange, FGPositioned::Type aLower, FGPositioned::Type aUpper, FGPositioned::List& aResult)
169 double lat = aPos.getLatitudeDeg(),
170 lon = aPos.getLongitudeDeg();
172 int bx = (int)( aRange*SG_NM_TO_METER / buck.get_width_m() / 2);
173 int by = (int)( aRange*SG_NM_TO_METER / buck.get_height_m() / 2 );
175 // loop over bucket range
176 for ( int i=-bx; i<=bx; i++) {
177 for ( int j=-by; j<=by; j++) {
178 buck = sgBucketOffset(lon, lat, i, j);
180 SpatialPositionedIndex::const_iterator it;
181 it = global_spatialIndex.find(buck.gen_index());
182 if (it == global_spatialIndex.end()) {
186 BucketEntry::const_iterator l = std::lower_bound(it->second.begin(), it->second.end(), aLower, LowerLimitOfType());
187 BucketEntry::const_iterator u = std::upper_bound(l, it->second.end(), aUpper, LowerLimitOfType());
189 for ( ; l != u; ++l) {
190 aResult.push_back(*l);
200 class RangePredictate
203 RangePredictate(const SGGeod& aOrigin, double aRange) :
204 mOrigin(SGVec3d::fromGeod(aOrigin)),
205 mRangeSqr(aRange * aRange)
208 bool operator()(const FGPositionedRef& aPos)
210 double dSqr = distSqr(aPos->cart(), mOrigin);
211 return (dSqr > mRangeSqr);
220 filterListByRange(const SGGeod& aPos, double aRange, FGPositioned::List& aResult)
222 RangePredictate pred(aPos, aRange * SG_NM_TO_METER);
223 FGPositioned::List::iterator newEnd;
224 newEnd = std::remove_if(aResult.begin(), aResult.end(), pred);
225 aResult.erase(newEnd, aResult.end());
228 class DistanceOrdering
231 DistanceOrdering(const SGGeod& aPos) :
232 mPos(SGVec3d::fromGeod(aPos))
235 bool operator()(const FGPositionedRef& a, const FGPositionedRef& b) const
237 double dA = distSqr(a->cart(), mPos),
238 dB = distSqr(b->cart(), mPos);
247 sortByDistance(const SGGeod& aPos, FGPositioned::List& aResult)
249 std::sort(aResult.begin(), aResult.end(), DistanceOrdering(aPos));
252 static FGPositionedRef
253 namedFindClosest(const std::string& aIdent, const SGGeod& aOrigin, FGPositioned::Filter* aFilter)
255 NamedIndexRange range = global_namedIndex.equal_range(aIdent);
256 if (range.first == range.second) {
260 // common case, only one result. looks a bit ugly because these are
261 // sequential iterators, not random-access ones
262 NamedPositionedIndex::const_iterator check = range.first;
263 if (++check == range.second) {
264 // excellent, only one match in the range - all we care about is the type
265 if (aFilter && !aFilter->pass(range.first->second)) {
266 return NULL; // type check failed
269 return range.first->second;
270 } // of short-circuit logic for single-element range
272 // multiple matches, we need to actually check the distance to each one
273 double minDist = HUGE_VAL;
274 FGPositionedRef result;
275 NamedPositionedIndex::const_iterator it = range.first;
276 SGVec3d cartOrigin(SGVec3d::fromGeod(aOrigin));
278 for (; it != range.second; ++it) {
279 if (aFilter && !aFilter->pass(range.first->second)) {
284 double d2 = distSqr(cartOrigin, it->second->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 ///////////////////////////////////////////////////////////////////////////////
341 FGPositioned::FGPositioned(Type ty, const std::string& aIdent, const SGGeod& aPos, bool aIndexed) :
346 SGReferenced::get(this); // hold an owning ref, for the moment
349 assert(ty != TAXIWAY);
354 FGPositioned::~FGPositioned()
356 //std::cout << "destroying:" << mIdent << "/" << nameForType(mType) << std::endl;
357 removeFromIndices(this);
361 FGPositioned::bucket() const
363 return SGBucket(mPosition);
367 FGPositioned::cart() const
369 return SGVec3d::fromGeod(mPosition);
372 const char* FGPositioned::nameForType(Type aTy)
375 case RUNWAY: return "runway";
376 case TAXIWAY: return "taxiway";
377 case PARK_STAND: return "parking stand";
378 case FIX: return "fix";
379 case VOR: return "VOR";
380 case NDB: return "NDB";
381 case ILS: return "ILS";
382 case LOC: return "localiser";
383 case GS: return "glideslope";
384 case OM: return "outer-marker";
385 case MM: return "middle-marker";
386 case IM: return "inner-marker";
387 case AIRPORT: return "airport";
388 case HELIPORT: return "heliport";
389 case SEAPORT: return "seaport";
390 case WAYPOINT: return "waypoint";
391 case DME: return "dme";
392 case TACAN: return "tacan";
398 ///////////////////////////////////////////////////////////////////////////////
399 // search / query functions
402 FGPositioned::findClosestWithIdent(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
404 return namedFindClosest(aIdent, aPos, aFilter);
408 FGPositioned::findWithinRange(const SGGeod& aPos, double aRangeNm, Filter* aFilter)
411 spatialFind(aPos, aRangeNm, aFilter, result);
412 filterListByRange(aPos, aRangeNm, result);
417 FGPositioned::findAllWithIdentSortedByRange(const std::string& aIdent, const SGGeod& aPos, Filter* aFilter)
420 NamedIndexRange range = global_namedIndex.equal_range(aIdent);
421 for (; range.first != range.second; ++range.first) {
422 if (aFilter && !aFilter->pass(range.first->second)) {
426 result.push_back(range.first->second);
429 sortByDistance(aPos, result);
434 FGPositioned::findClosest(const SGGeod& aPos, double aCutoffNm, Filter* aFilter)
436 FGPositioned::List l(spatialGetClosest(aPos, 1, aCutoffNm, aFilter));
441 assert(l.size() == 1);
446 FGPositioned::findClosestN(const SGGeod& aPos, unsigned int aN, double aCutoffNm, Filter* aFilter)
448 return spatialGetClosest(aPos, aN, aCutoffNm, aFilter);
452 FGPositioned::findNextWithPartialId(FGPositionedRef aCur, const std::string& aId, Filter* aFilter)
454 NamedIndexRange range = global_namedIndex.equal_range(aId);
455 for (; range.first != range.second; ++range.first) {
456 FGPositionedRef candidate = range.first->second;
457 if (aCur == candidate) {
458 aCur = NULL; // found our start point, next match will pass
462 if (aFilter && !aFilter->pass(candidate)) {
471 return NULL; // fell out, no match in range