]> git.mxchange.org Git - flightgear.git/blob - src/Airports/airport.cxx
MapWidget: silence compiler warning
[flightgear.git] / src / Airports / airport.cxx
1 //
2 // simple.cxx -- a really simplistic class to manage airport ID,
3 //               lat, lon of the center of one of it's runways, and
4 //               elevation in feet.
5 //
6 // Written by Curtis Olson, started April 1998.
7 // Updated by Durk Talsma, started December, 2004.
8 //
9 // Copyright (C) 1998  Curtis L. Olson  - http://www.flightgear.org/~curt
10 //
11 // This program is free software; you can redistribute it and/or
12 // modify it under the terms of the GNU General Public License as
13 // published by the Free Software Foundation; either version 2 of the
14 // License, or (at your option) any later version.
15 //
16 // This program is distributed in the hope that it will be useful, but
17 // WITHOUT ANY WARRANTY; without even the implied warranty of
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19 // General Public License for more details.
20 //
21 // You should have received a copy of the GNU General Public License
22 // along with this program; if not, write to the Free Software
23 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
24 //
25 // $Id$
26
27 #ifdef HAVE_CONFIG_H
28 #  include <config.h>
29 #endif
30
31 #include "airport.hxx"
32
33 #include <algorithm>
34 #include <cassert>
35 #include <boost/foreach.hpp>
36
37 #include <simgear/misc/sg_path.hxx>
38 #include <simgear/props/props.hxx>
39 #include <simgear/props/props_io.hxx>
40 #include <simgear/debug/logstream.hxx>
41 #include <simgear/sg_inlines.h>
42 #include <simgear/structure/exception.hxx>
43
44 #include <Environment/environment_mgr.hxx>
45 #include <Environment/environment.hxx>
46 #include <Main/fg_props.hxx>
47 #include <Airports/runways.hxx>
48 #include <Airports/pavement.hxx>
49 #include <Airports/dynamics.hxx>
50 #include <Airports/xmlloader.hxx>
51 #include <Navaids/procedure.hxx>
52 #include <Navaids/waypoint.hxx>
53 #include <ATC/CommStation.hxx>
54 #include <Navaids/NavDataCache.hxx>
55
56 using std::vector;
57 using std::pair;
58
59 using namespace flightgear;
60
61 /***************************************************************************
62  * FGAirport
63  ***************************************************************************/
64
65 AirportCache FGAirport::airportCache;
66
67 FGAirport::FGAirport( PositionedID aGuid,
68                       const std::string &id,
69                       const SGGeod& location,
70                       const std::string &name,
71                       bool has_metar,
72                       Type aType ):
73     FGPositioned(aGuid, aType, id, location),
74     _name(name),
75     _has_metar(has_metar),
76     _dynamics(0),
77     mTowerDataLoaded(false),
78     mRunwaysLoaded(false),
79     mHelipadsLoaded(false),
80     mTaxiwaysLoaded(false),
81     mProceduresLoaded(false),
82     mILSDataLoaded(false)
83 {
84 }
85
86
87 FGAirport::~FGAirport()
88 {
89     delete _dynamics;
90 }
91
92 bool FGAirport::isAirport() const
93 {
94   return type() == AIRPORT;
95 }
96
97 bool FGAirport::isSeaport() const
98 {
99   return type() == SEAPORT;
100 }
101
102 bool FGAirport::isHeliport() const
103 {
104   return type() == HELIPORT;
105 }
106
107 bool FGAirport::isAirportType(FGPositioned* pos)
108 {
109     if (!pos) {
110         return false;
111     }
112     
113     return (pos->type() >= AIRPORT) && (pos->type() <= SEAPORT);
114 }
115
116 FGAirportDynamics * FGAirport::getDynamics()
117 {
118     if (_dynamics) {
119         return _dynamics;
120     }
121     
122     _dynamics = new FGAirportDynamics(this);
123     XMLLoader::load(_dynamics);
124     _dynamics->init();
125   
126     FGRunwayPreference rwyPrefs(this);
127     XMLLoader::load(&rwyPrefs);
128     _dynamics->setRwyUse(rwyPrefs);
129     
130     return _dynamics;
131 }
132
133 //------------------------------------------------------------------------------
134 unsigned int FGAirport::numRunways() const
135 {
136   loadRunways();
137   return mRunways.size();
138 }
139
140 //------------------------------------------------------------------------------
141 unsigned int FGAirport::numHelipads() const
142 {
143   loadHelipads();
144   return mHelipads.size();
145 }
146
147 //------------------------------------------------------------------------------
148 FGRunwayRef FGAirport::getRunwayByIndex(unsigned int aIndex) const
149 {
150   loadRunways();
151   return loadById<FGRunway>(mRunways, aIndex);
152 }
153
154 //------------------------------------------------------------------------------
155 FGHelipadRef FGAirport::getHelipadByIndex(unsigned int aIndex) const
156 {
157   loadHelipads();
158   return loadById<FGHelipad>(mHelipads, aIndex);
159 }
160
161 //------------------------------------------------------------------------------
162 FGRunwayMap FGAirport::getRunwayMap() const
163 {
164   loadRunways();
165   FGRunwayMap map;
166
167   double minLengthFt = fgGetDouble("/sim/navdb/min-runway-length-ft");
168
169   BOOST_FOREACH(PositionedID id, mRunways)
170   {
171     FGRunway* rwy = loadById<FGRunway>(id);
172
173     // ignore unusably short runways
174     // TODO other methods don't check this...
175     if( rwy->lengthFt() >= minLengthFt )
176       map[ rwy->ident() ] = rwy;
177   }
178
179   return map;
180 }
181
182 //------------------------------------------------------------------------------
183 FGHelipadMap FGAirport::getHelipadMap() const
184 {
185   loadHelipads();
186   FGHelipadMap map;
187
188   BOOST_FOREACH(PositionedID id, mHelipads)
189   {
190     FGHelipad* rwy = loadById<FGHelipad>(id);
191     map[ rwy->ident() ] = rwy;
192   }
193
194   return map;
195 }
196
197 //------------------------------------------------------------------------------
198 bool FGAirport::hasRunwayWithIdent(const std::string& aIdent) const
199 {
200   return flightgear::NavDataCache::instance()
201     ->airportItemWithIdent(guid(), FGPositioned::RUNWAY, aIdent) != 0;
202 }
203
204 //------------------------------------------------------------------------------
205 bool FGAirport::hasHelipadWithIdent(const std::string& aIdent) const
206 {
207   return flightgear::NavDataCache::instance()
208     ->airportItemWithIdent(guid(), FGPositioned::HELIPAD, aIdent) != 0;
209 }
210
211 //------------------------------------------------------------------------------
212 FGRunwayRef FGAirport::getRunwayByIdent(const std::string& aIdent) const
213 {
214   PositionedID id =
215     flightgear::NavDataCache::instance()
216       ->airportItemWithIdent(guid(), FGPositioned::RUNWAY, aIdent);
217
218   if (id == 0) {
219     SG_LOG(SG_GENERAL, SG_ALERT, "no such runway '" << aIdent << "' at airport " << ident());
220     throw sg_range_exception("unknown runway " + aIdent + " at airport:" + ident(), "FGAirport::getRunwayByIdent");
221   }
222   
223   return loadById<FGRunway>(id);
224 }
225
226 //------------------------------------------------------------------------------
227 FGHelipadRef FGAirport::getHelipadByIdent(const std::string& aIdent) const
228 {
229   PositionedID id = flightgear::NavDataCache::instance()->airportItemWithIdent(guid(), FGPositioned::HELIPAD, aIdent);
230   if (id == 0) {
231     SG_LOG(SG_GENERAL, SG_ALERT, "no such helipad '" << aIdent << "' at airport " << ident());
232     throw sg_range_exception("unknown helipad " + aIdent + " at airport:" + ident(), "FGAirport::getRunwayByIdent");
233   }
234
235   return loadById<FGHelipad>(id);
236 }
237
238 //------------------------------------------------------------------------------
239 FGRunwayRef FGAirport::findBestRunwayForHeading(double aHeading) const
240 {
241   loadRunways();
242   
243   FGRunway* result = NULL;
244   double currentBestQuality = 0.0;
245   
246   SGPropertyNode *param = fgGetNode("/sim/airport/runways/search", true);
247   double lengthWeight = param->getDoubleValue("length-weight", 0.01);
248   double widthWeight = param->getDoubleValue("width-weight", 0.01);
249   double surfaceWeight = param->getDoubleValue("surface-weight", 10);
250   double deviationWeight = param->getDoubleValue("deviation-weight", 1);
251     
252   BOOST_FOREACH(PositionedID id, mRunways) {
253     FGRunway* rwy = loadById<FGRunway>(id);
254     // bug http://code.google.com/p/flightgear-bugs/issues/detail?id=1149
255     // (and probably some other issues besides). 
256     if (rwy->type() == FGPositioned::HELIPAD) {
257       continue;
258     }
259       
260     double good = rwy->score(lengthWeight, widthWeight, surfaceWeight);
261     double dev = aHeading - rwy->headingDeg();
262     SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
263     double bad = fabs(deviationWeight * dev) + 1e-20;
264     double quality = good / bad;
265     
266     if (quality > currentBestQuality) {
267       currentBestQuality = quality;
268       result = rwy;
269     }
270   }
271
272   return result;
273 }
274
275 //------------------------------------------------------------------------------
276 FGRunwayRef FGAirport::findBestRunwayForPos(const SGGeod& aPos) const
277 {
278   loadRunways();
279   
280   FGRunway* result = NULL;
281   double currentLowestDev = 180.0;
282   
283   BOOST_FOREACH(PositionedID id, mRunways) {
284     FGRunway* rwy = loadById<FGRunway>(id);
285
286     double inboundCourse = SGGeodesy::courseDeg(aPos, rwy->end());
287     double dev = inboundCourse - rwy->headingDeg();
288     SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
289
290     dev = fabs(dev);
291     if (dev < currentLowestDev) { // new best match
292       currentLowestDev = dev;
293       result = rwy;
294     }
295   } // of runway iteration
296   
297   return result;
298
299 }
300
301 //------------------------------------------------------------------------------
302 bool FGAirport::hasHardRunwayOfLengthFt(double aLengthFt) const
303 {
304   loadRunways();
305   
306   BOOST_FOREACH(PositionedID id, mRunways) {
307     FGRunway* rwy = loadById<FGRunway>(id);
308     if (rwy->isHardSurface() && (rwy->lengthFt() >= aLengthFt)) {
309       return true; // we're done!
310     }
311   } // of runways iteration
312
313   return false;
314 }
315
316 //------------------------------------------------------------------------------
317 FGRunwayList FGAirport::getRunwaysWithoutReciprocals() const
318 {
319   loadRunways();
320   
321   FGRunwayList r;
322   
323   BOOST_FOREACH(PositionedID id, mRunways) {
324     FGRunway* rwy = loadById<FGRunway>(id);
325     FGRunway* recip = rwy->reciprocalRunway();
326     if (recip) {
327       FGRunwayList::iterator it = std::find(r.begin(), r.end(), recip);
328       if (it != r.end()) {
329         continue; // reciprocal already in result set, don't include us
330       }
331     }
332     
333     r.push_back(rwy);
334   }
335   
336   return r;
337 }
338
339 //------------------------------------------------------------------------------
340 unsigned int FGAirport::numTaxiways() const
341 {
342   loadTaxiways();
343   return mTaxiways.size();
344 }
345
346 //------------------------------------------------------------------------------
347 FGTaxiwayRef FGAirport::getTaxiwayByIndex(unsigned int aIndex) const
348 {
349   loadTaxiways();
350   return loadById<FGTaxiway>(mTaxiways, aIndex);
351 }
352
353 //------------------------------------------------------------------------------
354 FGTaxiwayList FGAirport::getTaxiways() const
355 {
356   loadTaxiways();
357   return loadAllById<FGTaxiway>(mTaxiways);
358 }
359
360 //------------------------------------------------------------------------------
361 unsigned int FGAirport::numPavements() const
362 {
363   loadTaxiways();
364   return mPavements.size();
365 }
366
367 //------------------------------------------------------------------------------
368 FGPavementRef FGAirport::getPavementByIndex(unsigned int aIndex) const
369 {
370   loadTaxiways();
371   return loadById<FGPavement>(mPavements, aIndex);
372 }
373
374 //------------------------------------------------------------------------------
375 FGPavementList FGAirport::getPavements() const
376 {
377   loadTaxiways();
378   return loadAllById<FGPavement>(mPavements);
379 }
380
381 //------------------------------------------------------------------------------
382 FGRunwayRef FGAirport::getActiveRunwayForUsage() const
383 {
384   FGEnvironmentMgr* envMgr = (FGEnvironmentMgr *) globals->get_subsystem("environment");
385   
386   // This forces West-facing rwys to be used in no-wind situations
387   // which is consistent with Flightgear's initial setup.
388   double hdg = 270;
389   
390   if (envMgr) {
391     FGEnvironment stationWeather(envMgr->getEnvironment(mPosition));
392   
393     double windSpeed = stationWeather.get_wind_speed_kt();
394     if (windSpeed > 0.0) {
395       hdg = stationWeather.get_wind_from_heading_deg();
396     }
397   }
398   
399   return findBestRunwayForHeading(hdg);
400 }
401
402 //------------------------------------------------------------------------------
403 FGAirportRef FGAirport::findClosest( const SGGeod& aPos,
404                                      double aCuttofNm,
405                                      Filter* filter )
406 {
407   AirportFilter aptFilter;
408   if( !filter )
409     filter = &aptFilter;
410   
411   return static_pointer_cast<FGAirport>
412   (
413     FGPositioned::findClosest(aPos, aCuttofNm, filter)
414   );
415 }
416
417 FGAirport::HardSurfaceFilter::HardSurfaceFilter(double minLengthFt) :
418   mMinLengthFt(minLengthFt)
419 {
420   if (minLengthFt < 0.0) {
421     mMinLengthFt = fgGetDouble("/sim/navdb/min-runway-length-ft", 0.0);
422   }
423 }
424
425 bool FGAirport::HardSurfaceFilter::passAirport(FGAirport* aApt) const
426 {
427   return aApt->hasHardRunwayOfLengthFt(mMinLengthFt);
428 }
429
430 //------------------------------------------------------------------------------
431 FGAirport::TypeRunwayFilter::TypeRunwayFilter():
432   _type(FGPositioned::AIRPORT),
433   _min_runway_length_ft( fgGetDouble("/sim/navdb/min-runway-length-ft", 0.0) )
434 {
435
436 }
437
438 //------------------------------------------------------------------------------
439 bool FGAirport::TypeRunwayFilter::fromTypeString(const std::string& type)
440 {
441   if(      type == "heliport" ) _type = FGPositioned::HELIPORT;
442   else if( type == "seaport"  ) _type = FGPositioned::SEAPORT;
443   else if( type == "airport"  ) _type = FGPositioned::AIRPORT;
444   else                          return false;
445
446   return true;
447 }
448
449 //------------------------------------------------------------------------------
450 bool FGAirport::TypeRunwayFilter::pass(FGPositioned* pos) const
451 {
452   FGAirport* apt = static_cast<FGAirport*>(pos);
453   if(  (apt->type() == FGPositioned::AIRPORT)
454     && !apt->hasHardRunwayOfLengthFt(_min_runway_length_ft)
455     )
456     return false;
457
458   return true;
459 }
460
461 //------------------------------------------------------------------------------
462 FGAirportRef FGAirport::findByIdent(const std::string& aIdent)
463 {
464   AirportCache::iterator it = airportCache.find(aIdent);
465   if (it != airportCache.end())
466    return it->second;
467
468   PortsFilter filter;
469   FGAirportRef r = static_pointer_cast<FGAirport>
470   (
471     FGPositioned::findFirstWithIdent(aIdent, &filter)
472   );
473
474   // add airport to the cache (even when it's NULL, so we don't need to search in vain again)
475   airportCache[aIdent] = r;
476
477   // we don't warn here when r==NULL, let the caller do that
478   return r;
479 }
480
481 //------------------------------------------------------------------------------
482 FGAirportRef FGAirport::getByIdent(const std::string& aIdent)
483 {
484   FGAirportRef r = findByIdent(aIdent);
485   if (!r)
486     throw sg_range_exception("No such airport with ident: " + aIdent);
487   return r;
488 }
489
490 char** FGAirport::searchNamesAndIdents(const std::string& aFilter)
491 {
492   return NavDataCache::instance()->searchAirportNamesAndIdents(aFilter);
493 }
494
495 // find basic airport location info from airport database
496 const FGAirport *fgFindAirportID( const std::string& id)
497 {
498     if ( id.empty() ) {
499         return NULL;
500     }
501     
502     return FGAirport::findByIdent(id);
503 }
504
505 void FGAirport::loadRunways() const
506 {
507   if (mRunwaysLoaded) {
508     return; // already loaded, great
509   }
510   
511   loadSceneryDefinitions();
512   
513   mRunwaysLoaded = true;
514   mRunways = flightgear::NavDataCache::instance()->airportItemsOfType(guid(), FGPositioned::RUNWAY);
515 }
516
517 void FGAirport::loadHelipads() const
518 {
519   if (mHelipadsLoaded) {
520     return; // already loaded, great
521   }
522
523   loadSceneryDefinitions();
524
525   mHelipadsLoaded = true;
526   mHelipads = flightgear::NavDataCache::instance()->airportItemsOfType(guid(), FGPositioned::HELIPAD);
527 }
528
529 void FGAirport::loadTaxiways() const
530 {
531   if (mTaxiwaysLoaded) {
532     return; // already loaded, great
533   }
534   
535   mTaxiwaysLoaded =  true;
536   mTaxiways = flightgear::NavDataCache::instance()->airportItemsOfType(guid(), FGPositioned::TAXIWAY);
537 }
538
539 void FGAirport::loadProcedures() const
540 {
541   if (mProceduresLoaded) {
542     return;
543   }
544   
545   mProceduresLoaded = true;
546   SGPath path;
547   if (!XMLLoader::findAirportData(ident(), "procedures", path)) {
548     SG_LOG(SG_GENERAL, SG_INFO, "no procedures data available for " << ident());
549     return;
550   }
551   
552   SG_LOG(SG_GENERAL, SG_INFO, ident() << ": loading procedures from " << path.str());
553   RouteBase::loadAirportProcedures(path, const_cast<FGAirport*>(this));
554 }
555
556 void FGAirport::loadSceneryDefinitions() const
557 {
558   NavDataCache* cache = NavDataCache::instance();
559     if (cache->isReadOnly()) {
560         return;
561     }
562     
563   SGPath path;
564   if (!XMLLoader::findAirportData(ident(), "threshold", path)) {
565     return; // no XML threshold data
566   }
567   
568   if (!cache->isCachedFileModified(path)) {
569     // cached values are correct, we're all done
570     return;
571   }
572   
573     try {
574         flightgear::NavDataCache::Transaction txn(cache);
575         SGPropertyNode_ptr rootNode = new SGPropertyNode;
576         readProperties(path.str(), rootNode);
577         const_cast<FGAirport*>(this)->readThresholdData(rootNode);
578         cache->stampCacheFile(path);
579         txn.commit();
580     } catch (sg_exception& e) {
581         SG_LOG(SG_NAVAID, SG_WARN, ident() << "loading threshold XML failed:" << e.getFormattedMessage());
582     }
583 }
584
585 void FGAirport::readThresholdData(SGPropertyNode* aRoot)
586 {
587   SGPropertyNode* runway;
588   int runwayIndex = 0;
589   for (; (runway = aRoot->getChild("runway", runwayIndex)) != NULL; ++runwayIndex) {
590     SGPropertyNode* t0 = runway->getChild("threshold", 0),
591       *t1 = runway->getChild("threshold", 1);
592     assert(t0);
593     assert(t1); // too strict? maybe we should finally allow single-ended runways
594     
595     processThreshold(t0);
596     processThreshold(t1);
597   } // of runways iteration
598 }
599
600 void FGAirport::processThreshold(SGPropertyNode* aThreshold)
601 {
602   // first, let's identify the current runway
603   std::string rwyIdent(aThreshold->getStringValue("rwy"));
604   NavDataCache* cache = NavDataCache::instance(); 
605   PositionedID id = cache->airportItemWithIdent(guid(), FGPositioned::RUNWAY, rwyIdent);
606   if (id == 0) {
607     SG_LOG(SG_GENERAL, SG_DEBUG, "FGAirport::processThreshold: "
608            "found runway not defined in the global data:" << ident() << "/" << rwyIdent);
609     return;
610   }
611   
612   double lon = aThreshold->getDoubleValue("lon"),
613   lat = aThreshold->getDoubleValue("lat");
614   SGGeod newThreshold(SGGeod::fromDegM(lon, lat, mPosition.getElevationM()));
615   
616   double newHeading = aThreshold->getDoubleValue("hdg-deg");
617   double newDisplacedThreshold = aThreshold->getDoubleValue("displ-m");
618   double newStopway = aThreshold->getDoubleValue("stopw-m");
619   
620   cache->updateRunwayThreshold(id, newThreshold,
621                                newHeading, newDisplacedThreshold, newStopway);
622 }
623
624 SGGeod FGAirport::getTowerLocation() const
625 {
626   validateTowerData();
627   
628   NavDataCache* cache = NavDataCache::instance();
629   PositionedIDVec towers = cache->airportItemsOfType(guid(), FGPositioned::TOWER);
630   if (towers.empty()) {
631     SG_LOG(SG_GENERAL, SG_ALERT, "No towers defined for:" <<ident());
632     return SGGeod();
633   }
634   
635   FGPositionedRef tower = cache->loadById(towers.front());
636   return tower->geod();
637 }
638
639 void FGAirport::validateTowerData() const
640 {
641   if (mTowerDataLoaded) {
642     return;
643   }
644
645   mTowerDataLoaded = true;
646   NavDataCache* cache = NavDataCache::instance();
647     if (cache->isReadOnly()) {
648         return;
649     }
650     
651   SGPath path;
652   if (!XMLLoader::findAirportData(ident(), "twr", path)) {
653     return; // no XML tower data
654   }
655   
656   if (!cache->isCachedFileModified(path)) {
657   // cached values are correct, we're all done
658     return;
659   }
660
661     try {
662         flightgear::NavDataCache::Transaction txn(cache);
663         SGPropertyNode_ptr rootNode = new SGPropertyNode;
664         readProperties(path.str(), rootNode);
665         const_cast<FGAirport*>(this)->readTowerData(rootNode);
666         cache->stampCacheFile(path);
667         txn.commit();
668     } catch (sg_exception& e){
669         SG_LOG(SG_NAVAID, SG_WARN, ident() << "loading twr XML failed:" << e.getFormattedMessage());
670     }
671 }
672
673 void FGAirport::readTowerData(SGPropertyNode* aRoot)
674 {
675   SGPropertyNode* twrNode = aRoot->getChild("tower")->getChild("twr");
676   double lat = twrNode->getDoubleValue("lat"), 
677     lon = twrNode->getDoubleValue("lon"), 
678     elevM = twrNode->getDoubleValue("elev-m");  
679 // tower elevation is AGL, not AMSL. Since we don't want to depend on the
680 // scenery for a precise terrain elevation, we use the field elevation
681 // (this is also what the apt.dat code does)
682   double fieldElevationM = geod().getElevationM();
683   SGGeod towerLocation(SGGeod::fromDegM(lon, lat, fieldElevationM + elevM));
684   
685   NavDataCache* cache = NavDataCache::instance();
686   PositionedIDVec towers = cache->airportItemsOfType(guid(), FGPositioned::TOWER);
687   if (towers.empty()) {
688     cache->insertTower(guid(), towerLocation);
689   } else {
690     // update the position
691     cache->updatePosition(towers.front(), towerLocation);
692   }
693 }
694
695 bool FGAirport::validateILSData()
696 {
697   if (mILSDataLoaded) {
698     return false;
699   }
700   
701   mILSDataLoaded = true;
702   NavDataCache* cache = NavDataCache::instance();
703     if (cache->isReadOnly()) {
704         return false;
705     }
706     
707   SGPath path;
708   if (!XMLLoader::findAirportData(ident(), "ils", path)) {
709     return false; // no XML tower data
710   }
711   
712   if (!cache->isCachedFileModified(path)) {
713     // cached values are correct, we're all done
714     return false;
715   }
716   
717     try {
718         SGPropertyNode_ptr rootNode = new SGPropertyNode;
719         readProperties(path.str(), rootNode);
720
721         flightgear::NavDataCache::Transaction txn(cache);
722         readILSData(rootNode);
723         cache->stampCacheFile(path);
724         txn.commit();
725 // we loaded data, tell the caller it might need to reload things
726         return true;
727     } catch (sg_exception& e){
728         SG_LOG(SG_NAVAID, SG_WARN, ident() << "loading ils XML failed:" << e.getFormattedMessage());
729     }
730     
731     return false;
732 }
733
734 void FGAirport::readILSData(SGPropertyNode* aRoot)
735 {
736   NavDataCache* cache = NavDataCache::instance();
737   
738   // find the entry matching the runway
739   SGPropertyNode* runwayNode, *ilsNode;
740   for (int i=0; (runwayNode = aRoot->getChild("runway", i)) != NULL; ++i) {
741     for (int j=0; (ilsNode = runwayNode->getChild("ils", j)) != NULL; ++j) {
742       // must match on both nav-ident and runway ident, to support the following:
743       // - runways with multiple distinct ILS installations (KEWD, for example)
744       // - runways where both ends share the same nav ident (LFAT, for example)
745       PositionedID ils = cache->findILS(guid(), ilsNode->getStringValue("rwy"),
746                                         ilsNode->getStringValue("nav-id"));
747       if (ils == 0) {
748         SG_LOG(SG_GENERAL, SG_INFO, "reading ILS data for " << ident() <<
749                ", couldn;t find runway/navaid for:" <<
750                ilsNode->getStringValue("rwy") << "/" <<
751                ilsNode->getStringValue("nav-id"));
752         continue;
753       }
754       
755       double hdgDeg = ilsNode->getDoubleValue("hdg-deg"),
756         lon = ilsNode->getDoubleValue("lon"),
757         lat = ilsNode->getDoubleValue("lat"),
758         elevM = ilsNode->getDoubleValue("elev-m");
759  
760       cache->updateILS(ils, SGGeod::fromDegM(lon, lat, elevM), hdgDeg);
761     } // of ILS iteration
762   } // of runway iteration
763 }
764
765 void FGAirport::addSID(flightgear::SID* aSid)
766 {
767   mSIDs.push_back(aSid);
768 }
769
770 void FGAirport::addSTAR(STAR* aStar)
771 {
772   mSTARs.push_back(aStar);
773 }
774
775 void FGAirport::addApproach(Approach* aApp)
776 {
777   mApproaches.push_back(aApp);
778 }
779
780 //------------------------------------------------------------------------------
781 unsigned int FGAirport::numSIDs() const
782 {
783   loadProcedures();
784   return mSIDs.size();
785 }
786
787 //------------------------------------------------------------------------------
788 flightgear::SID* FGAirport::getSIDByIndex(unsigned int aIndex) const
789 {
790   loadProcedures();
791   return mSIDs[aIndex];
792 }
793
794 //------------------------------------------------------------------------------
795 flightgear::SID* FGAirport::findSIDWithIdent(const std::string& aIdent) const
796 {
797   loadProcedures();
798   for (unsigned int i=0; i<mSIDs.size(); ++i) {
799     if (mSIDs[i]->ident() == aIdent) {
800       return mSIDs[i];
801     }
802   }
803   
804   return NULL;
805 }
806
807 //------------------------------------------------------------------------------
808 flightgear::SIDList FGAirport::getSIDs() const
809 {
810   loadProcedures();
811   return flightgear::SIDList(mSIDs.begin(), mSIDs.end());
812 }
813
814 //------------------------------------------------------------------------------
815 unsigned int FGAirport::numSTARs() const
816 {
817   loadProcedures();
818   return mSTARs.size();
819 }
820
821 //------------------------------------------------------------------------------
822 STAR* FGAirport::getSTARByIndex(unsigned int aIndex) const
823 {
824   loadProcedures();
825   return mSTARs[aIndex];
826 }
827
828 //------------------------------------------------------------------------------
829 STAR* FGAirport::findSTARWithIdent(const std::string& aIdent) const
830 {
831   loadProcedures();
832   for (unsigned int i=0; i<mSTARs.size(); ++i) {
833     if (mSTARs[i]->ident() == aIdent) {
834       return mSTARs[i];
835     }
836   }
837   
838   return NULL;
839 }
840
841 //------------------------------------------------------------------------------
842 STARList FGAirport::getSTARs() const
843 {
844   loadProcedures();
845   return STARList(mSTARs.begin(), mSTARs.end());
846 }
847
848 unsigned int FGAirport::numApproaches() const
849 {
850   loadProcedures();
851   return mApproaches.size();
852 }
853
854 //------------------------------------------------------------------------------
855 Approach* FGAirport::getApproachByIndex(unsigned int aIndex) const
856 {
857   loadProcedures();
858   return mApproaches[aIndex];
859 }
860
861 //------------------------------------------------------------------------------
862 Approach* FGAirport::findApproachWithIdent(const std::string& aIdent) const
863 {
864   loadProcedures();
865   for (unsigned int i=0; i<mApproaches.size(); ++i) {
866     if (mApproaches[i]->ident() == aIdent) {
867       return mApproaches[i];
868     }
869   }
870   
871   return NULL;
872 }
873
874 //------------------------------------------------------------------------------
875 ApproachList FGAirport::getApproaches(ProcedureType type) const
876 {
877   loadProcedures();
878   if( type == PROCEDURE_INVALID )
879     return ApproachList(mApproaches.begin(), mApproaches.end());
880
881   ApproachList ret;
882   for(size_t i = 0; i < mApproaches.size(); ++i)
883   {
884     if( mApproaches[i]->type() == type )
885       ret.push_back(mApproaches[i]);
886   }
887   return ret;
888 }
889
890 CommStationList
891 FGAirport::commStations() const
892 {
893   NavDataCache* cache = NavDataCache::instance();
894   CommStationList result;
895   BOOST_FOREACH(PositionedID pos, cache->airportItemsOfType(guid(),
896                                                             FGPositioned::FREQ_GROUND,
897                                                             FGPositioned::FREQ_UNICOM))
898   {
899     result.push_back( loadById<CommStation>(pos) );
900   }
901   
902   return result;
903 }
904
905 CommStationList
906 FGAirport::commStationsOfType(FGPositioned::Type aTy) const
907 {
908   NavDataCache* cache = NavDataCache::instance();
909   CommStationList result;
910   BOOST_FOREACH(PositionedID pos, cache->airportItemsOfType(guid(), aTy)) {
911     result.push_back( loadById<CommStation>(pos) );
912   }
913   
914   return result;
915 }
916
917 class AirportWithSize
918 {
919 public:
920     AirportWithSize(FGPositionedRef pos) :
921         _pos(pos),
922         _sizeMetric(0)
923     {
924         assert(pos->type() == FGPositioned::AIRPORT);
925         FGAirport* apt = static_cast<FGAirport*>(pos.get());
926         BOOST_FOREACH(FGRunway* rwy, apt->getRunwaysWithoutReciprocals()) {
927             _sizeMetric += static_cast<int>(rwy->lengthFt());
928         }
929     }
930     
931     bool operator<(const AirportWithSize& other) const
932     {
933         return _sizeMetric < other._sizeMetric;
934     }
935     
936     FGPositionedRef pos() const
937     { return _pos; }
938 private:
939     FGPositionedRef _pos;
940     unsigned int _sizeMetric;
941     
942 };
943
944 void FGAirport::sortBySize(FGPositionedList& airportList)
945 {
946     std::vector<AirportWithSize> annotated;
947     BOOST_FOREACH(FGPositionedRef p, airportList) {
948         annotated.push_back(AirportWithSize(p));
949     }
950     std::sort(annotated.begin(), annotated.end());
951     
952     for (unsigned int i=0; i<annotated.size(); ++i) {
953         airportList[i] = annotated[i].pos();
954     }
955 }
956
957 // get airport elevation
958 double fgGetAirportElev( const std::string& id )
959 {
960     const FGAirport *a=fgFindAirportID( id);
961     if (a) {
962         return a->getElevation();
963     } else {
964         return -9999.0;
965     }
966 }
967
968
969 // get airport position
970 SGGeod fgGetAirportPos( const std::string& id )
971 {
972     const FGAirport *a = fgFindAirportID( id);
973
974     if (a) {
975         return SGGeod::fromDegM(a->getLongitude(), a->getLatitude(), a->getElevation());
976     } else {
977         return SGGeod::fromDegM(0.0, 0.0, -9999.0);
978     }
979 }