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