]> git.mxchange.org Git - flightgear.git/blob - src/Airports/simple.cxx
2ebfb8434579cd7f00f0838d4786ea4f7c958119
[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 <math.h>
32 #include <algorithm>
33
34 #include <simgear/compiler.h>
35
36 #include <plib/sg.h>
37 #include <plib/ul.h>
38
39 #include <Environment/environment_mgr.hxx>
40 #include <Environment/environment.hxx>
41 #include <simgear/misc/sg_path.hxx>
42 #include <simgear/props/props.hxx>
43 #include <simgear/structure/subsystem_mgr.hxx>
44 //#include <simgear/route/waypoint.hxx>
45 #include <simgear/debug/logstream.hxx>
46 #include <Main/globals.hxx>
47 #include <Main/fg_props.hxx>
48 #include <Airports/runways.hxx>
49 #include <Airports/dynamics.hxx>
50
51 #include <string>
52
53 #include "simple.hxx"
54 #include "xmlloader.hxx"
55
56 using std::sort;
57 using std::random_shuffle;
58
59
60
61
62 /***************************************************************************
63  * FGAirport
64  ***************************************************************************/
65 FGAirport::FGAirport() : _dynamics(0)
66 {
67 }
68
69 FGAirport::FGAirport(const string &id, const SGGeod& location, const SGGeod& tower_location,
70         const string &name, bool has_metar, bool is_airport, bool is_seaport,
71         bool is_heliport) :
72     _id(id),
73     _location(location),
74     _tower_location(tower_location),
75     _name(name),
76     _has_metar(has_metar),
77     _is_airport(is_airport),
78     _is_seaport(is_seaport),
79     _is_heliport(is_heliport),
80     _dynamics(0)
81 {
82 }
83
84
85 FGAirport::~FGAirport()
86 {
87     delete _dynamics;
88 }
89
90
91 FGAirportDynamics * FGAirport::getDynamics()
92 {
93     if (_dynamics != 0) {
94         return _dynamics;
95     } else {
96         //cerr << "Trying to load dynamics for " << _id << endl;
97         _dynamics = new FGAirportDynamics(this);
98         XMLLoader::load(_dynamics);
99
100         FGRunwayPreference rwyPrefs(this);
101         XMLLoader::load(&rwyPrefs);
102         _dynamics->setRwyUse(rwyPrefs);
103    }
104     return _dynamics;
105 }
106
107 unsigned int FGAirport::numRunways() const
108 {
109   return mRunways.size();
110 }
111
112 FGRunway FGAirport::getRunwayByIndex(unsigned int aIndex) const
113 {
114   assert(aIndex >= 0 && aIndex < mRunways.size());
115   return mRunways[aIndex];
116 }
117
118 bool FGAirport::hasRunwayWithIdent(const string& aIdent) const
119 {
120   bool dummy;
121   return (getIteratorForRunwayIdent(aIdent, dummy) != mRunways.end());
122 }
123
124 FGRunway FGAirport::getRunwayByIdent(const string& aIdent) const
125 {
126   bool reversed;
127   FGRunwayVector::const_iterator it = getIteratorForRunwayIdent(aIdent, reversed);
128   if (it == mRunways.end()) {
129     SG_LOG(SG_GENERAL, SG_ALERT, "no such runway '" << aIdent << "' at airport " << _id);
130     throw sg_range_exception("unknown runway " + aIdent + " at airport:" + _id, "FGAirport::getRunwayByIdent");
131   }
132   
133   if (!reversed) {
134     return *it;
135   }
136
137   FGRunway result(*it);
138   result._heading += 180.0;
139   result._rwy_no = FGRunway::reverseIdent(it->_rwy_no);
140   return result;
141 }
142
143 FGRunwayVector::const_iterator
144 FGAirport::getIteratorForRunwayIdent(const string& aIdent, bool& aReversed) const
145 {
146   string ident(aIdent);
147   if ((aIdent.size() == 1) || !isdigit(aIdent[1])) {
148     ident = "0" + aIdent;
149   }
150
151   string reversedRunway = FGRunway::reverseIdent(ident);
152   FGRunwayVector::const_iterator it = mRunways.begin();
153   
154   for (; it != mRunways.end(); ++it) {
155     if (it->_rwy_no == ident) {
156       aReversed = false;
157       return it;
158     }
159     
160     if (it->_rwy_no == reversedRunway) {
161       aReversed = true;
162       return it;
163     }
164   }
165
166   return it; // end()
167 }
168
169 static double normaliseBearing(double aBearing)
170 {
171   while (aBearing < 0.0) {
172     aBearing += 360.0;
173   }
174   
175   while (aBearing > 360.0) {
176     aBearing -= 360.0;
177   }
178   
179   return aBearing;
180 }
181
182 FGRunway FGAirport::findBestRunwayForHeading(double aHeading) const
183 {
184   FGRunwayVector::const_iterator it = mRunways.begin();
185   FGRunway result;
186   double currentBestQuality = 0.0;
187   
188   SGPropertyNode *param = fgGetNode("/sim/airport/runways/search", true);
189   double lengthWeight = param->getDoubleValue("length-weight", 0.01);
190   double widthWeight = param->getDoubleValue("width-weight", 0.01);
191   double surfaceWeight = param->getDoubleValue("surface-weight", 10);
192   double deviationWeight = param->getDoubleValue("deviation-weight", 1);
193     
194   for (; it != mRunways.end(); ++it) {
195     double good = it->score(lengthWeight, widthWeight, surfaceWeight);
196     
197     // first side
198     double dev = normaliseBearing(aHeading - it->_heading);
199     double bad = fabs(deviationWeight * dev) + 1e-20;
200     double quality = good / bad;
201     
202     if (quality > currentBestQuality) {
203       currentBestQuality = quality;
204       result = *it;
205     }
206     
207     dev = normaliseBearing(aHeading - it->_heading - 180.0);
208     bad = fabs(deviationWeight * dev) + 1e-20;
209     quality = good / bad;
210     
211     if (quality > currentBestQuality) {
212       currentBestQuality = quality;
213       result = *it;
214       result._heading += 180.0;
215       result._rwy_no = FGRunway::reverseIdent(it->_rwy_no);
216     }
217   }
218
219   return result;
220 }
221
222 unsigned int FGAirport::numTaxiways() const
223 {
224   return mTaxiways.size();
225 }
226
227 FGRunway FGAirport::getTaxiwayByIndex(unsigned int aIndex) const
228 {
229   assert(aIndex >= 0 && aIndex < mTaxiways.size());
230   return mTaxiways[aIndex];
231 }
232
233 void FGAirport::addRunway(const FGRunway& aRunway)
234 {
235   if (aRunway.isTaxiway()) {
236     mTaxiways.push_back(aRunway);
237   } else {
238     mRunways.push_back(aRunway);
239   }
240 }
241
242 FGRunway FGAirport::getActiveRunwayForUsage() const
243 {
244   static FGEnvironmentMgr* envMgr = NULL;
245   if (!envMgr) {
246     envMgr = (FGEnvironmentMgr *) globals->get_subsystem("environment");
247   }
248   
249   FGEnvironment stationWeather(envMgr->getEnvironment(_location));
250   
251   double windSpeed = stationWeather.get_wind_speed_kt();
252   double hdg = stationWeather.get_wind_from_heading_deg();
253   if (windSpeed <= 0.0) {
254     hdg = 270;  // This forces West-facing rwys to be used in no-wind situations
255     // which is consistent with Flightgear's initial setup.
256   }
257   
258   return findBestRunwayForHeading(hdg);
259 }
260
261 /******************************************************************************
262  * FGAirportList
263  *****************************************************************************/
264
265 // Populates a list of subdirectories of $FG_ROOT/Airports/AI so that
266 // the add() method doesn't have to try opening 2 XML files in each of
267 // thousands of non-existent directories.  FIXME: should probably add
268 // code to free this list after parsing of apt.dat is finished;
269 // non-issue at the moment, however, as there are no AI subdirectories
270 // in the base package.
271 //
272 // Note: 2005/12/23: This is probably not necessary anymore, because I'm
273 // Switching to runtime airport dynamics loading (DT).
274 FGAirportList::FGAirportList()
275 {
276 //     ulDir* d;
277 //     ulDirEnt* dent;
278 //     SGPath aid( globals->get_fg_root() );
279 //     aid.append( "/Airports/AI" );
280 //     if((d = ulOpenDir(aid.c_str())) == NULL)
281 //         return;
282 //     while((dent = ulReadDir(d)) != NULL) {
283 //         SG_LOG( SG_GENERAL, SG_DEBUG, "Dent: " << dent->d_name );
284 //         ai_dirs.insert(dent->d_name);
285 //     }
286 //     ulCloseDir(d);
287 }
288
289
290 FGAirportList::~FGAirportList( void )
291 {
292     for (unsigned int i = 0; i < airports_array.size(); ++i) {
293         delete airports_array[i];
294     }
295 }
296
297
298 // add an entry to the list
299 FGAirport* FGAirportList::add( const string &id, const SGGeod& location, const SGGeod& tower_location,
300                          const string &name, bool has_metar, bool is_airport, bool is_seaport,
301                          bool is_heliport)
302 {
303     FGAirport* a = new FGAirport(id, location, tower_location, name, has_metar,
304             is_airport, is_seaport, is_heliport);
305
306     airports_by_id[a->getId()] = a;
307     // try and read in an auxilary file
308
309     airports_array.push_back( a );
310     SG_LOG( SG_GENERAL, SG_BULK, "Adding " << id << " pos = " << location.getLongitudeDeg()
311             << ", " << location.getLatitudeDeg() << " elev = " << location.getElevationFt() );
312             
313     return a;
314 }
315
316
317 // search for the specified id
318 FGAirport* FGAirportList::search( const string& id)
319 {
320     airport_map_iterator itr = airports_by_id.find(id);
321     return (itr == airports_by_id.end() ? NULL : itr->second);
322 }
323
324 // wrap an FGIdentOrdering in an STL-compatible functor. not the most
325 // efficent / pretty thing in the world, but avoids template nastiness in the 
326 // headers, and we're only doing O(log(N)) comparisoms per search
327 class orderingFunctor
328 {
329 public:
330   orderingFunctor(FGIdentOrdering* aOrder) :
331     mOrdering(aOrder)
332   { assert(aOrder); }
333   
334   bool operator()(const airport_map::value_type& aA, const std::string& aB) const
335   {
336     return mOrdering->compare(aA.first,aB);
337   }
338
339   bool operator()(const std::string& aA, const airport_map::value_type& aB) const
340   {
341     return mOrdering->compare(aA, aB.first);
342   }
343
344   bool operator()(const airport_map::value_type& aA, const airport_map::value_type& aB) const
345   {
346     return mOrdering->compare(aA.first, aB.first);
347   }
348   
349 private:
350   FGIdentOrdering* mOrdering;
351 };
352
353 const FGAirport* FGAirportList::findFirstById(const std::string& aIdent, FGIdentOrdering* aOrder)
354 {
355   airport_map_iterator itr;
356   if (aOrder) {
357     orderingFunctor func(aOrder);
358     itr = std::lower_bound(airports_by_id.begin(),airports_by_id.end(), aIdent, func);
359   } else {
360     itr = airports_by_id.lower_bound(aIdent);
361   }
362   
363   if (itr == airports_by_id.end()) {
364     return NULL;
365   }
366   
367   return itr->second;
368 }
369
370 // search for the airport nearest the specified position
371 FGAirport* FGAirportList::search(double lon_deg, double lat_deg, double max_range)
372 {
373     static FGAirportSearchFilter accept_any;
374     return search(lon_deg, lat_deg, max_range, accept_any);
375 }
376
377
378 // search for the airport nearest the specified position and
379 // passing the filter
380 FGAirport* FGAirportList::search(double lon_deg, double lat_deg,
381         double max_range,
382         FGAirportSearchFilter& filter)
383 {
384     double min_dist = max_range;
385
386     airport_list_iterator it = airports_array.begin();
387     airport_list_iterator end = airports_array.end();
388     airport_list_iterator closest = end;
389     for (; it != end; ++it) {
390         if (!filter.pass(*it))
391             continue;
392
393         // crude manhatten distance based on lat/lon difference
394         double d = fabs(lon_deg - (*it)->getLongitude())
395                 + fabs(lat_deg - (*it)->getLatitude());
396         if (d < min_dist) {
397             closest = it;
398             min_dist = d;
399         }
400     }
401     return closest != end ? *closest : 0;
402 }
403
404
405 int
406 FGAirportList::size () const
407 {
408     return airports_array.size();
409 }
410
411
412 const FGAirport *FGAirportList::getAirport( unsigned int index ) const
413 {
414     if (index < airports_array.size()) {
415         return(airports_array[index]);
416     } else {
417         return(NULL);
418     }
419 }
420
421
422 /**
423  * Mark the specified airport record as not having metar
424  */
425 void FGAirportList::no_metar( const string &id )
426 {
427     if(airports_by_id.find(id) != airports_by_id.end()) {
428         airports_by_id[id]->setMetar(false);
429     }
430 }
431
432
433 /**
434  * Mark the specified airport record as (yes) having metar
435  */
436 void FGAirportList::has_metar( const string &id )
437 {
438     if(airports_by_id.find(id) != airports_by_id.end()) {
439         airports_by_id[id]->setMetar(true);
440     }
441 }
442
443
444 // find basic airport location info from airport database
445 const FGAirport *fgFindAirportID( const string& id)
446 {
447     const FGAirport* result = NULL;
448     if ( id.length() ) {
449         SG_LOG( SG_GENERAL, SG_BULK, "Searching for airport code = " << id );
450
451         result = globals->get_airports()->search( id );
452
453         if ( result == NULL ) {
454             SG_LOG( SG_GENERAL, SG_ALERT,
455                     "Failed to find " << id << " in apt.dat.gz" );
456             return NULL;
457         }
458     } else {
459         return NULL;
460     }
461     SG_LOG( SG_GENERAL, SG_BULK,
462             "Position for " << id << " is ("
463             << result->getLongitude() << ", "
464             << result->getLatitude() << ")" );
465
466     return result;
467 }
468
469
470 // get airport elevation
471 double fgGetAirportElev( const string& id )
472 {
473     SG_LOG( SG_GENERAL, SG_BULK,
474             "Finding elevation for airport: " << id );
475
476     const FGAirport *a=fgFindAirportID( id);
477     if (a) {
478         return a->getElevation();
479     } else {
480         return -9999.0;
481     }
482 }
483
484
485 // get airport position
486 Point3D fgGetAirportPos( const string& id )
487 {
488     SG_LOG( SG_ATC, SG_BULK,
489             "Finding position for airport: " << id );
490
491     const FGAirport *a = fgFindAirportID( id);
492
493     if (a) {
494         return Point3D(a->getLongitude(), a->getLatitude(), a->getElevation());
495     } else {
496         return Point3D(0.0, 0.0, -9999.0);
497     }
498 }