]> git.mxchange.org Git - flightgear.git/blob - src/Airports/airport.cxx
ICAO.twr.xml works in read-only mode.
[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, struct FindBestRunwayForHeadingParams * parms ) const
240 {
241   loadRunways();
242   
243   FGRunway* result = NULL;
244   double currentBestQuality = 0.0;
245   
246   struct FindBestRunwayForHeadingParams fbrfhp;
247   if( NULL != parms ) fbrfhp = *parms;
248
249   SGPropertyNode_ptr searchNode = fgGetNode("/sim/airport/runways/search");
250   if( searchNode.valid() ) {
251     fbrfhp.lengthWeight = searchNode->getDoubleValue("length-weight", fbrfhp.lengthWeight );
252     fbrfhp.widthWeight = searchNode->getDoubleValue("width-weight", fbrfhp.widthWeight );
253     fbrfhp.surfaceWeight = searchNode->getDoubleValue("surface-weight", fbrfhp.surfaceWeight );
254     fbrfhp.deviationWeight = searchNode->getDoubleValue("deviation-weight", fbrfhp.deviationWeight );
255     fbrfhp.ilsWeight = searchNode->getDoubleValue("ils-weight", fbrfhp.ilsWeight );
256   }
257     
258   BOOST_FOREACH(PositionedID id, mRunways) {
259     FGRunway* rwy = loadById<FGRunway>(id);
260     // bug http://code.google.com/p/flightgear-bugs/issues/detail?id=1149
261     // (and probably some other issues besides). 
262     if (rwy->type() == FGPositioned::HELIPAD) {
263       continue;
264     }
265       
266     double good = rwy->score( fbrfhp.lengthWeight,  fbrfhp.widthWeight,  fbrfhp.surfaceWeight,  fbrfhp.ilsWeight );
267     double dev = aHeading - rwy->headingDeg();
268     SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
269     double bad = fabs( fbrfhp.deviationWeight * dev) + 1e-20;
270     double quality = good / bad;
271     
272     if (quality > currentBestQuality) {
273       currentBestQuality = quality;
274       result = rwy;
275     }
276   }
277
278   return result;
279 }
280
281 //------------------------------------------------------------------------------
282 FGRunwayRef FGAirport::findBestRunwayForPos(const SGGeod& aPos) const
283 {
284   loadRunways();
285   
286   FGRunway* result = NULL;
287   double currentLowestDev = 180.0;
288   
289   BOOST_FOREACH(PositionedID id, mRunways) {
290     FGRunway* rwy = loadById<FGRunway>(id);
291
292     double inboundCourse = SGGeodesy::courseDeg(aPos, rwy->end());
293     double dev = inboundCourse - rwy->headingDeg();
294     SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
295
296     dev = fabs(dev);
297     if (dev < currentLowestDev) { // new best match
298       currentLowestDev = dev;
299       result = rwy;
300     }
301   } // of runway iteration
302   
303   return result;
304
305 }
306
307 //------------------------------------------------------------------------------
308 bool FGAirport::hasHardRunwayOfLengthFt(double aLengthFt) const
309 {
310   loadRunways();
311   
312   BOOST_FOREACH(PositionedID id, mRunways) {
313     FGRunway* rwy = loadById<FGRunway>(id);
314     if (rwy->isHardSurface() && (rwy->lengthFt() >= aLengthFt)) {
315       return true; // we're done!
316     }
317   } // of runways iteration
318
319   return false;
320 }
321
322 //------------------------------------------------------------------------------
323 FGRunwayList FGAirport::getRunwaysWithoutReciprocals() const
324 {
325   loadRunways();
326   
327   FGRunwayList r;
328   
329   BOOST_FOREACH(PositionedID id, mRunways) {
330     FGRunway* rwy = loadById<FGRunway>(id);
331     FGRunway* recip = rwy->reciprocalRunway();
332     if (recip) {
333       FGRunwayList::iterator it = std::find(r.begin(), r.end(), recip);
334       if (it != r.end()) {
335         continue; // reciprocal already in result set, don't include us
336       }
337     }
338     
339     r.push_back(rwy);
340   }
341   
342   return r;
343 }
344
345 //------------------------------------------------------------------------------
346 unsigned int FGAirport::numTaxiways() const
347 {
348   loadTaxiways();
349   return mTaxiways.size();
350 }
351
352 //------------------------------------------------------------------------------
353 FGTaxiwayRef FGAirport::getTaxiwayByIndex(unsigned int aIndex) const
354 {
355   loadTaxiways();
356   return loadById<FGTaxiway>(mTaxiways, aIndex);
357 }
358
359 //------------------------------------------------------------------------------
360 FGTaxiwayList FGAirport::getTaxiways() const
361 {
362   loadTaxiways();
363   return loadAllById<FGTaxiway>(mTaxiways);
364 }
365
366 //------------------------------------------------------------------------------
367 unsigned int FGAirport::numPavements() const
368 {
369   loadTaxiways();
370   return mPavements.size();
371 }
372
373 //------------------------------------------------------------------------------
374 FGPavementRef FGAirport::getPavementByIndex(unsigned int aIndex) const
375 {
376   loadTaxiways();
377   return loadById<FGPavement>(mPavements, aIndex);
378 }
379
380 //------------------------------------------------------------------------------
381 FGPavementList FGAirport::getPavements() const
382 {
383   loadTaxiways();
384   return loadAllById<FGPavement>(mPavements);
385 }
386
387 //------------------------------------------------------------------------------
388 FGRunwayRef FGAirport::getActiveRunwayForUsage() const
389 {
390   FGEnvironmentMgr* envMgr = (FGEnvironmentMgr *) globals->get_subsystem("environment");
391   
392   // This forces West-facing rwys to be used in no-wind situations
393   // which is consistent with Flightgear's initial setup.
394   double hdg = 270;
395   
396   if (envMgr) {
397     FGEnvironment stationWeather(envMgr->getEnvironment(geod()));
398   
399     double windSpeed = stationWeather.get_wind_speed_kt();
400     if (windSpeed > 0.0) {
401       hdg = stationWeather.get_wind_from_heading_deg();
402     }
403   }
404   
405   return findBestRunwayForHeading(hdg);
406 }
407
408 //------------------------------------------------------------------------------
409 FGAirportRef FGAirport::findClosest( const SGGeod& aPos,
410                                      double aCuttofNm,
411                                      Filter* filter )
412 {
413   AirportFilter aptFilter;
414   if( !filter )
415     filter = &aptFilter;
416   
417   return static_pointer_cast<FGAirport>
418   (
419     FGPositioned::findClosest(aPos, aCuttofNm, filter)
420   );
421 }
422
423 FGAirport::HardSurfaceFilter::HardSurfaceFilter(double minLengthFt) :
424   mMinLengthFt(minLengthFt)
425 {
426   if (minLengthFt < 0.0) {
427     mMinLengthFt = fgGetDouble("/sim/navdb/min-runway-length-ft", 0.0);
428   }
429 }
430
431 bool FGAirport::HardSurfaceFilter::passAirport(FGAirport* aApt) const
432 {
433   return aApt->hasHardRunwayOfLengthFt(mMinLengthFt);
434 }
435
436 //------------------------------------------------------------------------------
437 FGAirport::TypeRunwayFilter::TypeRunwayFilter():
438   _type(FGPositioned::AIRPORT),
439   _min_runway_length_ft( fgGetDouble("/sim/navdb/min-runway-length-ft", 0.0) )
440 {
441
442 }
443
444 //------------------------------------------------------------------------------
445 bool FGAirport::TypeRunwayFilter::fromTypeString(const std::string& type)
446 {
447   if(      type == "heliport" ) _type = FGPositioned::HELIPORT;
448   else if( type == "seaport"  ) _type = FGPositioned::SEAPORT;
449   else if( type == "airport"  ) _type = FGPositioned::AIRPORT;
450   else                          return false;
451
452   return true;
453 }
454
455 //------------------------------------------------------------------------------
456 bool FGAirport::TypeRunwayFilter::pass(FGPositioned* pos) const
457 {
458   FGAirport* apt = static_cast<FGAirport*>(pos);
459   if(  (apt->type() == FGPositioned::AIRPORT)
460     && !apt->hasHardRunwayOfLengthFt(_min_runway_length_ft)
461     )
462     return false;
463
464   return true;
465 }
466
467 //------------------------------------------------------------------------------
468 FGAirportRef FGAirport::findByIdent(const std::string& aIdent)
469 {
470   AirportCache::iterator it = airportCache.find(aIdent);
471   if (it != airportCache.end())
472    return it->second;
473
474   PortsFilter filter;
475   FGAirportRef r = static_pointer_cast<FGAirport>
476   (
477     FGPositioned::findFirstWithIdent(aIdent, &filter)
478   );
479
480   // add airport to the cache (even when it's NULL, so we don't need to search in vain again)
481   airportCache[aIdent] = r;
482
483   // we don't warn here when r==NULL, let the caller do that
484   return r;
485 }
486
487 //------------------------------------------------------------------------------
488 FGAirportRef FGAirport::getByIdent(const std::string& aIdent)
489 {
490   FGAirportRef r = findByIdent(aIdent);
491   if (!r)
492     throw sg_range_exception("No such airport with ident: " + aIdent);
493   return r;
494 }
495
496 char** FGAirport::searchNamesAndIdents(const std::string& aFilter)
497 {
498   return NavDataCache::instance()->searchAirportNamesAndIdents(aFilter);
499 }
500
501 // find basic airport location info from airport database
502 const FGAirport *fgFindAirportID( const std::string& id)
503 {
504     if ( id.empty() ) {
505         return NULL;
506     }
507     
508     return FGAirport::findByIdent(id);
509 }
510
511 void FGAirport::loadRunways() const
512 {
513   if (mRunwaysLoaded) {
514     return; // already loaded, great
515   }
516   
517   loadSceneryDefinitions();
518   
519   mRunwaysLoaded = true;
520   mRunways = flightgear::NavDataCache::instance()->airportItemsOfType(guid(), FGPositioned::RUNWAY);
521 }
522
523 void FGAirport::loadHelipads() const
524 {
525   if (mHelipadsLoaded) {
526     return; // already loaded, great
527   }
528
529   loadSceneryDefinitions();
530
531   mHelipadsLoaded = true;
532   mHelipads = flightgear::NavDataCache::instance()->airportItemsOfType(guid(), FGPositioned::HELIPAD);
533 }
534
535 void FGAirport::loadTaxiways() const
536 {
537   if (mTaxiwaysLoaded) {
538     return; // already loaded, great
539   }
540   
541   mTaxiwaysLoaded =  true;
542   mTaxiways = flightgear::NavDataCache::instance()->airportItemsOfType(guid(), FGPositioned::TAXIWAY);
543 }
544
545 void FGAirport::loadProcedures() const
546 {
547   if (mProceduresLoaded) {
548     return;
549   }
550   
551   mProceduresLoaded = true;
552   SGPath path;
553   if (!XMLLoader::findAirportData(ident(), "procedures", path)) {
554     SG_LOG(SG_GENERAL, SG_INFO, "no procedures data available for " << ident());
555     return;
556   }
557   
558   SG_LOG(SG_GENERAL, SG_INFO, ident() << ": loading procedures from " << path.str());
559   RouteBase::loadAirportProcedures(path, const_cast<FGAirport*>(this));
560 }
561
562 void FGAirport::loadSceneryDefinitions() const
563 {
564   NavDataCache* cache = NavDataCache::instance();
565     if (cache->isReadOnly()) {
566         return;
567     }
568     
569   SGPath path;
570   if (!XMLLoader::findAirportData(ident(), "threshold", path)) {
571     return; // no XML threshold data
572   }
573   
574   if (!cache->isCachedFileModified(path)) {
575     // cached values are correct, we're all done
576     return;
577   }
578   
579     try {
580         flightgear::NavDataCache::Transaction txn(cache);
581         SGPropertyNode_ptr rootNode = new SGPropertyNode;
582         readProperties(path.str(), rootNode);
583         const_cast<FGAirport*>(this)->readThresholdData(rootNode);
584         cache->stampCacheFile(path);
585         txn.commit();
586     } catch (sg_exception& e) {
587         SG_LOG(SG_NAVAID, SG_WARN, ident() << "loading threshold XML failed:" << e.getFormattedMessage());
588     }
589 }
590
591 void FGAirport::readThresholdData(SGPropertyNode* aRoot)
592 {
593   SGPropertyNode* runway;
594   int runwayIndex = 0;
595   for (; (runway = aRoot->getChild("runway", runwayIndex)) != NULL; ++runwayIndex) {
596     SGPropertyNode* t0 = runway->getChild("threshold", 0),
597       *t1 = runway->getChild("threshold", 1);
598     assert(t0);
599     assert(t1); // too strict? maybe we should finally allow single-ended runways
600     
601     processThreshold(t0);
602     processThreshold(t1);
603   } // of runways iteration
604 }
605
606 void FGAirport::processThreshold(SGPropertyNode* aThreshold)
607 {
608   // first, let's identify the current runway
609   std::string rwyIdent(aThreshold->getStringValue("rwy"));
610   NavDataCache* cache = NavDataCache::instance(); 
611   PositionedID id = cache->airportItemWithIdent(guid(), FGPositioned::RUNWAY, rwyIdent);
612   if (id == 0) {
613     SG_LOG(SG_GENERAL, SG_DEBUG, "FGAirport::processThreshold: "
614            "found runway not defined in the global data:" << ident() << "/" << rwyIdent);
615     return;
616   }
617   
618   double lon = aThreshold->getDoubleValue("lon"),
619   lat = aThreshold->getDoubleValue("lat");
620   SGGeod newThreshold(SGGeod::fromDegM(lon, lat, elevationM()));
621   
622   double newHeading = aThreshold->getDoubleValue("hdg-deg");
623   double newDisplacedThreshold = aThreshold->getDoubleValue("displ-m");
624   double newStopway = aThreshold->getDoubleValue("stopw-m");
625   
626   cache->updateRunwayThreshold(id, newThreshold,
627                                newHeading, newDisplacedThreshold, newStopway);
628 }
629
630 SGGeod FGAirport::getTowerLocation() const
631 {
632   validateTowerData();
633   return mTowerPosition;
634 }
635
636 void FGAirport::validateTowerData() const
637 {
638   if (mTowerDataLoaded) {
639     return;
640   }
641   
642   mTowerDataLoaded = true;
643
644 // first, load data from the cache (apt.dat)
645   NavDataCache* cache = NavDataCache::instance();
646   PositionedIDVec towers = cache->airportItemsOfType(guid(), FGPositioned::TOWER);
647   if (towers.empty()) {
648     SG_LOG(SG_GENERAL, SG_ALERT, "No towers defined for:" <<ident());
649     mTowerPosition = geod(); // use airport position
650     // increase tower elevation by 20 metres above the field elevation
651     mTowerPosition.setElevationM(geod().getElevationM() + 20.0);
652   } else {
653     FGPositionedRef tower = cache->loadById(towers.front());
654     mTowerPosition = tower->geod();
655   }
656   
657   SGPath path;
658   if (!XMLLoader::findAirportData(ident(), "twr", path)) {
659     return; // no XML tower data, base position is fine
660   }
661   
662   try {
663     SGPropertyNode_ptr rootNode = new SGPropertyNode;
664     readProperties(path.str(), rootNode);
665     const_cast<FGAirport*>(this)->readTowerData(rootNode);
666   } catch (sg_exception& e){
667     SG_LOG(SG_NAVAID, SG_WARN, ident() << "loading twr XML failed:" << e.getFormattedMessage());
668   }
669 }
670
671 void FGAirport::readTowerData(SGPropertyNode* aRoot)
672 {
673   SGPropertyNode* twrNode = aRoot->getChild("tower")->getChild("twr");
674   double lat = twrNode->getDoubleValue("lat"), 
675     lon = twrNode->getDoubleValue("lon"), 
676     elevM = twrNode->getDoubleValue("elev-m");  
677 // tower elevation is AGL, not AMSL. Since we don't want to depend on the
678 // scenery for a precise terrain elevation, we use the field elevation
679 // (this is also what the apt.dat code does)
680   double fieldElevationM = geod().getElevationM();
681   mTowerPosition = SGGeod::fromDegM(lon, lat, fieldElevationM + elevM);
682 }
683
684 bool FGAirport::validateILSData()
685 {
686   if (mILSDataLoaded) {
687     return false;
688   }
689   
690   mILSDataLoaded = true;
691   NavDataCache* cache = NavDataCache::instance();
692     if (cache->isReadOnly()) {
693         return false;
694     }
695     
696   SGPath path;
697   if (!XMLLoader::findAirportData(ident(), "ils", path)) {
698     return false; // no XML tower data
699   }
700   
701   if (!cache->isCachedFileModified(path)) {
702     // cached values are correct, we're all done
703     return false;
704   }
705   
706     try {
707         SGPropertyNode_ptr rootNode = new SGPropertyNode;
708         readProperties(path.str(), rootNode);
709
710         flightgear::NavDataCache::Transaction txn(cache);
711         readILSData(rootNode);
712         cache->stampCacheFile(path);
713         txn.commit();
714 // we loaded data, tell the caller it might need to reload things
715         return true;
716     } catch (sg_exception& e){
717         SG_LOG(SG_NAVAID, SG_WARN, ident() << "loading ils XML failed:" << e.getFormattedMessage());
718     }
719     
720     return false;
721 }
722
723 void FGAirport::readILSData(SGPropertyNode* aRoot)
724 {
725   NavDataCache* cache = NavDataCache::instance();
726   
727   // find the entry matching the runway
728   SGPropertyNode* runwayNode, *ilsNode;
729   for (int i=0; (runwayNode = aRoot->getChild("runway", i)) != NULL; ++i) {
730     for (int j=0; (ilsNode = runwayNode->getChild("ils", j)) != NULL; ++j) {
731       // must match on both nav-ident and runway ident, to support the following:
732       // - runways with multiple distinct ILS installations (KEWD, for example)
733       // - runways where both ends share the same nav ident (LFAT, for example)
734       PositionedID ils = cache->findILS(guid(), ilsNode->getStringValue("rwy"),
735                                         ilsNode->getStringValue("nav-id"));
736       if (ils == 0) {
737         SG_LOG(SG_GENERAL, SG_INFO, "reading ILS data for " << ident() <<
738                ", couldn;t find runway/navaid for:" <<
739                ilsNode->getStringValue("rwy") << "/" <<
740                ilsNode->getStringValue("nav-id"));
741         continue;
742       }
743       
744       double hdgDeg = ilsNode->getDoubleValue("hdg-deg"),
745         lon = ilsNode->getDoubleValue("lon"),
746         lat = ilsNode->getDoubleValue("lat"),
747         elevM = ilsNode->getDoubleValue("elev-m");
748  
749       cache->updateILS(ils, SGGeod::fromDegM(lon, lat, elevM), hdgDeg);
750     } // of ILS iteration
751   } // of runway iteration
752 }
753
754 void FGAirport::addSID(flightgear::SID* aSid)
755 {
756   mSIDs.push_back(aSid);
757 }
758
759 void FGAirport::addSTAR(STAR* aStar)
760 {
761   mSTARs.push_back(aStar);
762 }
763
764 void FGAirport::addApproach(Approach* aApp)
765 {
766   mApproaches.push_back(aApp);
767 }
768
769 //------------------------------------------------------------------------------
770 unsigned int FGAirport::numSIDs() const
771 {
772   loadProcedures();
773   return mSIDs.size();
774 }
775
776 //------------------------------------------------------------------------------
777 flightgear::SID* FGAirport::getSIDByIndex(unsigned int aIndex) const
778 {
779   loadProcedures();
780   return mSIDs[aIndex];
781 }
782
783 //------------------------------------------------------------------------------
784 flightgear::SID* FGAirport::findSIDWithIdent(const std::string& aIdent) const
785 {
786   loadProcedures();
787   for (unsigned int i=0; i<mSIDs.size(); ++i) {
788     if (mSIDs[i]->ident() == aIdent) {
789       return mSIDs[i];
790     }
791   }
792   
793   return NULL;
794 }
795
796 //------------------------------------------------------------------------------
797 flightgear::SIDList FGAirport::getSIDs() const
798 {
799   loadProcedures();
800   return flightgear::SIDList(mSIDs.begin(), mSIDs.end());
801 }
802
803 //------------------------------------------------------------------------------
804 unsigned int FGAirport::numSTARs() const
805 {
806   loadProcedures();
807   return mSTARs.size();
808 }
809
810 //------------------------------------------------------------------------------
811 STAR* FGAirport::getSTARByIndex(unsigned int aIndex) const
812 {
813   loadProcedures();
814   return mSTARs[aIndex];
815 }
816
817 //------------------------------------------------------------------------------
818 STAR* FGAirport::findSTARWithIdent(const std::string& aIdent) const
819 {
820   loadProcedures();
821   for (unsigned int i=0; i<mSTARs.size(); ++i) {
822     if (mSTARs[i]->ident() == aIdent) {
823       return mSTARs[i];
824     }
825   }
826   
827   return NULL;
828 }
829
830 //------------------------------------------------------------------------------
831 STARList FGAirport::getSTARs() const
832 {
833   loadProcedures();
834   return STARList(mSTARs.begin(), mSTARs.end());
835 }
836
837 unsigned int FGAirport::numApproaches() const
838 {
839   loadProcedures();
840   return mApproaches.size();
841 }
842
843 //------------------------------------------------------------------------------
844 Approach* FGAirport::getApproachByIndex(unsigned int aIndex) const
845 {
846   loadProcedures();
847   return mApproaches[aIndex];
848 }
849
850 //------------------------------------------------------------------------------
851 Approach* FGAirport::findApproachWithIdent(const std::string& aIdent) const
852 {
853   loadProcedures();
854   for (unsigned int i=0; i<mApproaches.size(); ++i) {
855     if (mApproaches[i]->ident() == aIdent) {
856       return mApproaches[i];
857     }
858   }
859   
860   return NULL;
861 }
862
863 //------------------------------------------------------------------------------
864 ApproachList FGAirport::getApproaches(ProcedureType type) const
865 {
866   loadProcedures();
867   if( type == PROCEDURE_INVALID )
868     return ApproachList(mApproaches.begin(), mApproaches.end());
869
870   ApproachList ret;
871   for(size_t i = 0; i < mApproaches.size(); ++i)
872   {
873     if( mApproaches[i]->type() == type )
874       ret.push_back(mApproaches[i]);
875   }
876   return ret;
877 }
878
879 CommStationList
880 FGAirport::commStations() const
881 {
882   NavDataCache* cache = NavDataCache::instance();
883   CommStationList result;
884   BOOST_FOREACH(PositionedID pos, cache->airportItemsOfType(guid(),
885                                                             FGPositioned::FREQ_GROUND,
886                                                             FGPositioned::FREQ_UNICOM))
887   {
888     result.push_back( loadById<CommStation>(pos) );
889   }
890   
891   return result;
892 }
893
894 CommStationList
895 FGAirport::commStationsOfType(FGPositioned::Type aTy) const
896 {
897   NavDataCache* cache = NavDataCache::instance();
898   CommStationList result;
899   BOOST_FOREACH(PositionedID pos, cache->airportItemsOfType(guid(), aTy)) {
900     result.push_back( loadById<CommStation>(pos) );
901   }
902   
903   return result;
904 }
905
906 class AirportWithSize
907 {
908 public:
909     AirportWithSize(FGPositionedRef pos) :
910         _pos(pos),
911         _sizeMetric(0)
912     {
913         assert(pos->type() == FGPositioned::AIRPORT);
914         FGAirport* apt = static_cast<FGAirport*>(pos.get());
915         BOOST_FOREACH(FGRunway* rwy, apt->getRunwaysWithoutReciprocals()) {
916             _sizeMetric += static_cast<int>(rwy->lengthFt());
917         }
918     }
919     
920     bool operator<(const AirportWithSize& other) const
921     {
922         return _sizeMetric < other._sizeMetric;
923     }
924     
925     FGPositionedRef pos() const
926     { return _pos; }
927 private:
928     FGPositionedRef _pos;
929     unsigned int _sizeMetric;
930     
931 };
932
933 void FGAirport::sortBySize(FGPositionedList& airportList)
934 {
935     std::vector<AirportWithSize> annotated;
936     BOOST_FOREACH(FGPositionedRef p, airportList) {
937         annotated.push_back(AirportWithSize(p));
938     }
939     std::sort(annotated.begin(), annotated.end());
940     
941     for (unsigned int i=0; i<annotated.size(); ++i) {
942         airportList[i] = annotated[i].pos();
943     }
944 }
945
946 // get airport elevation
947 double fgGetAirportElev( const std::string& id )
948 {
949     const FGAirport *a=fgFindAirportID( id);
950     if (a) {
951         return a->getElevation();
952     } else {
953         return -9999.0;
954     }
955 }
956
957
958 // get airport position
959 SGGeod fgGetAirportPos( const std::string& id )
960 {
961     const FGAirport *a = fgFindAirportID( id);
962
963     if (a) {
964         return SGGeod::fromDegM(a->getLongitude(), a->getLatitude(), a->getElevation());
965     } else {
966         return SGGeod::fromDegM(0.0, 0.0, -9999.0);
967     }
968 }