]> git.mxchange.org Git - flightgear.git/blob - src/Airports/dynamics.cxx
Fix line endings
[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., 675 Mass Ave, Cambridge, MA 02139, 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   _latitude(lat),
61   _longitude(lon),
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->getLongitude();
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   cout << "Warning: " << message << " (" << line << ',' << column << ')'   
441        << endl;
442 }
443
444 void  FGAirportDynamics::error (const char * message, int line, int column) {
445   cout << "Error: " << message << " (" << line << ',' << column << ')'
446        << endl;
447 }
448
449 void FGAirportDynamics::setRwyUse(const FGRunwayPreference& ref)
450 {
451   rwyPrefs = ref;
452   //cerr << "Exiting due to not implemented yet" << endl;
453   //exit(1);
454 }
455 void FGAirportDynamics::getActiveRunway(const string &trafficType, int action, string &runway)
456 {
457   double windSpeed;
458   double windHeading;
459   double maxTail;
460   double maxCross;
461   string name;
462   string type;
463
464   if (!(rwyPrefs.available()))
465     {
466       runway = chooseRunwayFallback();
467       return; // generic fall back goes here
468     }
469   else
470     {
471       RunwayGroup *currRunwayGroup = 0;
472       int nrActiveRunways = 0;
473       time_t dayStart = fgGetLong("/sim/time/utc/day-seconds");
474       if (((dayStart - lastUpdate) > 600) || trafficType != prevTrafficType)
475         {
476           landing.clear();
477           takeoff.clear();
478           //lastUpdate = dayStart;
479           prevTrafficType = trafficType;
480
481           FGEnvironment 
482             stationweather = ((FGEnvironmentMgr *) globals->get_subsystem("environment"))
483             ->getEnvironment(getLatitude(), 
484                              getLongitude(), 
485                              getElevation());
486           
487           windSpeed = stationweather.get_wind_speed_kt();
488           windHeading = stationweather.get_wind_from_heading_deg();
489           double averageWindSpeed   = 0;
490           double averageWindHeading = 0;
491           double cosHeading         = 0;
492           double sinHeading         = 0;
493           // Initialize at the beginning of the next day or startup
494           if ((lastUpdate == 0) || (dayStart < lastUpdate))
495             {
496               for (int i = 0; i < 10; i++)
497                 {
498                   avWindHeading [i] = windHeading;
499                   avWindSpeed   [i] = windSpeed;
500                 }
501             }
502           else
503             {
504               if (windSpeed != avWindSpeed[9]) // update if new metar data 
505                 {
506                   // shift the running average
507                   for (int i = 0; i < 9 ; i++)
508                     {
509                       avWindHeading[i] = avWindHeading[i+1];
510                       avWindSpeed  [i] = avWindSpeed  [i+1];
511                     }
512                 } 
513               avWindHeading[9] = windHeading;
514               avWindSpeed  [9] = windSpeed;
515             }
516           
517           for (int i = 0; i < 10; i++)
518             {
519               averageWindSpeed   += avWindSpeed   [i];
520               //averageWindHeading += avWindHeading [i];
521               cosHeading += cos(avWindHeading[i] * SG_DEGREES_TO_RADIANS);
522               sinHeading += sin(avWindHeading[i] * SG_DEGREES_TO_RADIANS);
523             }
524           averageWindSpeed   /= 10;
525           //averageWindHeading /= 10;
526           cosHeading /= 10;
527           sinHeading /= 10;
528           averageWindHeading = atan2(sinHeading, cosHeading) *SG_RADIANS_TO_DEGREES;
529           if (averageWindHeading < 0)
530             averageWindHeading += 360.0;
531           //cerr << "Wind Heading " << windHeading << " average " << averageWindHeading << endl;
532           //cerr << "Wind Speed   " << windSpeed   << " average " << averageWindSpeed   << endl;
533           lastUpdate = dayStart;
534               //if (wind_speed == 0) {
535           //  wind_heading = 270;        This forces West-facing rwys to be used in no-wind situations
536             // which is consistent with Flightgear's initial setup.
537           //}
538           
539           //string rwy_no = globals->get_runways()->search(apt->getId(), int(wind_heading));
540           string scheduleName;
541           //cerr << "finding active Runway for" << _id << endl;
542           //cerr << "Nr of seconds since day start << " << dayStart << endl;
543           ScheduleTime *currSched;
544           //cerr << "A"<< endl;
545           currSched = rwyPrefs.getSchedule(trafficType.c_str());
546           if (!(currSched))
547             return;   
548           //cerr << "B"<< endl;
549           scheduleName = currSched->getName(dayStart);
550           maxTail  = currSched->getTailWind  ();
551           maxCross = currSched->getCrossWind ();
552           //cerr << "SChedule anme = " << scheduleName << endl;
553           if (scheduleName.empty())
554             return;
555           //cerr << "C"<< endl;
556           currRunwayGroup = rwyPrefs.getGroup(scheduleName); 
557           //cerr << "D"<< endl;
558           if (!(currRunwayGroup))
559             return;
560           nrActiveRunways = currRunwayGroup->getNrActiveRunways();
561           //cerr << "Nr of Active Runways = " << nrActiveRunways << endl; 
562           currRunwayGroup->setActive(_id, averageWindSpeed, averageWindHeading, maxTail, maxCross); 
563           nrActiveRunways = currRunwayGroup->getNrActiveRunways();
564           for (int i = 0; i < nrActiveRunways; i++)
565             {
566               type = "unknown"; // initialize to something other than landing or takeoff
567               currRunwayGroup->getActive(i, name, type);
568               if (type == "landing")
569                 {
570                   landing.push_back(name);
571                   //cerr << "Landing " << name << endl; 
572                 }
573               if (type == "takeoff")
574                 {
575                   takeoff.push_back(name);
576                   //cerr << "takeoff " << name << endl;
577                 }
578             }
579         }
580       if (action == 1) // takeoff 
581         {
582           int nr = takeoff.size();
583           if (nr)
584             {
585               runway = takeoff[(rand() %  nr)];
586             }
587           else
588             { // Fallback
589               runway = chooseRunwayFallback();
590             }
591         } 
592       if (action == 2) // landing
593         {
594           int nr = landing.size();
595           if (nr)
596             {
597               runway = landing[(rand() % nr)];
598             }
599           else
600             {  //fallback
601                runway = chooseRunwayFallback();
602             }
603         }
604       
605       //runway = globals->get_runways()->search(_id, int(windHeading));
606       //cerr << "Seleceted runway: " << runway << endl;
607     }
608 }
609
610 string FGAirportDynamics::chooseRunwayFallback()
611 {   
612   FGEnvironment 
613     stationweather = ((FGEnvironmentMgr *) globals->get_subsystem("environment"))
614     ->getEnvironment(getLatitude(), 
615                      getLongitude(),
616                      getElevation());
617   
618   double windSpeed = stationweather.get_wind_speed_kt();
619   double windHeading = stationweather.get_wind_from_heading_deg();
620   if (windSpeed == 0) {
621     windHeading = 270;  // This forces West-facing rwys to be used in no-wind situations
622     //which is consistent with Flightgear's initial setup.
623   }
624   
625    return globals->get_runways()->search(_id, int(windHeading));
626 }