]> git.mxchange.org Git - flightgear.git/blob - src/Airports/dynamics.cxx
Merge branch 'maint' into next
[flightgear.git] / src / Airports / dynamics.cxx
1 // dynamics.cxx - Code to manage the higher order airport ground activities
2 // Written by Durk Talsma, started December 2004.
3 //
4 //
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License as
7 // published by the Free Software Foundation; either version 2 of the
8 // License, or (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful, but
11 // WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 //
19 // $Id$
20
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24
25 #include <algorithm>
26
27 #include <simgear/compiler.h>
28
29 #include <plib/sg.h>
30 #include <plib/ul.h>
31
32 #include <Environment/environment_mgr.hxx>
33 #include <Environment/environment.hxx>
34 #include <simgear/misc/sg_path.hxx>
35 #include <simgear/props/props.hxx>
36 #include <simgear/structure/subsystem_mgr.hxx>
37 #include <simgear/debug/logstream.hxx>
38 #include <simgear/route/waypoint.hxx>
39 #include <Main/globals.hxx>
40 #include <Main/fg_props.hxx>
41 #include <Airports/runways.hxx>
42
43 #include <string>
44 #include <vector>
45
46 using std::string;
47 using std::vector;
48 using std::sort;
49 using std::random_shuffle;
50
51 #include "simple.hxx"
52 #include "dynamics.hxx"
53
54 FGAirportDynamics::FGAirportDynamics(FGAirport* ap) :
55   _ap(ap), rwyPrefs(ap) {
56   lastUpdate = 0;
57
58   // For testing only. This needs to be refined when we move ATIS functionality over.
59   atisInformation = "Sierra";
60 }
61
62 // Note that the ground network should also be copied
63 FGAirportDynamics::FGAirportDynamics(const FGAirportDynamics& other) :
64   rwyPrefs(other.rwyPrefs)
65 {
66   for (FGParkingVecConstIterator ip= other.parkings.begin(); ip != other.parkings.end(); ip++)
67     parkings.push_back(*(ip));
68   // rwyPrefs = other.rwyPrefs;
69   lastUpdate = other.lastUpdate;
70   
71   stringVecConstIterator il;
72   for (il = other.landing.begin(); il != other.landing.end(); il++)
73     landing.push_back(*il);
74   for (il = other.takeoff.begin(); il != other.takeoff.end(); il++)
75     takeoff.push_back(*il);
76   lastUpdate = other.lastUpdate;
77   atisInformation = other.atisInformation; 
78 }
79
80 // Destructor
81 FGAirportDynamics::~FGAirportDynamics()
82 {
83 }
84
85
86 // Initialization required after XMLRead
87 void FGAirportDynamics::init() 
88 {
89   // This may seem a bit weird to first randomly shuffle the parkings
90   // and then sort them again. However, parkings are sorted here by ascending 
91   // radius. Since many parkings have similar radii, with each radius class they will
92   // still be allocated relatively systematically. Randomizing prior to sorting will
93   // prevent any initial orderings to be destroyed, leading (hopefully) to a more 
94   // naturalistic gate assignment. 
95   random_shuffle(parkings.begin(), parkings.end());
96   sort(parkings.begin(), parkings.end());
97   // add the gate positions to the ground network. 
98   groundNetwork.addNodes(&parkings);
99   groundNetwork.init();
100   groundNetwork.setTowerController(&towerController);
101   groundNetwork.setParent(_ap);
102 }
103
104 bool FGAirportDynamics::getAvailableParking(double *lat, double *lon, double *heading, int *gateId, double rad, const string &flType, const string &acType, const string &airline)
105 {
106   bool found = false;
107   bool available = false;
108   //string gateType;
109
110   FGParkingVecIterator i;
111 //   if (flType == "cargo")
112 //     {
113 //       gateType = "RAMP_CARGO";
114 //     }
115 //   else if (flType == "ga")
116 //     {
117 //       gateType = "RAMP_GA";
118 //     }
119 //   else gateType = "GATE";
120   
121   if (parkings.begin() == parkings.end())
122     {
123       //cerr << "Could not find parking spot at " << _ap->getId() << endl;
124       *lat = _ap->getLatitude();
125       *lon = _ap->getLongitude();
126       *heading = 0;
127       found = true;
128     }
129   else
130     {
131       // First try finding a parking with a designated airline code
132       for (i = parkings.begin(); !(i == parkings.end() || found); i++)
133         {
134           //cerr << "Gate Id: " << i->getIndex()
135           //     << " Type  : " << i->getType()
136           //     << " Codes : " << i->getCodes()
137           //     << " Radius: " << i->getRadius()
138           //     << " Name  : " << i->getName()
139           //     << " Available: " << i->isAvailable() << endl;
140           available = true;
141           // Taken by another aircraft
142           if (!(i->isAvailable()))
143             {
144               available = false;
145               continue;
146             }
147           // No airline codes, so skip
148           if (i->getCodes().empty())
149             {
150               available = false;
151               continue;
152             }
153           else // Airline code doesn't match
154             {
155               //cerr << "Code = " << airline << ": Codes " << i->getCodes();
156               if (i->getCodes().find(airline, 0) == string::npos)
157                 {
158                   available = false;
159                   //cerr << "Unavailable" << endl;
160                   continue;
161                 }
162               else
163                 {
164                   //cerr << "Available" << endl;
165                 }
166             }
167           // Type doesn't match
168           if (i->getType() != flType)
169             {
170               available = false;
171               continue;
172             }
173           // too small
174           if (i->getRadius() < rad)
175             {
176               available = false;
177               continue;
178             }
179           
180           if (available)
181             {
182               *lat     = i->getLatitude ();
183               *lon     = i->getLongitude();
184               *heading = i->getHeading  ();
185               *gateId  = i->getIndex    ();
186               i->setAvailable(false);
187               found = true;
188             }
189         }
190       // then try again for those without codes. 
191       for (i = parkings.begin(); !(i == parkings.end() || found); i++)
192         {
193           available = true;
194           if (!(i->isAvailable()))
195             {
196               available = false;
197               continue;
198             }
199           if (!(i->getCodes().empty()))
200             {
201               if ((i->getCodes().find(airline,0) == string::npos))
202                 {
203                     available = false;
204                     continue;
205                 }
206             }
207           if (i->getType() != flType)
208             {
209               available = false;
210               continue;
211             }
212               
213           if (i->getRadius() < rad)
214             {
215               available = false;
216               continue;
217             }
218           
219           if (available)
220             {
221               *lat     = i->getLatitude ();
222               *lon     = i->getLongitude();
223               *heading = i->getHeading  ();
224               *gateId  = i->getIndex    ();
225               i->setAvailable(false);
226               found = true;
227             }
228         }
229       // And finally once more if that didn't work. Now ignore the airline codes, as a last resort
230       for (i = parkings.begin(); !(i == parkings.end() || found); i++)
231         {
232           available = true;
233           if (!(i->isAvailable()))
234             {
235               available = false;
236               continue;
237             }
238           if (i->getType() != flType)
239             {
240               available = false;
241               continue;
242             }
243           
244           if (i->getRadius() < rad)
245             {
246               available = false;
247               continue;
248             }
249           
250           if (available)
251             {
252               *lat     = i->getLatitude ();
253               *lon     = i->getLongitude();
254               *heading = i->getHeading  ();
255               *gateId  = i->getIndex    ();
256               i->setAvailable(false);
257               found = true;
258             }
259         }
260     }
261   if (!found)
262     {
263       //cerr << "Traffic overflow at" << _ap->getId() 
264       //           << ". flType = " << flType 
265       //           << ". airline = " << airline 
266       //           << " Radius = " <<rad
267       //           << endl;
268       *lat = _ap->getLatitude();
269       *lon = _ap->getLongitude();
270       *heading = 0;
271       *gateId  = -1;
272       //exit(1);
273     }
274   return found;
275 }
276
277 void FGAirportDynamics::getParking (int id, double *lat, double* lon, double *heading)
278 {
279   if (id < 0)
280     {
281       *lat = _ap->getLatitude();
282       *lon = _ap->getLongitude();
283       *heading = 0;
284     }
285   else
286     {
287       FGParkingVecIterator i = parkings.begin();
288       for (i = parkings.begin(); i != parkings.end(); i++)
289         {
290           if (id == i->getIndex())
291             {
292               *lat     = i->getLatitude();
293               *lon     = i->getLongitude();
294               *heading = i->getHeading();
295             }
296         }
297     }
298
299
300 FGParking *FGAirportDynamics::getParking(int id) 
301
302     FGParkingVecIterator i = parkings.begin();
303     for (i = parkings.begin(); i != parkings.end(); i++)
304         {
305           if (id == i->getIndex()) {
306                return &(*i);
307           }
308         }
309     return 0;
310 }
311 string FGAirportDynamics::getParkingName(int id) 
312
313     FGParkingVecIterator i = parkings.begin();
314     for (i = parkings.begin(); i != parkings.end(); i++)
315         {
316           if (id == i->getIndex()) {
317                return i->getName();
318           }
319         }
320
321     return string("overflow");
322 }
323 void FGAirportDynamics::releaseParking(int id)
324 {
325   if (id >= 0)
326     {
327       
328       FGParkingVecIterator i = parkings.begin();
329       for (i = parkings.begin(); i != parkings.end(); i++)
330         {
331           if (id == i->getIndex())
332             {
333               i -> setAvailable(true);
334             }
335         }
336     }
337 }
338   
339 void FGAirportDynamics::setRwyUse(const FGRunwayPreference& ref)
340 {
341   rwyPrefs = ref;
342   //cerr << "Exiting due to not implemented yet" << endl;
343   //exit(1);
344 }
345
346 bool FGAirportDynamics::innerGetActiveRunway(const string &trafficType, int action, string &runway)
347 {
348 double windSpeed;
349   double windHeading;
350   double maxTail;
351   double maxCross;
352   string name;
353   string type;
354
355   if (!rwyPrefs.available()) {
356     return false;
357   }
358   
359   RunwayGroup *currRunwayGroup = 0;
360   int nrActiveRunways = 0;
361   time_t dayStart = fgGetLong("/sim/time/utc/day-seconds");
362   if ((abs((long)(dayStart - lastUpdate)) > 600) || trafficType != prevTrafficType)
363         {
364           landing.clear();
365           takeoff.clear();
366           lastUpdate = dayStart;
367           prevTrafficType = trafficType;
368
369           FGEnvironment 
370             stationweather = ((FGEnvironmentMgr *) globals->get_subsystem("environment"))
371             ->getEnvironment(getLatitude(), 
372                              getLongitude(), 
373                              getElevation());
374           
375           windSpeed = stationweather.get_wind_speed_kt();
376           windHeading = stationweather.get_wind_from_heading_deg();
377           string scheduleName;
378           //cerr << "finding active Runway for" << _ap->getId() << endl;
379           //cerr << "Nr of seconds since day start << " << dayStart << endl;
380
381           ScheduleTime *currSched;
382           //cerr << "A"<< endl;
383           currSched = rwyPrefs.getSchedule(trafficType.c_str());
384           if (!(currSched))
385             return false;
386           //cerr << "B"<< endl;
387           scheduleName = currSched->getName(dayStart);
388           maxTail  = currSched->getTailWind  ();
389           maxCross = currSched->getCrossWind ();
390           //cerr << "SChedule anme = " << scheduleName << endl;
391           if (scheduleName.empty())
392             return false;
393           //cerr << "C"<< endl;
394           currRunwayGroup = rwyPrefs.getGroup(scheduleName); 
395           //cerr << "D"<< endl;
396           if (!(currRunwayGroup))
397             return false;
398           nrActiveRunways = currRunwayGroup->getNrActiveRunways();
399
400         // Keep a history of the currently active runways, to ensure
401         // that an already established selection of runways will not
402         // be overridden once a more preferred selection becomes 
403         // available as that can lead to random runway swapping.
404         if (trafficType == "com") {
405           currentlyActive = &comActive;
406         } else if (trafficType == "gen") {
407           currentlyActive = &genActive;
408         } else if (trafficType == "mil") {
409           currentlyActive = &milActive;
410         } else if (trafficType == "ul") {
411           currentlyActive = &ulActive;
412         }
413           // 
414           currRunwayGroup->setActive(_ap, 
415                                      windSpeed, 
416                                      windHeading, 
417                                      maxTail, 
418                                      maxCross, 
419                                      currentlyActive); 
420
421           // Note that I SHOULD keep multiple lists in memory, one for 
422           // general aviation, one for commercial and one for military
423           // traffic.
424           currentlyActive->clear();
425           nrActiveRunways = currRunwayGroup->getNrActiveRunways();
426           //cerr << "Choosing runway for " << trafficType << endl;
427           for (int i = 0; i < nrActiveRunways; i++)
428             {
429               type = "unknown"; // initialize to something other than landing or takeoff
430               currRunwayGroup->getActive(i, name, type);
431               if (type == "landing")
432                 {
433                   landing.push_back(name);
434                   currentlyActive->push_back(name);
435                   //cerr << "Landing " << name << endl; 
436                 }
437               if (type == "takeoff")
438                 {
439                   takeoff.push_back(name);
440                   currentlyActive->push_back(name);
441                   //cerr << "takeoff " << name << endl;
442                 }
443             }
444           //cerr << endl;
445         }
446   
447   if (action == 1) // takeoff 
448         {
449           int nr = takeoff.size();
450           if (nr)
451             {
452               // Note that the randomization below, is just a placeholder to choose between
453               // multiple active runways for this action. This should be
454               // under ATC control.
455               runway = takeoff[(rand() %  nr)];
456             }
457           else
458             { // Fallback
459               runway = chooseRunwayFallback();
460             }
461         } 
462   
463   if (action == 2) // landing
464         {
465           int nr = landing.size();
466           if (nr)
467             {
468               runway = landing[(rand() % nr)];
469             }
470           else
471             {  //fallback
472                runway = chooseRunwayFallback();
473             }
474         } 
475
476   return true;
477 }
478
479 void FGAirportDynamics::getActiveRunway(const string &trafficType, int action, string &runway)
480 {
481   bool ok = innerGetActiveRunway(trafficType, action, runway);
482   if (!ok) {
483     runway = chooseRunwayFallback();
484   }
485 }
486
487 string FGAirportDynamics::chooseRunwayFallback()
488 {   
489   FGRunway* rwy = _ap->getActiveRunwayForUsage();
490   return rwy->ident();
491 }
492
493 void FGAirportDynamics::addParking(FGParking& park) {
494   parkings.push_back(park);
495 }
496
497 double FGAirportDynamics::getLatitude() const {
498   return _ap->getLatitude();
499 }
500
501 double FGAirportDynamics::getLongitude() const {
502   return _ap->getLongitude();
503 }
504
505 double FGAirportDynamics::getElevation() const {
506   return _ap->getElevation();
507 }
508
509 const string& FGAirportDynamics::getId() const {
510   return _ap->getId();
511 }
512
513 // Experimental: Return a different ground frequency depending on the leg of the
514 // Flight. Leg should always have a minimum value of two when this function is called. 
515 // Note that in this scheme, the assignment of various frequencies to various ground 
516 // operations is completely arbitrary. As such, is a short cut I need to take now,
517 // so that at least I can start working on assigning different frequencies to different
518 // operations.
519
520 int FGAirportDynamics::getGroundFrequency(int leg) { 
521      //return freqGround.size() ? freqGround[0] : 0; };
522      int groundFreq;
523      if (leg < 2) {
524          SG_LOG(SG_ATC, SG_ALERT, "Leg value is smaller than two at " << SG_ORIGIN);
525      }
526      if (freqGround.size() == 0) {
527          return 0;
528      }
529      if ((freqGround.size() >= leg-1) && (leg > 1)) {
530           groundFreq =  freqGround[leg-1];
531      }
532      if ((freqGround.size() < leg-1) && (leg > 1)) {
533           groundFreq = (freqGround.size() < (leg-2)) ? freqGround[freqGround.size()-1] : freqGround[leg-2];
534      }
535      if ((freqGround.size() >= leg-1) && (leg > 1)) {
536           groundFreq = freqGround[leg-2];
537      }
538     return groundFreq;
539 }