]> git.mxchange.org Git - flightgear.git/blob - src/Traffic/TrafficMgr.cxx
Merge branch 'next' of D:\Git_New\flightgear into next
[flightgear.git] / src / Traffic / TrafficMgr.cxx
1 /******************************************************************************
2  * TrafficMGr.cxx
3  * Written by Durk Talsma, started May 5, 2004.
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  *
20  **************************************************************************/
21  
22 /* 
23  * Traffic manager parses airlines timetable-like data and uses this to 
24  * determine the approximate position of each AI aircraft in its database.
25  * When an AI aircraft is close to the user's position, a more detailed 
26  * AIModels based simulation is set up. 
27  * 
28  * I'm currently assuming the following simplifications:
29  * 1) The earth is a perfect sphere
30  * 2) Each aircraft flies a perfect great circle route.
31  * 3) Each aircraft flies at a constant speed (with infinite accelerations and
32  *    decelerations) 
33  * 4) Each aircraft leaves at exactly the departure time. 
34  * 5) Each aircraft arrives at exactly the specified arrival time. 
35  *
36  *
37  *****************************************************************************/
38
39 #ifdef HAVE_CONFIG_H
40 #  include "config.h"
41 #endif
42
43 #include <stdlib.h>
44 #include <time.h>
45 #include <cstring>
46 #include <iostream>
47 #include <fstream>
48
49
50 #include <string>
51 #include <vector>
52 #include <algorithm>
53
54 #include <plib/ul.h>
55
56 #include <simgear/compiler.h>
57 #include <simgear/misc/sg_path.hxx>
58 #include <simgear/props/props.hxx>
59 #include <simgear/route/waypoint.hxx>
60 #include <simgear/structure/subsystem_mgr.hxx>
61 #include <simgear/xml/easyxml.hxx>
62
63 #include <AIModel/AIAircraft.hxx>
64 #include <AIModel/AIFlightPlan.hxx>
65 #include <AIModel/AIBase.hxx>
66 #include <Airports/simple.hxx>
67 #include <Main/fg_init.hxx>
68
69
70
71 #include "TrafficMgr.hxx"
72
73 using std::sort;
74 using std::strcmp;
75  
76 /******************************************************************************
77  * TrafficManager
78  *****************************************************************************/
79 FGTrafficManager::FGTrafficManager()
80 {
81   //score = 0;
82   //runCount = 0;
83   acCounter = 0;
84 }
85
86 FGTrafficManager:: ~FGTrafficManager()
87 {
88     // Save the heuristics data
89     bool saveData = false;
90     ofstream cachefile;
91     if (fgGetBool("/sim/traffic-manager/heuristics")) {
92         SGPath cacheData(fgGetString("/sim/fg-home"));
93         cacheData.append("ai");
94         string airport = fgGetString("/sim/presets/airport-id");
95         
96         if ((airport) != "")  {
97             char buffer[128];
98             ::snprintf(buffer, 128, "%c/%c/%c/",
99                 airport[0], airport[1], airport[2]);
100             cacheData.append(buffer);
101             if (!cacheData.exists()) {
102                 cacheData.create_dir(0777);
103             }
104             cacheData.append(airport + "-cache.txt");
105             //cerr << "Saving AI traffic heuristics" << endl;
106             saveData = true;
107             cachefile.open(cacheData.str().c_str());
108         }
109    }
110    for (ScheduleVectorIterator sched = scheduledAircraft.begin(); sched != scheduledAircraft.end(); sched++) {
111       if (saveData) {
112           cachefile << (*sched)->getRegistration() << " " 
113                     << (*sched)-> getRunCount() << " " 
114                     << (*sched)->getHits() << endl;
115       }
116       delete (*sched);
117     }
118   if (saveData) {
119       cachefile.close();
120   }
121   scheduledAircraft.clear();
122   flights.clear();
123 }
124
125
126 void FGTrafficManager::init()
127
128   ulDir* d, *d2;
129   ulDirEnt* dent, *dent2;
130   SGPath aircraftDir = globals->get_fg_root();
131   SGPath path = aircraftDir;
132   heuristicsVector heuristics;
133   HeuristicMap     heurMap;
134   
135     
136   aircraftDir.append("AI/Traffic");
137   if ((d = ulOpenDir(aircraftDir.c_str())) != NULL)
138     {
139       while((dent = ulReadDir(d)) != NULL) {
140         if (string(dent->d_name) != string(".")  && 
141             string(dent->d_name) != string("..") &&
142             dent->d_isdir)
143           {
144             SGPath currACDir = aircraftDir;
145             currACDir.append(dent->d_name);
146             if ((d2 = ulOpenDir(currACDir.c_str())) == NULL)
147               return;
148             while ((dent2 = ulReadDir(d2)) != NULL) {
149               SGPath currFile = currACDir;
150               currFile.append(dent2->d_name);
151               if (currFile.extension() == string("xml"))
152                 {
153                   SGPath currFile = currACDir;
154                   currFile.append(dent2->d_name);
155                   SG_LOG(SG_GENERAL, SG_DEBUG, "Scanning " << currFile.str() << " for traffic");
156                   readXML(currFile.str(),*this);
157                 }
158             }
159             ulCloseDir(d2);
160           }
161       }
162       ulCloseDir(d);
163     }
164     if (fgGetBool("/sim/traffic-manager/heuristics")) {
165         //cerr << "Processing Heuristics" << endl;
166         // Load the heuristics data
167         SGPath cacheData(fgGetString("/sim/fg-home"));
168         cacheData.append("ai");
169         string airport = fgGetString("/sim/presets/airport-id");
170         if ((airport) != "") {
171             char buffer[128];
172             ::snprintf(buffer, 128, "%c/%c/%c/",
173                  airport[0], airport[1], airport[2]);
174             cacheData.append(buffer);
175             cacheData.append(airport + "-cache.txt");
176             if (cacheData.exists()) {
177                 ifstream data(cacheData.c_str());
178                 while (1) {
179                     Heuristic *h = new Heuristic;
180                     data >> h->registration >> h->runCount >> h->hits;
181                     if (data.eof())
182                         break;
183                     heurMap[h->registration] = h;
184                     heuristics.push_back(h);
185                 }
186             }
187         }
188         for (currAircraft = scheduledAircraft.begin(); 
189             currAircraft != scheduledAircraft.end();
190             currAircraft++) {
191             string registration = (*currAircraft)->getRegistration();
192             HeuristicMapIterator itr = heurMap.find(registration);
193             //cerr << "Processing heuristics for" << (*currAircraft)->getRegistration() << endl;
194             if (itr == heurMap.end()) {
195                 //cerr << "No heuristics found for " << registration << endl;
196             } else {
197                 (*currAircraft)->setrunCount(itr->second->runCount);
198                 (*currAircraft)->setHits    (itr->second->hits);
199                 (*currAircraft)->setScore();
200                 //cerr <<"Runcount " << itr->second->runCount << ".Hits " << itr->second->hits << endl;
201             }
202         }
203         //cerr << "Done" << endl;
204         for (heuristicsVectorIterator hvi = heuristics.begin();
205                                       hvi != heuristics.end();
206                                       hvi++) {
207             delete (*hvi);
208         }
209         sort (scheduledAircraft.begin(), scheduledAircraft.end(), compareSchedules);
210     }
211     currAircraft = scheduledAircraft.begin();
212     currAircraftClosest = scheduledAircraft.begin();
213 }
214
215 void FGTrafficManager::update(double /*dt*/)
216 {
217   if (fgGetBool("/environment/metar/valid") == false) {
218        return;
219   }
220   time_t now = time(NULL) + fgGetLong("/sim/time/warp");
221   if (scheduledAircraft.size() == 0) {
222     return;
223   }
224   
225   SGVec3d userCart = SGVec3d::fromGeod(SGGeod::fromDeg(
226     fgGetDouble("/position/longitude-deg"), 
227     fgGetDouble("/position/latitude-deg")));
228   
229   if(currAircraft == scheduledAircraft.end())
230     {
231       currAircraft = scheduledAircraft.begin();
232     }
233   //cerr << "Processing << " << (*currAircraft)->getRegistration() << " with score " << (*currAircraft)->getScore() << endl;
234   if (!((*currAircraft)->update(now, userCart)))
235     {
236       // NOTE: With traffic manager II, this statement below is no longer true
237       // after proper initialization, we shouldnt get here.
238       // But let's make sure
239       //SG_LOG( SG_GENERAL, SG_ALERT, "Failed to update aircraft schedule in traffic manager");
240     }
241   currAircraft++;
242 }
243
244 void FGTrafficManager::release(int id)
245 {
246   releaseList.push_back(id);
247 }
248
249 bool FGTrafficManager::isReleased(int id)
250 {
251   IdListIterator i = releaseList.begin();
252   while (i != releaseList.end())
253     {
254       if ((*i) == id)
255         {
256           releaseList.erase(i);
257           return true;
258         }
259       i++;
260     }
261   return false;
262 }
263 /*
264 void FGTrafficManager::readTimeTableFromFile(SGPath infileName)
265 {
266     string model;
267     string livery;
268     string homePort;
269     string registration;
270     string flightReq;
271     bool   isHeavy;
272     string acType;
273     string airline;
274     string m_class;
275     string FlightType;
276     double radius;
277     double offset;
278
279     char buffer[256];
280     string buffString;
281     vector <string> tokens, depTime,arrTime;
282     vector <string>::iterator it;
283     ifstream infile(infileName.str().c_str());
284     while (1) {
285          infile.getline(buffer, 256);
286          if (infile.eof()) {
287              break;
288          }
289          //cerr << "Read line : " << buffer << endl;
290          buffString = string(buffer);
291          tokens.clear();
292          Tokenize(buffString, tokens, " \t");
293          //for (it = tokens.begin(); it != tokens.end(); it++) {
294          //    cerr << "Tokens: " << *(it) << endl;
295          //}
296          //cerr << endl;
297          if (!tokens.empty()) {
298              if (tokens[0] == string("AC")) {
299                  if (tokens.size() != 13) {
300                      SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
301                      exit(1);
302                  }
303                  model          = tokens[12];
304                  livery         = tokens[6];
305                  homePort       = tokens[1];
306                  registration   = tokens[2];
307                  if (tokens[11] == string("false")) {
308                      isHeavy = false;
309                  } else {
310                      isHeavy = true;
311                  }
312                  acType         = tokens[4];
313                  airline        = tokens[5];
314                  flightReq      = tokens[3] + tokens[5];
315                  m_class        = tokens[10];
316                  FlightType     = tokens[9];
317                  radius         = atof(tokens[8].c_str());
318                  offset         = atof(tokens[7].c_str());;
319                  //cerr << "Found AC string " << model << " " << livery << " " << homePort << " " 
320                  //     << registration << " " << flightReq << " " << isHeavy << " " << acType << " " << airline << " " << m_class 
321                  //     << " " << FlightType << " " << radius << " " << offset << endl;
322                  scheduledAircraft.push_back(new FGAISchedule(model, 
323                                                               livery, 
324                                                               homePort,
325                                                               registration, 
326                                                               flightReq,
327                                                               isHeavy,
328                                                               acType, 
329                                                               airline, 
330                                                               m_class, 
331                                                               FlightType,
332                                                               radius,
333                                                               offset));
334              }
335              if (tokens[0] == string("FLIGHT")) {
336                  //cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
337                  if (tokens.size() != 10) {
338                      SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
339                      exit(1);
340                  }
341                  string callsign = tokens[1];
342                  string fltrules = tokens[2];
343                  string weekdays = tokens[3];
344                  string departurePort = tokens[5];
345                  string arrivalPort   = tokens[7];
346                  int    cruiseAlt     = atoi(tokens[8].c_str());
347                  string depTimeGen    = tokens[4];
348                  string arrTimeGen    = tokens[6];
349                  string repeat        = "WEEK";
350                  string requiredAircraft = tokens[9];
351                  
352                  if (weekdays.size() != 7) {
353                      cerr << "Found misconfigured weekdays string" << weekdays << endl;
354                      exit(1);
355                  }
356                  depTime.clear();
357                  arrTime.clear();
358                  Tokenize(depTimeGen, depTime, ":");
359                  Tokenize(arrTimeGen, arrTime, ":");
360                  double dep = atof(depTime[0].c_str()) + (atof(depTime[1].c_str()) / 60.0);
361                  double arr = atof(arrTime[0].c_str()) + (atof(arrTime[1].c_str()) / 60.0);
362                  //cerr << "Using " << dep << " " << arr << endl;
363                  bool arrivalWeekdayNeedsIncrement = false;
364                  if (arr < dep) {
365                        arrivalWeekdayNeedsIncrement = true;
366                  }
367                  for (int i = 0; i < 7; i++) {
368                      if (weekdays[i] != '.') {
369                          char buffer[4];
370                          snprintf(buffer, 4, "%d/", i);
371                          string departureTime = string(buffer) + depTimeGen + string(":00");
372                          string arrivalTime;
373                          if (!arrivalWeekdayNeedsIncrement) {
374                              arrivalTime   = string(buffer) + arrTimeGen + string(":00");
375                          }
376                          if (arrivalWeekdayNeedsIncrement && i != 6 ) {
377                              snprintf(buffer, 4, "%d/", i+1);
378                              arrivalTime   = string(buffer) + arrTimeGen + string(":00");
379                          }
380                          if (arrivalWeekdayNeedsIncrement && i == 6 ) {
381                              snprintf(buffer, 4, "%d/", 0);
382                              arrivalTime   = string(buffer) + arrTimeGen  + string(":00");
383                          }
384                          cerr << "Adding flight: " << callsign       << " "
385                                                    << fltrules       << " "
386                                                    <<  departurePort << " "
387                                                    <<  arrivalPort   << " "
388                                                    <<  cruiseAlt     << " "
389                                                    <<  departureTime << " "
390                                                    <<  arrivalTime   << " "
391                                                    <<  repeat        << " " 
392                                                    <<  requiredAircraft << endl;
393
394                          flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
395                                                                  fltrules,
396                                                                  departurePort,
397                                                                  arrivalPort,
398                                                                  cruiseAlt,
399                                                                  departureTime,
400                                                                  arrivalTime,
401                                                                  repeat,
402                                                                  requiredAircraft));
403                     }
404                 }
405              }
406          }
407
408     }
409     //exit(1);
410 }*/
411
412 /*
413 void FGTrafficManager::Tokenize(const string& str,
414                       vector<string>& tokens,
415                       const string& delimiters)
416 {
417     // Skip delimiters at beginning.
418     string::size_type lastPos = str.find_first_not_of(delimiters, 0);
419     // Find first "non-delimiter".
420     string::size_type pos     = str.find_first_of(delimiters, lastPos);
421
422     while (string::npos != pos || string::npos != lastPos)
423     {
424         // Found a token, add it to the vector.
425         tokens.push_back(str.substr(lastPos, pos - lastPos));
426         // Skip delimiters.  Note the "not_of"
427         lastPos = str.find_first_not_of(delimiters, pos);
428         // Find next "non-delimiter"
429         pos = str.find_first_of(delimiters, lastPos);
430     }
431 }
432 */
433
434 void  FGTrafficManager::startXML () {
435   //cout << "Start XML" << endl;
436   requiredAircraft = "";
437   homePort         = "";
438 }
439
440 void  FGTrafficManager::endXML () {
441   //cout << "End XML" << endl;
442 }
443
444 void  FGTrafficManager::startElement (const char * name, const XMLAttributes &atts) {
445   const char * attval;
446   //cout << "Start element " << name << endl;
447   //FGTrafficManager temp;
448   //for (int i = 0; i < atts.size(); i++)
449   //  if (string(atts.getName(i)) == string("include"))
450   attval = atts.getValue("include");
451   if (attval != 0)
452       {
453         //cout << "including " << attval << endl;
454         SGPath path = 
455           globals->get_fg_root();
456         path.append("/Traffic/");
457         path.append(attval);
458         readXML(path.str(), *this);
459       }
460   elementValueStack.push_back( "" );
461   //  cout << "  " << atts.getName(i) << '=' << atts.getValue(i) << endl; 
462 }
463
464 void  FGTrafficManager::endElement (const char * name) {
465   //cout << "End element " << name << endl;
466   const string& value = elementValueStack.back();
467
468   if (!strcmp(name, "model"))
469     mdl = value;
470   else if (!strcmp(name, "livery"))
471     livery = value;
472   else if (!strcmp(name, "home-port"))
473     homePort = value;
474   else if (!strcmp(name, "registration"))
475     registration = value;
476   else if (!strcmp(name, "airline"))
477     airline = value;
478   else if (!strcmp(name, "actype"))
479     acType = value;
480   else if (!strcmp(name, "required-aircraft"))
481     requiredAircraft = value;
482   else if (!strcmp(name, "flighttype"))
483     flighttype = value;
484   else if (!strcmp(name, "radius"))
485     radius = atoi(value.c_str());
486   else if (!strcmp(name, "offset"))
487     offset = atoi(value.c_str());
488   else if (!strcmp(name, "performance-class"))
489     m_class = value;
490   else if (!strcmp(name, "heavy"))
491     {
492       if(value == string("true"))
493         heavy = true;
494       else
495         heavy = false;
496     }
497   else if (!strcmp(name, "callsign"))
498     callsign = value;
499   else if (!strcmp(name, "fltrules"))
500     fltrules = value;
501   else if (!strcmp(name, "port"))
502     port = value;
503   else if (!strcmp(name, "time"))
504     timeString = value;
505   else if (!strcmp(name, "departure"))
506     {
507       departurePort = port;
508       departureTime = timeString;
509     }
510   else if (!strcmp(name, "cruise-alt"))
511     cruiseAlt = atoi(value.c_str());
512   else if (!strcmp(name, "arrival"))
513     {
514       arrivalPort = port;
515       arrivalTime = timeString;
516     }
517   else if (!strcmp(name, "repeat"))
518     repeat = value;
519   else if (!strcmp(name, "flight"))
520     {
521       // We have loaded and parsed all the information belonging to this flight
522       // so we temporarily store it. 
523       //cerr << "Pusing back flight " << callsign << endl;
524       //cerr << callsign  <<  " " << fltrules     << " "<< departurePort << " " <<  arrivalPort << " "
525       //   << cruiseAlt <<  " " << departureTime<< " "<< arrivalTime   << " " << repeat << endl;
526
527       //Prioritize aircraft 
528       string apt = fgGetString("/sim/presets/airport-id");
529       //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
530       //if (departurePort == apt) score++;
531       //flights.push_back(new FGScheduledFlight(callsign,
532         //                                fltrules,
533         //                                departurePort,
534         //                                arrivalPort,
535         //                                cruiseAlt,
536         //                                departureTime,
537         //                                arrivalTime,
538         //                                repeat));
539     if (requiredAircraft == "") {
540         char buffer[16];
541         snprintf(buffer, 16, "%d", acCounter);
542         requiredAircraft = buffer;
543     }
544     SG_LOG(SG_GENERAL, SG_DEBUG, "Adding flight: " << callsign       << " "
545                               << fltrules       << " "
546                               <<  departurePort << " "
547                               <<  arrivalPort   << " "
548                               <<  cruiseAlt     << " "
549                               <<  departureTime << " "
550                               <<  arrivalTime   << " "
551                               <<  repeat        << " " 
552                               <<  requiredAircraft);
553
554      flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
555                                                                  fltrules,
556                                                                  departurePort,
557                                                                  arrivalPort,
558                                                                  cruiseAlt,
559                                                                  departureTime,
560                                                                  arrivalTime,
561                                                                  repeat,
562                                                                  requiredAircraft));
563       requiredAircraft = "";
564   }
565   else if (!strcmp(name, "aircraft"))
566     {
567       int proportion = (int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
568       int randval = rand() & 100;
569       if (randval < proportion) {
570           //scheduledAircraft.push_back(new FGAISchedule(mdl, 
571         //                                     livery, 
572         //                                     registration, 
573         //                                     heavy,
574         //                                     acType, 
575         //                                     airline, 
576         //                                     m_class, 
577         //                                     flighttype,
578         //                                     radius,
579         //                                     offset,
580         //                                     score,
581         //                                     flights));
582     if (requiredAircraft == "") {
583         char buffer[16];
584         snprintf(buffer, 16, "%d", acCounter);
585         requiredAircraft = buffer;
586     }
587     if (homePort == "") {
588         homePort = departurePort;
589     }
590             scheduledAircraft.push_back(new FGAISchedule(mdl, 
591                                                          livery, 
592                                                          homePort,
593                                                          registration, 
594                                                          requiredAircraft,
595                                                          heavy,
596                                                          acType, 
597                                                          airline, 
598                                                          m_class, 
599                                                          flighttype,
600                                                          radius,
601                                                          offset));
602
603      //  while(flights.begin() != flights.end()) {
604 //      flights.pop_back();
605 //       }
606         }
607     acCounter++;
608     requiredAircraft = "";
609     homePort = "";
610   //for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
611   //  {
612   //    delete (*flt);
613   //  }
614   //flights.clear();
615       SG_LOG( SG_GENERAL, SG_BULK, "Reading aircraft : " 
616               << registration 
617               << " with prioritization score " 
618               << score);
619       score = 0;
620     }
621   elementValueStack.pop_back();
622 }
623
624 void  FGTrafficManager::data (const char * s, int len) {
625   string token = string(s,len);
626   //cout << "Character data " << string(s,len) << endl;
627   elementValueStack.back() += token;
628 }
629
630 void  FGTrafficManager::pi (const char * target, const char * data) {
631   //cout << "Processing instruction " << target << ' ' << data << endl;
632 }
633
634 void  FGTrafficManager::warning (const char * message, int line, int column) {
635   SG_LOG(SG_IO, SG_WARN, "Warning: " << message << " (" << line << ',' << column << ')');
636 }
637
638 void  FGTrafficManager::error (const char * message, int line, int column) {
639   SG_LOG(SG_IO, SG_ALERT, "Error: " << message << " (" << line << ',' << column << ')');
640 }
641