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.
29 #include <simgear/math/sg_geodesy.hxx>
31 #include "positioned.hxx"
33 typedef std::multimap<std::string, FGPositioned*> NamedPositionedIndex;
34 typedef std::pair<NamedPositionedIndex::const_iterator, NamedPositionedIndex::const_iterator> NamedIndexRange;
37 * Order positioned elements by type, then pointer address. This allows us to
38 * use range searches (lower_ and upper_bound) to grab items of a particular
39 * type out of bucket efficently.
44 bool operator()(const FGPositioned* a, const FGPositioned* b) const
46 if (a->type() == b->type()) return a < b;
47 return a->type() < b->type();
51 typedef std::set<FGPositioned*, OrderByType> BucketEntry;
52 typedef std::map<long int, BucketEntry> SpatialPositionedIndex;
54 static NamedPositionedIndex global_namedIndex;
55 static SpatialPositionedIndex global_spatialIndex;
57 SpatialPositionedIndex::iterator
58 bucketEntryForPositioned(FGPositioned* aPos)
60 int bucketIndex = aPos->bucket().gen_index();
61 SpatialPositionedIndex::iterator it = global_spatialIndex.find(bucketIndex);
62 if (it != global_spatialIndex.end()) {
66 // create a new BucketEntry
67 return global_spatialIndex.insert(it, std::make_pair(bucketIndex, BucketEntry()));
71 addToIndices(FGPositioned* aPos)
74 global_namedIndex.insert(global_namedIndex.begin(),
75 std::make_pair(aPos->ident(), aPos));
77 SpatialPositionedIndex::iterator it = bucketEntryForPositioned(aPos);
78 it->second.insert(aPos);
82 removeFromIndices(FGPositioned* aPos)
86 NamedPositionedIndex::iterator it = global_namedIndex.find(aPos->ident());
87 while (it != global_namedIndex.end() && (it->first == aPos->ident())) {
88 if (it->second == aPos) {
89 global_namedIndex.erase(it);
96 SpatialPositionedIndex::iterator sit = bucketEntryForPositioned(aPos);
97 sit->second.erase(aPos);
101 spatialFilterInBucket(const SGBucket& aBucket, const FGPositioned::Filter& aFilter, FGPositioned::List& aResult)
103 SpatialPositionedIndex::const_iterator it;
104 it = global_spatialIndex.find(aBucket.gen_index());
105 if (it == global_spatialIndex.end()) {
109 BucketEntry::const_iterator l = it->second.begin();
110 BucketEntry::const_iterator u = it->second.end();
112 for ( ; l != u; ++l) {
114 aResult.push_back(*l);
120 spatialFind(const SGGeod& aPos, double aRange,
121 const FGPositioned::Filter& aFilter, FGPositioned::List& aResult)
124 double lat = aPos.getLatitudeDeg(),
125 lon = aPos.getLongitudeDeg();
127 int bx = (int)( aRange*SG_NM_TO_METER / buck.get_width_m() / 2);
128 int by = (int)( aRange*SG_NM_TO_METER / buck.get_height_m() / 2 );
130 // loop over bucket range
131 for ( int i=-bx; i<=bx; i++) {
132 for ( int j=-by; j<=by; j++) {
133 spatialFilterInBucket(sgBucketOffset(lon, lat, i, j), aFilter, aResult);
138 class LowerLimitOfType
141 bool operator()(const FGPositioned* a, const FGPositioned::Type b) const
143 return a->type() < b;
146 bool operator()(const FGPositioned::Type a, const FGPositioned* b) const
148 return a < b->type();
153 spatialFindTyped(const SGGeod& aPos, double aRange, FGPositioned::Type aLower, FGPositioned::Type aUpper, FGPositioned::List& aResult)
156 double lat = aPos.getLatitudeDeg(),
157 lon = aPos.getLongitudeDeg();
159 int bx = (int)( aRange*SG_NM_TO_METER / buck.get_width_m() / 2);
160 int by = (int)( aRange*SG_NM_TO_METER / buck.get_height_m() / 2 );
162 // loop over bucket range
163 for ( int i=-bx; i<=bx; i++) {
164 for ( int j=-by; j<=by; j++) {
165 buck = sgBucketOffset(lon, lat, i, j);
167 SpatialPositionedIndex::const_iterator it;
168 it = global_spatialIndex.find(buck.gen_index());
169 if (it == global_spatialIndex.end()) {
173 BucketEntry::const_iterator l = std::lower_bound(it->second.begin(), it->second.end(), aLower, LowerLimitOfType());
174 BucketEntry::const_iterator u = std::upper_bound(l, it->second.end(), aUpper, LowerLimitOfType());
176 for ( ; l != u; ++l) {
177 aResult.push_back(*l);
185 * Cartesian range predicate. Note that for really long ranges, might need to
186 * to use geodetic / geocentric distance instead
188 class RangePredictate
191 RangePredictate(const Point3D& aOrigin, double aRange) :
193 mRangeSquared(aRange * aRange)
196 bool operator()(const FGPositionedRef& aPos)
198 Point3D p(Point3D::fromSGGeod(aPos->geod()));
199 bool ok = (mOrigin.distance3Dsquared(p) > mRangeSquared);
201 double x = sqrt(mOrigin.distance3Dsquared(p) - mRangeSquared);
203 //std::cout << "pos:" << aPos->ident() << " failed range check by " << x << std::endl;
210 double mRangeSquared;
214 filterListByRange(const SGGeod& aPos, double aRange, FGPositioned::List& aResult)
216 RangePredictate pred(Point3D::fromSGGeod(aPos), aRange * SG_NM_TO_METER);
217 FGPositioned::List::iterator newEnd;
218 newEnd = std::remove_if(aResult.begin(), aResult.end(), pred);
219 aResult.erase(newEnd, aResult.end());
222 class DistanceOrdering
225 DistanceOrdering(const SGGeod& aPos) :
226 mPos(Point3D::fromSGGeod(aPos))
229 bool operator()(const FGPositionedRef& a, const FGPositionedRef& b) const
231 return mPos.distance3Dsquared(Point3D::fromSGGeod(a->geod())) <
232 mPos.distance3Dsquared(Point3D::fromSGGeod(b->geod()));
240 sortByDistance(const SGGeod& aPos, FGPositioned::List& aResult)
242 std::sort(aResult.begin(), aResult.end(), DistanceOrdering(aPos));
245 static FGPositionedRef
246 namedFindClosestTyped(const std::string& aIdent, const SGGeod& aOrigin,
247 FGPositioned::Type aLower, FGPositioned::Type aUpper)
249 NamedIndexRange range = global_namedIndex.equal_range(aIdent);
250 if (range.first == range.second) return NULL;
252 // common case, only one result. looks a bit ugly because these are
253 // sequential iterators, not random-access ones
254 NamedPositionedIndex::const_iterator check = range.first;
255 if (++check == range.second) {
256 // excellent, only one match in the range - all we care about is the type
257 FGPositioned::Type ty = range.first->second->type();
258 if ((ty < aLower) || (ty > aUpper)) {
259 return NULL; // type check failed
262 return range.first->second;
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 Point3D origin(Point3D::fromSGGeod(aOrigin));
270 for (; range.first != range.second; ++range.first) {
272 FGPositioned::Type ty = range.first->second->type();
273 if ((ty < aLower) || (ty > aUpper)) {
278 Point3D p(Point3D::fromSGGeod(range.first->second->geod()));
279 double ds = origin.distance3Dsquared(p);
282 result = range.first->second;
289 static FGPositioned::List
290 spatialGetClosest(const SGGeod& aPos, unsigned int aN, double aCutoffNm, const FGPositioned::Filter& aFilter)
292 FGPositioned::List result;
293 int radius = 1; // start at 1, radius 0 is handled explicitly
295 double lat = aPos.getLatitudeDeg(),
296 lon = aPos.getLongitudeDeg();
297 // final cutoff is in metres, and scaled to account for testing the corners
298 // of the 'box' instead of the centre of each edge
299 double cutoffM = aCutoffNm * SG_NM_TO_METER * 1.5;
301 // base case, simplifes loop to do it seperately here
302 spatialFilterInBucket(sgBucketOffset(lon, lat, 0, 0), aFilter, result);
304 for (;result.size() < aN; ++radius) {
306 double az1, az2, d1, d2;
307 SGGeodesy::inverse(aPos, sgBucketOffset(lon, lat, -radius, -radius).get_center(), az1, az2, d1);
308 SGGeodesy::inverse(aPos, sgBucketOffset(lon, lat, radius, radius).get_center(), az1, az2, d2);
310 if ((d1 > cutoffM) && (d2 > cutoffM)) {
311 //std::cerr << "spatialGetClosest terminating due to range cutoff" << std::endl;
315 FGPositioned::List hits;
316 for ( int i=-radius; i<=radius; i++) {
317 spatialFilterInBucket(sgBucketOffset(lon, lat, i, -radius), aFilter, hits);
318 spatialFilterInBucket(sgBucketOffset(lon, lat, -radius, i), aFilter, hits);
319 spatialFilterInBucket(sgBucketOffset(lon, lat, i, radius), aFilter, hits);
320 spatialFilterInBucket(sgBucketOffset(lon, lat, radius, i), aFilter, hits);
323 result.insert(result.end(), hits.begin(), hits.end()); // append
326 if (result.size() > aN) {
327 result.resize(aN); // truncate at requested number of matches
330 sortByDistance(aPos, result);
334 ///////////////////////////////////////////////////////////////////////////////
336 FGPositioned::FGPositioned() :
341 FGPositioned::FGPositioned(Type ty, const std::string& aIdent, double aLat, double aLon, double aElev) :
344 mPosition(SGGeod::fromDegFt(aLon, aLat, aElev))
346 //addToIndices(this);
347 //SGReferenced::get(this); // hold an owning ref, for the moment
350 FGPositioned::FGPositioned(Type ty, const std::string& aIdent, const SGGeod& aPos) :
355 //addToIndices(this);
356 //SGReferenced::get(this); // hold an owning ref, for the moment
359 FGPositioned::~FGPositioned()
361 //std::cout << "~FGPositioned:" << mIdent << std::endl;
362 //removeFromIndices(this);
366 FGPositioned::bucket() const
368 return SGBucket(mPosition);
371 const char* FGPositioned::nameForType(Type aTy)
374 case FIX: return "fix";
375 case VOR: return "VOR";
376 case NDB: return "NDB";
377 case OM: return "outer-marker";
378 case MM: return "middle-marker";
379 case IM: return "inner-marker";
380 case AIRPORT: return "airport";
381 case HELIPORT: return "heliport";
382 case SEAPORT: return "seaport";
383 case WAYPOINT: return "waypoint";
389 ///////////////////////////////////////////////////////////////////////////////
390 // search / query functions
393 FGPositioned::findClosestWithIdent(const std::string& aIdent, double aLat, double aLon)
395 return findClosestWithIdent(aIdent, SGGeod::fromDeg(aLon, aLat));
399 FGPositioned::findClosestWithIdent(const std::string& aIdent, const SGGeod& aPos)
401 return namedFindClosestTyped(aIdent, aPos, INVALID, LAST_TYPE);
405 FGPositioned::findWithinRangeByType(const SGGeod& aPos, double aRangeNm, Type aTy)
408 spatialFindTyped(aPos, aRangeNm, aTy, aTy, result);
409 filterListByRange(aPos, aRangeNm, result);
414 FGPositioned::findWithinRange(const SGGeod& aPos, double aRangeNm, const Filter& aFilter)
417 spatialFind(aPos, aRangeNm, aFilter, result);
418 filterListByRange(aPos, aRangeNm, result);
423 FGPositioned::findAllWithIdent(const std::string& aIdent)
426 NamedIndexRange range = global_namedIndex.equal_range(aIdent);
427 for (; range.first != range.second; ++range.first) {
428 result.push_back(range.first->second);
435 FGPositioned::findClosestN(const SGGeod& aPos, unsigned int aN, double aCutoffNm, const Filter& aFilter)
437 return spatialGetClosest(aPos, aN, aCutoffNm, aFilter);