]> git.mxchange.org Git - flightgear.git/blob - src/Airports/dynamics.cxx
b4816611c0d61d0ae951c1164dd003f23100ee72
[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 #include <simgear/xml/easyxml.hxx>
43
44 #include STL_STRING
45 #include <vector>
46
47 SG_USING_STD(string);
48 SG_USING_STD(vector);
49 SG_USING_STD(sort);
50 SG_USING_STD(random_shuffle);
51
52 #include "parking.hxx"
53 #include "groundnetwork.hxx"
54 #include "runwayprefs.hxx"
55 #include "dynamics.hxx"
56
57 /********** FGAirport Dynamics *********************************************/
58
59 FGAirportDynamics::FGAirportDynamics(double lat, double lon, double elev, string id) :
60   _longitude(lon),
61   _latitude(lat),
62   _elevation(elev),
63   _id(id)
64 {
65   lastUpdate = 0;
66   for (int i = 0; i < 10; i++)
67     {
68       avWindHeading [i] = 0;
69       avWindSpeed   [i] = 0;
70     }
71 }
72
73
74 // Note that the ground network should also be copied
75 FGAirportDynamics::FGAirportDynamics(const FGAirportDynamics& other) 
76 {
77   for (FGParkingVecConstIterator ip= other.parkings.begin(); ip != other.parkings.end(); ip++)
78     parkings.push_back(*(ip));
79   rwyPrefs = other.rwyPrefs;
80   lastUpdate = other.lastUpdate;
81   
82   stringVecConstIterator il;
83   for (il = other.landing.begin(); il != other.landing.end(); il++)
84     landing.push_back(*il);
85   for (il = other.takeoff.begin(); il != other.takeoff.end(); il++)
86     takeoff.push_back(*il);
87   lastUpdate = other.lastUpdate;
88   for (int i = 0; i < 10; i++)
89     {
90       avWindHeading [i] = other.avWindHeading[i];
91       avWindSpeed   [i] = other.avWindSpeed  [i];
92     }
93 }
94
95 // Destructor
96 FGAirportDynamics::~FGAirportDynamics()
97 {
98   
99 }
100
101
102 // Initialization required after XMLRead
103 void FGAirportDynamics::init() 
104 {
105   // This may seem a bit weird to first randomly shuffle the parkings
106   // and then sort them again. However, parkings are sorted here by ascending 
107   // radius. Since many parkings have similar radii, with each radius class they will
108   // still be allocated relatively systematically. Randomizing prior to sorting will
109   // prevent any initial orderings to be destroyed, leading (hopefully) to a more 
110   // naturalistic gate assignment. 
111   random_shuffle(parkings.begin(), parkings.end());
112   sort(parkings.begin(), parkings.end());
113   // add the gate positions to the ground network. 
114   groundNetwork.addNodes(&parkings);
115   groundNetwork.init();
116 }
117
118 bool FGAirportDynamics::getAvailableParking(double *lat, double *lon, double *heading, int *gateId, double rad, const string &flType, const string &acType, const string &airline)
119 {
120   bool found = false;
121   bool available = false;
122   //string gateType;
123
124   FGParkingVecIterator i;
125 //   if (flType == "cargo")
126 //     {
127 //       gateType = "RAMP_CARGO";
128 //     }
129 //   else if (flType == "ga")
130 //     {
131 //       gateType = "RAMP_GA";
132 //     }
133 //   else gateType = "GATE";
134   
135   if (parkings.begin() == parkings.end())
136     {
137       //cerr << "Could not find parking spot at " << _id << endl;
138       *lat = _latitude;
139       *lon = _longitude;
140       *heading = 0;
141       found = true;
142     }
143   else
144     {
145       // First try finding a parking with a designated airline code
146       for (i = parkings.begin(); !(i == parkings.end() || found); i++)
147         {
148           //cerr << "Gate Id: " << i->getIndex()
149           //     << " Type  : " << i->getType()
150           //     << " Codes : " << i->getCodes()
151           //     << " Radius: " << i->getRadius()
152           //     << " Name  : " << i->getName()
153           //     << " Available: " << i->isAvailable() << endl;
154           available = true;
155           // Taken by another aircraft
156           if (!(i->isAvailable()))
157             {
158               available = false;
159               continue;
160             }
161           // No airline codes, so skip
162           if (i->getCodes().empty())
163             {
164               available = false;
165               continue;
166             }
167           else // Airline code doesn't match
168             if (i->getCodes().find(airline, 0) == string::npos)
169               {
170                 available = false;
171                 continue;
172               }
173           // Type doesn't match
174           if (i->getType() != flType)
175             {
176               available = false;
177               continue;
178             }
179           // too small
180           if (i->getRadius() < rad)
181             {
182               available = false;
183               continue;
184             }
185           
186           if (available)
187             {
188               *lat     = i->getLatitude ();
189               *lon     = i->getLongitude();
190               *heading = i->getHeading  ();
191               *gateId  = i->getIndex    ();
192               i->setAvailable(false);
193               found = true;
194             }
195         }
196       // then try again for those without codes. 
197       for (i = parkings.begin(); !(i == parkings.end() || found); i++)
198         {
199           available = true;
200           if (!(i->isAvailable()))
201             {
202               available = false;
203               continue;
204             }
205           if (!(i->getCodes().empty()))
206             {
207               if ((i->getCodes().find(airline,0) == string::npos))
208           {
209             available = false;
210             continue;
211           }
212             }
213           if (i->getType() != flType)
214             {
215               available = false;
216               continue;
217             }
218               
219           if (i->getRadius() < rad)
220             {
221               available = false;
222               continue;
223             }
224           
225           if (available)
226             {
227               *lat     = i->getLatitude ();
228               *lon     = i->getLongitude();
229               *heading = i->getHeading  ();
230               *gateId  = i->getIndex    ();
231               i->setAvailable(false);
232               found = true;
233             }
234         } 
235       // And finally once more if that didn't work. Now ignore the airline codes, as a last resort
236       for (i = parkings.begin(); !(i == parkings.end() || found); i++)
237         {
238           available = true;
239           if (!(i->isAvailable()))
240             {
241               available = false;
242               continue;
243             }
244           if (i->getType() != flType)
245             {
246               available = false;
247               continue;
248             }
249           
250           if (i->getRadius() < rad)
251             {
252               available = false;
253               continue;
254             }
255           
256           if (available)
257             {
258               *lat     = i->getLatitude ();
259               *lon     = i->getLongitude();
260               *heading = i->getHeading  ();
261               *gateId  = i->getIndex    ();
262               i->setAvailable(false);
263               found = true;
264             }
265         }
266     }
267   if (!found)
268     {
269       //cerr << "Traffic overflow at" << _id 
270       //           << ". flType = " << flType 
271       //           << ". airline = " << airline 
272       //           << " Radius = " <<rad
273       //           << endl;
274       *lat = _latitude;
275       *lon = _longitude;
276       *heading = 0;
277       *gateId  = -1;
278       //exit(1);
279     }
280   return found;
281 }
282
283 void FGAirportDynamics::getParking (int id, double *lat, double* lon, double *heading)
284 {
285   if (id < 0)
286     {
287       *lat = _latitude;
288       *lon = _longitude;
289       *heading = 0;
290     }
291   else
292     {
293       FGParkingVecIterator i = parkings.begin();
294       for (i = parkings.begin(); i != parkings.end(); i++)
295         {
296           if (id == i->getIndex())
297             {
298               *lat     = i->getLatitude();
299               *lon     = i->getLongitude();
300               *heading = i->getHeading();
301             }
302         }
303     }
304
305
306 FGParking *FGAirportDynamics::getParking(int i) 
307
308   if (i < (int)parkings.size()) 
309     return &(parkings[i]); 
310   else 
311     return 0;
312 }
313 string FGAirportDynamics::getParkingName(int i) 
314
315   if (i < (int)parkings.size() && i >= 0) 
316     return (parkings[i].getName()); 
317   else 
318     return string("overflow");
319 }
320 void FGAirportDynamics::releaseParking(int id)
321 {
322   if (id >= 0)
323     {
324       
325       FGParkingVecIterator i = parkings.begin();
326       for (i = parkings.begin(); i != parkings.end(); i++)
327         {
328           if (id == i->getIndex())
329             {
330               i -> setAvailable(true);
331             }
332         }
333     }
334 }
335   
336 void  FGAirportDynamics::startXML () {
337   //cout << "Start XML" << endl;
338 }
339
340 void  FGAirportDynamics::endXML () {
341   //cout << "End XML" << endl;
342 }
343
344 void  FGAirportDynamics::startElement (const char * name, const XMLAttributes &atts) {
345   // const char *attval;
346   FGParking park;
347   FGTaxiNode taxiNode;
348   FGTaxiSegment taxiSegment;
349   int index = 0;
350   taxiSegment.setIndex(index);
351   //cout << "Start element " << name << endl;
352   string attname;
353   string value;
354   string gateName;
355   string gateNumber;
356   string lat;
357   string lon;
358   if (name == string("Parking"))
359     {
360       for (int i = 0; i < atts.size(); i++)
361         {
362           //cout << "  " << atts.getName(i) << '=' << atts.getValue(i) << endl; 
363           attname = atts.getName(i);
364           if (attname == string("index"))
365             park.setIndex(atoi(atts.getValue(i)));
366           else if (attname == string("type"))
367             park.setType(atts.getValue(i));
368          else if (attname == string("name"))
369            gateName = atts.getValue(i);
370           else if (attname == string("number"))
371             gateNumber = atts.getValue(i);
372           else if (attname == string("lat"))
373            park.setLatitude(atts.getValue(i));
374           else if (attname == string("lon"))
375             park.setLongitude(atts.getValue(i)); 
376           else if (attname == string("heading"))
377             park.setHeading(atof(atts.getValue(i)));
378           else if (attname == string("radius")) {
379             string radius = atts.getValue(i);
380             if (radius.find("M") != string::npos)
381               radius = radius.substr(0, radius.find("M",0));
382             //cerr << "Radius " << radius <<endl;
383             park.setRadius(atof(radius.c_str()));
384           }
385            else if (attname == string("airlineCodes"))
386              park.setCodes(atts.getValue(i));
387         }
388       park.setName((gateName+gateNumber));
389       parkings.push_back(park);
390     }
391   if (name == string("node")) 
392     {
393       for (int i = 0; i < atts.size() ; i++)
394         {
395           attname = atts.getName(i);
396           if (attname == string("index"))
397             taxiNode.setIndex(atoi(atts.getValue(i)));
398           if (attname == string("lat"))
399             taxiNode.setLatitude(atts.getValue(i));
400           if (attname == string("lon"))
401             taxiNode.setLongitude(atts.getValue(i));
402         }
403       groundNetwork.addNode(taxiNode);
404     }
405   if (name == string("arc")) 
406     {
407       taxiSegment.setIndex(++index);
408       for (int i = 0; i < atts.size() ; i++)
409         {
410           attname = atts.getName(i);
411           if (attname == string("begin"))
412             taxiSegment.setStartNodeRef(atoi(atts.getValue(i)));
413           if (attname == string("end"))
414             taxiSegment.setEndNodeRef(atoi(atts.getValue(i)));
415         }
416       groundNetwork.addSegment(taxiSegment);
417     }
418   // sort by radius, in asending order, so that smaller gates are first in the list
419 }
420
421 void  FGAirportDynamics::endElement (const char * name) {
422   //cout << "End element " << name << endl;
423
424 }
425
426 void  FGAirportDynamics::data (const char * s, int len) {
427   string token = string(s,len);
428   //cout << "Character data " << string(s,len) << endl;
429   //if ((token.find(" ") == string::npos && (token.find('\n')) == string::npos))
430     //value += token;
431   //else
432     //value = string("");
433 }
434
435 void  FGAirportDynamics::pi (const char * target, const char * data) {
436   //cout << "Processing instruction " << target << ' ' << data << endl;
437 }
438
439 void  FGAirportDynamics::warning (const char * message, int line, int column) {
440   SG_LOG(SG_IO, SG_WARN, "Warning: " << message << " (" << line << ',' << column << ')');
441 }
442
443 void  FGAirportDynamics::error (const char * message, int line, int column) {
444   SG_LOG(SG_IO, SG_ALERT, "Error: " << message << " (" << line << ',' << column << ')');
445 }
446
447 void FGAirportDynamics::setRwyUse(const FGRunwayPreference& ref)
448 {
449   rwyPrefs = ref;
450   //cerr << "Exiting due to not implemented yet" << endl;
451   //exit(1);
452 }
453 void FGAirportDynamics::getActiveRunway(const string &trafficType, int action, string &runway)
454 {
455   double windSpeed;
456   double windHeading;
457   double maxTail;
458   double maxCross;
459   string name;
460   string type;
461
462   if (!(rwyPrefs.available()))
463     {
464       runway = chooseRunwayFallback();
465       return; // generic fall back goes here
466     }
467   else
468     {
469       RunwayGroup *currRunwayGroup = 0;
470       int nrActiveRunways = 0;
471       time_t dayStart = fgGetLong("/sim/time/utc/day-seconds");
472       if (((dayStart - lastUpdate) > 600) || trafficType != prevTrafficType)
473         {
474           landing.clear();
475           takeoff.clear();
476           //lastUpdate = dayStart;
477           prevTrafficType = trafficType;
478
479           FGEnvironment 
480             stationweather = ((FGEnvironmentMgr *) globals->get_subsystem("environment"))
481             ->getEnvironment(getLatitude(), 
482                              getLongitude(), 
483                              getElevation());
484           
485           windSpeed = stationweather.get_wind_speed_kt();
486           windHeading = stationweather.get_wind_from_heading_deg();
487          //  double averageWindSpeed   = 0;
488 //        double averageWindHeading = 0;
489 //        double cosHeading         = 0;
490 //        double sinHeading         = 0;
491 //        // Initialize at the beginning of the next day or startup
492 //        if ((lastUpdate == 0) || (dayStart < lastUpdate))
493 //          {
494 //            for (int i = 0; i < 10; i++)
495 //              {
496 //                avWindHeading [i] = windHeading;
497 //                avWindSpeed   [i] = windSpeed;
498 //              }
499 //          }
500 //        else
501 //          {
502 //            if (windSpeed != avWindSpeed[9]) // update if new metar data 
503 //              {
504 //                // shift the running average
505 //                for (int i = 0; i < 9 ; i++)
506 //                  {
507 //                    avWindHeading[i] = avWindHeading[i+1];
508 //                    avWindSpeed  [i] = avWindSpeed  [i+1];
509 //                  }
510 //              } 
511 //            avWindHeading[9] = windHeading;
512 //            avWindSpeed  [9] = windSpeed;
513 //          }
514           
515 //        for (int i = 0; i < 10; i++)
516 //          {
517 //            averageWindSpeed   += avWindSpeed   [i];
518 //            //averageWindHeading += avWindHeading [i];
519 //            cosHeading += cos(avWindHeading[i] * SG_DEGREES_TO_RADIANS);
520 //            sinHeading += sin(avWindHeading[i] * SG_DEGREES_TO_RADIANS);
521 //          }
522 //        averageWindSpeed   /= 10;
523 //        //averageWindHeading /= 10;
524 //        cosHeading /= 10;
525 //        sinHeading /= 10;
526 //        averageWindHeading = atan2(sinHeading, cosHeading) *SG_RADIANS_TO_DEGREES;
527 //        if (averageWindHeading < 0)
528 //          averageWindHeading += 360.0;
529 //        //cerr << "Wind Heading " << windHeading << " average " << averageWindHeading << endl;
530 //        //cerr << "Wind Speed   " << windSpeed   << " average " << averageWindSpeed   << endl;
531 //        lastUpdate = dayStart;
532 //            //if (wind_speed == 0) {
533 //        //  wind_heading = 270;        This forces West-facing rwys to be used in no-wind situations
534 //          // which is consistent with Flightgear's initial setup.
535 //        //}
536           
537           //string rwy_no = globals->get_runways()->search(apt->getId(), int(wind_heading));
538           string scheduleName;
539           //cerr << "finding active Runway for" << _id << endl;
540           //cerr << "Nr of seconds since day start << " << dayStart << endl;
541
542           ScheduleTime *currSched;
543           //cerr << "A"<< endl;
544           currSched = rwyPrefs.getSchedule(trafficType.c_str());
545           if (!(currSched))
546             return;   
547           //cerr << "B"<< endl;
548           scheduleName = currSched->getName(dayStart);
549           maxTail  = currSched->getTailWind  ();
550           maxCross = currSched->getCrossWind ();
551           //cerr << "SChedule anme = " << scheduleName << endl;
552           if (scheduleName.empty())
553             return;
554           //cerr << "C"<< endl;
555           currRunwayGroup = rwyPrefs.getGroup(scheduleName); 
556           //cerr << "D"<< endl;
557           if (!(currRunwayGroup))
558             return;
559           nrActiveRunways = currRunwayGroup->getNrActiveRunways();
560           //cerr << "Nr of Active Runways = " << nrActiveRunways << endl; 
561
562           // 
563           currRunwayGroup->setActive(_id, 
564                                      windSpeed, 
565                                      windHeading, 
566                                      maxTail, 
567                                      maxCross, 
568                                      &currentlyActive); 
569
570           // Note that I SHOULD keep three lists in memory, one for 
571           // general aviation, one for commercial and one for military
572           // traffic.
573           currentlyActive.clear();
574           nrActiveRunways = currRunwayGroup->getNrActiveRunways();
575           for (int i = 0; i < nrActiveRunways; i++)
576             {
577               type = "unknown"; // initialize to something other than landing or takeoff
578               currRunwayGroup->getActive(i, name, type);
579               if (type == "landing")
580                 {
581                   landing.push_back(name);
582                   currentlyActive.push_back(name);
583                   //cerr << "Landing " << name << endl; 
584                 }
585               if (type == "takeoff")
586                 {
587                   takeoff.push_back(name);
588                   currentlyActive.push_back(name);
589                   //cerr << "takeoff " << name << endl;
590                 }
591             }
592         }
593       if (action == 1) // takeoff 
594         {
595           int nr = takeoff.size();
596           if (nr)
597             {
598               // Note that the randomization below, is just a placeholder to choose between
599               // multiple active runways for this action. This should be
600               // under ATC control.
601               runway = takeoff[(rand() %  nr)];
602             }
603           else
604             { // Fallback
605               runway = chooseRunwayFallback();
606             }
607         } 
608       if (action == 2) // landing
609         {
610           int nr = landing.size();
611           if (nr)
612             {
613               runway = landing[(rand() % nr)];
614             }
615           else
616             {  //fallback
617                runway = chooseRunwayFallback();
618             }
619         }
620       
621       //runway = globals->get_runways()->search(_id, int(windHeading));
622       //cerr << "Seleceted runway: " << runway << endl;
623     }
624 }
625
626 string FGAirportDynamics::chooseRunwayFallback()
627 {   
628   FGEnvironment 
629     stationweather = ((FGEnvironmentMgr *) globals->get_subsystem("environment"))
630     ->getEnvironment(getLatitude(), 
631                      getLongitude(),
632                      getElevation());
633   
634   double windSpeed = stationweather.get_wind_speed_kt();
635   double windHeading = stationweather.get_wind_from_heading_deg();
636   if (windSpeed == 0) {
637     windHeading = 270;  // This forces West-facing rwys to be used in no-wind situations
638     //which is consistent with Flightgear's initial setup.
639   }
640   
641    return globals->get_runways()->search(_id, int(windHeading));
642 }