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