]> git.mxchange.org Git - flightgear.git/blob - src/Airports/simple.cxx
Implement a persistent cache for navigation data.
[flightgear.git] / src / Airports / simple.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 "simple.hxx"
32
33 #include <cassert>
34 #include <boost/foreach.hpp>
35
36 #include <simgear/misc/sg_path.hxx>
37 #include <simgear/props/props.hxx>
38 #include <simgear/props/props_io.hxx>
39 #include <simgear/debug/logstream.hxx>
40 #include <simgear/sg_inlines.h>
41
42 #include <Environment/environment_mgr.hxx>
43 #include <Environment/environment.hxx>
44 #include <Main/fg_props.hxx>
45 #include <Airports/runways.hxx>
46 #include <Airports/pavement.hxx>
47 #include <Airports/dynamics.hxx>
48 #include <Airports/xmlloader.hxx>
49 #include <Navaids/procedure.hxx>
50 #include <Navaids/waypoint.hxx>
51 #include <ATC/CommStation.hxx>
52 #include <Navaids/NavDataCache.hxx>
53
54 using std::vector;
55 using std::pair;
56
57 using namespace flightgear;
58
59
60 /***************************************************************************
61  * FGAirport
62  ***************************************************************************/
63
64 FGAirport::FGAirport(PositionedID aGuid, const string &id, const SGGeod& location,
65         const string &name, bool has_metar, Type aType) :
66     FGPositioned(aGuid, aType, id, location),
67     _name(name),
68     _has_metar(has_metar),
69     _dynamics(0),
70     mTowerDataLoaded(false),
71     mRunwaysLoaded(false),
72     mTaxiwaysLoaded(true)
73 {
74 }
75
76
77 FGAirport::~FGAirport()
78 {
79     delete _dynamics;
80 }
81
82 bool FGAirport::isAirport() const
83 {
84   return type() == AIRPORT;
85 }
86
87 bool FGAirport::isSeaport() const
88 {
89   return type() == SEAPORT;
90 }
91
92 bool FGAirport::isHeliport() const
93 {
94   return type() == HELIPORT;
95 }
96
97 bool FGAirport::isAirportType(FGPositioned* pos)
98 {
99     if (!pos) {
100         return false;
101     }
102     
103     return (pos->type() >= AIRPORT) && (pos->type() <= SEAPORT);
104 }
105
106 FGAirportDynamics * FGAirport::getDynamics()
107 {
108     if (_dynamics) {
109         return _dynamics;
110     }
111     
112     _dynamics = new FGAirportDynamics(this);
113     XMLLoader::load(_dynamics);
114
115     FGRunwayPreference rwyPrefs(this);
116     XMLLoader::load(&rwyPrefs);
117     _dynamics->setRwyUse(rwyPrefs);
118     XMLLoader::load(_dynamics->getSIDs());
119     
120     return _dynamics;
121 }
122
123 unsigned int FGAirport::numRunways() const
124 {
125   loadRunways();
126   return mRunways.size();
127 }
128
129 FGRunway* FGAirport::getRunwayByIndex(unsigned int aIndex) const
130 {
131   loadRunways();
132   
133   assert(aIndex >= 0 && aIndex < mRunways.size());
134   return (FGRunway*) flightgear::NavDataCache::instance()->loadById(mRunways[aIndex]);
135 }
136
137 bool FGAirport::hasRunwayWithIdent(const string& aIdent) const
138 {
139   return flightgear::NavDataCache::instance()->airportItemWithIdent(guid(), FGPositioned::RUNWAY, aIdent) != 0;
140 }
141
142 FGRunway* FGAirport::getRunwayByIdent(const string& aIdent) const
143 {
144   PositionedID id = flightgear::NavDataCache::instance()->airportItemWithIdent(guid(), FGPositioned::RUNWAY, aIdent);  
145   if (id == 0) {
146     SG_LOG(SG_GENERAL, SG_ALERT, "no such runway '" << aIdent << "' at airport " << ident());
147     throw sg_range_exception("unknown runway " + aIdent + " at airport:" + ident(), "FGAirport::getRunwayByIdent");
148   }
149   
150   return (FGRunway*) flightgear::NavDataCache::instance()->loadById(id);
151 }
152
153
154 FGRunway* FGAirport::findBestRunwayForHeading(double aHeading) const
155 {
156   loadRunways();
157   
158   FGRunway* result = NULL;
159   double currentBestQuality = 0.0;
160   
161   SGPropertyNode *param = fgGetNode("/sim/airport/runways/search", true);
162   double lengthWeight = param->getDoubleValue("length-weight", 0.01);
163   double widthWeight = param->getDoubleValue("width-weight", 0.01);
164   double surfaceWeight = param->getDoubleValue("surface-weight", 10);
165   double deviationWeight = param->getDoubleValue("deviation-weight", 1);
166     
167   BOOST_FOREACH(PositionedID id, mRunways) {
168     FGRunway* rwy = (FGRunway*) flightgear::NavDataCache::instance()->loadById(id);
169     double good = rwy->score(lengthWeight, widthWeight, surfaceWeight);
170     double dev = aHeading - rwy->headingDeg();
171     SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
172     double bad = fabs(deviationWeight * dev) + 1e-20;
173     double quality = good / bad;
174     
175     if (quality > currentBestQuality) {
176       currentBestQuality = quality;
177       result = rwy;
178     }
179   }
180
181   return result;
182 }
183
184 FGRunway* FGAirport::findBestRunwayForPos(const SGGeod& aPos) const
185 {
186   loadRunways();
187   
188   FGRunway* result = NULL;
189   double currentLowestDev = 180.0;
190   
191   BOOST_FOREACH(PositionedID id, mRunways) {
192     FGRunway* rwy = (FGRunway*) flightgear::NavDataCache::instance()->loadById(id);
193
194     double inboundCourse = SGGeodesy::courseDeg(aPos, rwy->end());
195     double dev = inboundCourse - rwy->headingDeg();
196     SG_NORMALIZE_RANGE(dev, -180.0, 180.0);
197
198     dev = fabs(dev);
199     if (dev < currentLowestDev) { // new best match
200       currentLowestDev = dev;
201       result = rwy;
202     }
203   } // of runway iteration
204   
205   return result;
206
207 }
208
209 bool FGAirport::hasHardRunwayOfLengthFt(double aLengthFt) const
210 {
211   loadRunways();
212   
213   BOOST_FOREACH(PositionedID id, mRunways) {
214     FGRunway* rwy = (FGRunway*) flightgear::NavDataCache::instance()->loadById(id);
215
216     if (rwy->isReciprocal()) {
217       continue; // we only care about lengths, so don't do work twice
218     }
219
220     if (rwy->isHardSurface() && (rwy->lengthFt() >= aLengthFt)) {
221       return true; // we're done!
222     }
223   } // of runways iteration
224
225   return false;
226 }
227
228 unsigned int FGAirport::numTaxiways() const
229 {
230   loadTaxiways();
231   return mTaxiways.size();
232 }
233
234 FGTaxiway* FGAirport::getTaxiwayByIndex(unsigned int aIndex) const
235 {
236   loadTaxiways();
237   assert(aIndex >= 0 && aIndex < mTaxiways.size());
238   return (FGTaxiway*) flightgear::NavDataCache::instance()->loadById(mTaxiways[aIndex]);
239 }
240
241 unsigned int FGAirport::numPavements() const
242 {
243   loadTaxiways();
244   return mPavements.size();
245 }
246
247 FGPavement* FGAirport::getPavementByIndex(unsigned int aIndex) const
248 {
249   loadTaxiways();
250   assert(aIndex >= 0 && aIndex < mPavements.size());
251   return (FGPavement*) flightgear::NavDataCache::instance()->loadById(mPavements[aIndex]);
252 }
253
254 FGRunway* FGAirport::getActiveRunwayForUsage() const
255 {
256   static FGEnvironmentMgr* envMgr = NULL;
257   if (!envMgr) {
258     envMgr = (FGEnvironmentMgr *) globals->get_subsystem("environment");
259   }
260   
261   // This forces West-facing rwys to be used in no-wind situations
262   // which is consistent with Flightgear's initial setup.
263   double hdg = 270;
264   
265   if (envMgr) {
266     FGEnvironment stationWeather(envMgr->getEnvironment(mPosition));
267   
268     double windSpeed = stationWeather.get_wind_speed_kt();
269     if (windSpeed > 0.0) {
270       hdg = stationWeather.get_wind_from_heading_deg();
271     }
272   }
273   
274   return findBestRunwayForHeading(hdg);
275 }
276
277 FGAirport* FGAirport::findClosest(const SGGeod& aPos, double aCuttofNm, Filter* filter)
278 {
279   AirportFilter aptFilter;
280   if (filter == NULL) {
281     filter = &aptFilter;
282   }
283   
284   FGPositionedRef r = FGPositioned::findClosest(aPos, aCuttofNm, filter);
285   if (!r) {
286     return NULL;
287   }
288   
289   return static_cast<FGAirport*>(r.ptr());
290 }
291
292 FGAirport::HardSurfaceFilter::HardSurfaceFilter(double minLengthFt) :
293   mMinLengthFt(minLengthFt)
294 {
295   if (minLengthFt < 0.0) {
296     mMinLengthFt = fgGetDouble("/sim/navdb/min-runway-length-ft", 0.0);
297   }
298 }
299       
300 bool FGAirport::HardSurfaceFilter::passAirport(FGAirport* aApt) const
301 {
302   return aApt->hasHardRunwayOfLengthFt(mMinLengthFt);
303 }
304
305 FGAirport* FGAirport::findByIdent(const std::string& aIdent)
306 {
307   PortsFilter filter;
308   FGPositionedRef r = FGPositioned::findFirstWithIdent(aIdent, &filter);
309   if (!r) {
310     return NULL; // we don't warn here, let the caller do that
311   }
312   return static_cast<FGAirport*>(r.ptr());
313 }
314
315 FGAirport* FGAirport::getByIdent(const std::string& aIdent)
316 {
317   FGPositionedRef r;
318   PortsFilter filter;
319   r = FGPositioned::findFirstWithIdent(aIdent, &filter);
320   if (!r) {
321     throw sg_range_exception("No such airport with ident: " + aIdent);
322   }
323   return static_cast<FGAirport*>(r.ptr());
324 }
325
326 char** FGAirport::searchNamesAndIdents(const std::string& aFilter)
327 {
328   return NavDataCache::instance()->searchAirportNamesAndIdents(aFilter);
329 }
330
331 // find basic airport location info from airport database
332 const FGAirport *fgFindAirportID( const string& id)
333 {
334     if ( id.empty() ) {
335         return NULL;
336     }
337     
338     return FGAirport::findByIdent(id);
339 }
340
341 void FGAirport::loadRunways() const
342 {
343   if (mRunwaysLoaded) {
344     return; // already loaded, great
345   }
346   
347   loadSceneryDefinitions();
348   
349   mRunwaysLoaded = true;
350   mRunways = flightgear::NavDataCache::instance()->airportItemsOfType(guid(), FGPositioned::RUNWAY);
351 }
352
353 void FGAirport::loadTaxiways() const
354 {
355   if (mTaxiwaysLoaded) {
356     return; // already loaded, great
357   }
358   
359   mTaxiwaysLoaded =  true;
360   mTaxiways = flightgear::NavDataCache::instance()->airportItemsOfType(guid(), FGPositioned::TAXIWAY);
361 }
362
363 void FGAirport::loadProcedures() const
364 {
365   if (mProceduresLoaded) {
366     return;
367   }
368   
369   mProceduresLoaded = true;
370   SGPath path;
371   if (!XMLLoader::findAirportData(ident(), "procedures", path)) {
372     SG_LOG(SG_GENERAL, SG_INFO, "no procedures data available for " << ident());
373     return;
374   }
375   
376   SG_LOG(SG_GENERAL, SG_INFO, ident() << ": loading procedures from " << path.str());
377   RouteBase::loadAirportProcedures(path, const_cast<FGAirport*>(this));
378 }
379
380 void FGAirport::loadSceneryDefinitions() const
381 {
382   NavDataCache* cache = NavDataCache::instance();
383   SGPath path;
384   if (!XMLLoader::findAirportData(ident(), "threshold", path)) {
385     return; // no XML threshold data
386   }
387   
388   if (!cache->isCachedFileModified(path)) {
389     // cached values are correct, we're all done
390     return;
391   }
392   
393   SGPropertyNode_ptr rootNode = new SGPropertyNode;
394   readProperties(path.str(), rootNode);
395   const_cast<FGAirport*>(this)->readThresholdData(rootNode);
396   cache->stampCacheFile(path);
397
398 }
399
400 void FGAirport::readThresholdData(SGPropertyNode* aRoot)
401 {
402   SGPropertyNode* runway;
403   int runwayIndex = 0;
404   for (; (runway = aRoot->getChild("runway", runwayIndex)) != NULL; ++runwayIndex) {
405     SGPropertyNode* t0 = runway->getChild("threshold", 0),
406       *t1 = runway->getChild("threshold", 1);
407     assert(t0);
408     assert(t1); // too strict? mayeb we should finally allow single-ended runways
409     
410     processThreshold(t0);
411     processThreshold(t1);
412   } // of runways iteration
413 }
414
415 void FGAirport::processThreshold(SGPropertyNode* aThreshold)
416 {
417   // first, let's identify the current runway
418   string rwyIdent(aThreshold->getStringValue("rwy"));
419   NavDataCache* cache = NavDataCache::instance(); 
420   PositionedID id = cache->airportItemWithIdent(guid(), FGPositioned::RUNWAY, rwyIdent);
421   if (id == 0) {
422     SG_LOG(SG_GENERAL, SG_DEBUG, "FGAirport::processThreshold: "
423            "found runway not defined in the global data:" << ident() << "/" << rwyIdent);
424     return;
425   }
426   
427   double lon = aThreshold->getDoubleValue("lon"),
428   lat = aThreshold->getDoubleValue("lat");
429   SGGeod newThreshold(SGGeod::fromDegM(lon, lat, mPosition.getElevationM()));
430   
431   double newHeading = aThreshold->getDoubleValue("hdg-deg");
432   double newDisplacedThreshold = aThreshold->getDoubleValue("displ-m") * SG_METER_TO_FEET;
433   double newStopway = aThreshold->getDoubleValue("stopw-m") * SG_METER_TO_FEET;
434   
435   cache->updateRunwayThreshold(id, newThreshold,
436                                newHeading, newDisplacedThreshold, newStopway);
437 }
438
439 SGGeod FGAirport::getTowerLocation() const
440 {
441   validateTowerData();
442   
443   NavDataCache* cache = NavDataCache::instance();
444   PositionedIDVec towers = cache->airportItemsOfType(guid(), FGPositioned::TOWER);
445   if (towers.empty()) {
446     SG_LOG(SG_GENERAL, SG_ALERT, "No towers defined for:" <<ident());
447     return SGGeod();
448   }
449   
450   FGPositionedRef tower = cache->loadById(towers.front());
451   return tower->geod();
452 }
453
454 void FGAirport::validateTowerData() const
455 {
456   if (mTowerDataLoaded) {
457     return;
458   }
459
460   mTowerDataLoaded = true;
461   NavDataCache* cache = NavDataCache::instance();
462   SGPath path;
463   if (!XMLLoader::findAirportData(ident(), "twr", path)) {
464     return; // no XML tower data
465   }
466   
467   if (!cache->isCachedFileModified(path)) {
468   // cached values are correct, we're all done
469     return;
470   }
471     
472   SGPropertyNode_ptr rootNode = new SGPropertyNode;
473   readProperties(path.str(), rootNode);
474   const_cast<FGAirport*>(this)->readTowerData(rootNode);
475   cache->stampCacheFile(path);
476 }
477
478 void FGAirport::readTowerData(SGPropertyNode* aRoot)
479 {
480   SGPropertyNode* twrNode = aRoot->getChild("tower")->getChild("twr");
481   double lat = twrNode->getDoubleValue("lat"), 
482     lon = twrNode->getDoubleValue("lon"), 
483     elevM = twrNode->getDoubleValue("elev-m");  
484 // tower elevation is AGL, not AMSL. Since we don't want to depend on the
485 // scenery for a precise terrain elevation, we use the field elevation
486 // (this is also what the apt.dat code does)
487   double fieldElevationM = geod().getElevationM();
488   SGGeod towerLocation(SGGeod::fromDegM(lon, lat, fieldElevationM + elevM));
489   
490   NavDataCache* cache = NavDataCache::instance();
491   PositionedIDVec towers = cache->airportItemsOfType(guid(), FGPositioned::TOWER);
492   if (towers.empty()) {
493     cache->insertTower(guid(), towerLocation);
494   } else {
495     // update the position
496     cache->updatePosition(towers.front(), towerLocation);
497   }
498 }
499
500 bool FGAirport::validateILSData()
501 {
502   if (mILSDataLoaded) {
503     return false;
504   }
505   
506   mILSDataLoaded = true;
507   NavDataCache* cache = NavDataCache::instance();
508   SGPath path;
509   if (!XMLLoader::findAirportData(ident(), "ils", path)) {
510     return false; // no XML tower data
511   }
512   
513   if (!cache->isCachedFileModified(path)) {
514     // cached values are correct, we're all done
515     return false;
516   }
517   
518   SGPropertyNode_ptr rootNode = new SGPropertyNode;
519   readProperties(path.str(), rootNode);
520   readILSData(rootNode);
521   cache->stampCacheFile(path);
522   
523 // we loaded data, tell the caller it might need to reload things
524   return true;
525 }
526
527 void FGAirport::readILSData(SGPropertyNode* aRoot)
528 {
529   NavDataCache* cache = NavDataCache::instance();
530   
531   // find the entry matching the runway
532   SGPropertyNode* runwayNode, *ilsNode;
533   for (int i=0; (runwayNode = aRoot->getChild("runway", i)) != NULL; ++i) {
534     for (int j=0; (ilsNode = runwayNode->getChild("ils", j)) != NULL; ++j) {
535       // must match on both nav-ident and runway ident, to support the following:
536       // - runways with multiple distinct ILS installations (KEWD, for example)
537       // - runways where both ends share the same nav ident (LFAT, for example)
538       PositionedID ils = cache->findILS(guid(), ilsNode->getStringValue("rwy"),
539                                         ilsNode->getStringValue("nav-id"));
540       if (ils == 0) {
541         SG_LOG(SG_GENERAL, SG_INFO, "reading ILS data for " << ident() <<
542                ", couldn;t find runway/navaid for:" <<
543                ilsNode->getStringValue("rwy") << "/" <<
544                ilsNode->getStringValue("nav-id"));
545         continue;
546       }
547       
548       double hdgDeg = ilsNode->getDoubleValue("hdg-deg"),
549         lon = ilsNode->getDoubleValue("lon"),
550         lat = ilsNode->getDoubleValue("lat"),
551         elevM = ilsNode->getDoubleValue("elev-m");
552  
553       cache->updateILS(ils, SGGeod::fromDegM(lon, lat, elevM), hdgDeg);
554     } // of ILS iteration
555   } // of runway iteration
556 }
557
558 void FGAirport::addSID(flightgear::SID* aSid)
559 {
560   mSIDs.push_back(aSid);
561 }
562
563 void FGAirport::addSTAR(STAR* aStar)
564 {
565   mSTARs.push_back(aStar);
566 }
567
568 void FGAirport::addApproach(Approach* aApp)
569 {
570   mApproaches.push_back(aApp);
571 }
572
573 unsigned int FGAirport::numSIDs() const
574 {
575   loadProcedures();
576   return mSIDs.size();
577 }
578
579 flightgear::SID* FGAirport::getSIDByIndex(unsigned int aIndex) const
580 {
581   loadProcedures();
582   return mSIDs[aIndex];
583 }
584
585 flightgear::SID* FGAirport::findSIDWithIdent(const std::string& aIdent) const
586 {
587   loadProcedures();
588   for (unsigned int i=0; i<mSIDs.size(); ++i) {
589     if (mSIDs[i]->ident() == aIdent) {
590       return mSIDs[i];
591     }
592   }
593   
594   return NULL;
595 }
596
597 unsigned int FGAirport::numSTARs() const
598 {
599   loadProcedures();
600   return mSTARs.size();
601 }
602
603 STAR* FGAirport::getSTARByIndex(unsigned int aIndex) const
604 {
605   loadProcedures();
606   return mSTARs[aIndex];
607 }
608
609 STAR* FGAirport::findSTARWithIdent(const std::string& aIdent) const
610 {
611   loadProcedures();
612   for (unsigned int i=0; i<mSTARs.size(); ++i) {
613     if (mSTARs[i]->ident() == aIdent) {
614       return mSTARs[i];
615     }
616   }
617   
618   return NULL;
619 }
620
621 unsigned int FGAirport::numApproaches() const
622 {
623   loadProcedures();
624   return mApproaches.size();
625 }
626
627 Approach* FGAirport::getApproachByIndex(unsigned int aIndex) const
628 {
629   loadProcedures();
630   return mApproaches[aIndex];
631 }
632
633 Approach* FGAirport::findApproachWithIdent(const std::string& aIdent) const
634 {
635   loadProcedures();
636   for (unsigned int i=0; i<mApproaches.size(); ++i) {
637     if (mApproaches[i]->ident() == aIdent) {
638       return mApproaches[i];
639     }
640   }
641   
642   return NULL;
643 }
644
645 CommStationList
646 FGAirport::commStations() const
647 {
648   NavDataCache* cache = NavDataCache::instance();
649   CommStationList result;
650   BOOST_FOREACH(PositionedID pos, cache->airportItemsOfType(guid(),
651                                                             FGPositioned::FREQ_GROUND,
652                                                             FGPositioned::FREQ_UNICOM))
653   {
654     result.push_back((CommStation*) cache->loadById(pos));
655   }
656   
657   return result;
658 }
659
660 CommStationList
661 FGAirport::commStationsOfType(FGPositioned::Type aTy) const
662 {
663   NavDataCache* cache = NavDataCache::instance();
664   CommStationList result;
665   BOOST_FOREACH(PositionedID pos, cache->airportItemsOfType(guid(), aTy)) {
666     result.push_back((CommStation*) cache->loadById(pos));
667   }
668   
669   return result;
670 }
671
672 // get airport elevation
673 double fgGetAirportElev( const string& id )
674 {
675     const FGAirport *a=fgFindAirportID( id);
676     if (a) {
677         return a->getElevation();
678     } else {
679         return -9999.0;
680     }
681 }
682
683
684 // get airport position
685 SGGeod fgGetAirportPos( const string& id )
686 {
687     const FGAirport *a = fgFindAirportID( id);
688
689     if (a) {
690         return SGGeod::fromDegM(a->getLongitude(), a->getLatitude(), a->getElevation());
691     } else {
692         return SGGeod::fromDegM(0.0, 0.0, -9999.0);
693     }
694 }