]> git.mxchange.org Git - flightgear.git/blob - src/Traffic/TrafficMgr.cxx
Merge branch 'maint' 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 <iostream>
46 #include <fstream>
47
48
49 #include <string>
50 #include <vector>
51 #include <algorithm>
52
53 #include <plib/ul.h>
54
55 #include <simgear/compiler.h>
56 #include <simgear/misc/sg_path.hxx>
57 #include <simgear/props/props.hxx>
58 #include <simgear/route/waypoint.hxx>
59 #include <simgear/structure/subsystem_mgr.hxx>
60 #include <simgear/xml/easyxml.hxx>
61
62 #include <AIModel/AIAircraft.hxx>
63 #include <AIModel/AIFlightPlan.hxx>
64 #include <AIModel/AIBase.hxx>
65 #include <Airports/simple.hxx>
66 #include <Main/fg_init.hxx>
67
68
69
70 #include "TrafficMgr.hxx"
71
72 using std::sort;
73  
74 /******************************************************************************
75  * TrafficManager
76  *****************************************************************************/
77 FGTrafficManager::FGTrafficManager()
78 {
79   //score = 0;
80   //runCount = 0;
81   acCounter = 0;
82 }
83
84 FGTrafficManager:: ~FGTrafficManager()
85 {
86   for (ScheduleVectorIterator sched = scheduledAircraft.begin(); sched != scheduledAircraft.end(); sched++)
87     {
88       delete (*sched);
89     }
90   scheduledAircraft.clear();
91   flights.clear();
92 }
93
94
95 void FGTrafficManager::init()
96
97   ulDir* d, *d2;
98   ulDirEnt* dent, *dent2;
99   SGPath aircraftDir = globals->get_fg_root();
100
101   SGPath path = aircraftDir;
102   
103   aircraftDir.append("AI/Traffic");
104   if ((d = ulOpenDir(aircraftDir.c_str())) != NULL)
105     {
106       while((dent = ulReadDir(d)) != NULL) {
107         if (string(dent->d_name) != string(".")  && 
108             string(dent->d_name) != string("..") &&
109             dent->d_isdir)
110           {
111             SGPath currACDir = aircraftDir;
112             currACDir.append(dent->d_name);
113             if ((d2 = ulOpenDir(currACDir.c_str())) == NULL)
114               return;
115             while ((dent2 = ulReadDir(d2)) != NULL) {
116               SGPath currFile = currACDir;
117               currFile.append(dent2->d_name);
118               if (currFile.extension() == string("xml"))
119                 {
120                   SGPath currFile = currACDir;
121                   currFile.append(dent2->d_name);
122                   SG_LOG(SG_GENERAL, SG_INFO, "Scanning " << currFile.str() << " for traffic");
123                   readXML(currFile.str(),*this);
124                 }
125             }
126             ulCloseDir(d2);
127           }
128       }
129       ulCloseDir(d);
130     }
131     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
132
133     currAircraft = scheduledAircraft.begin();
134     currAircraftClosest = scheduledAircraft.begin();
135 }
136
137 void FGTrafficManager::update(double /*dt*/)
138 {
139
140   time_t now = time(NULL) + fgGetLong("/sim/time/warp");
141   if (scheduledAircraft.size() == 0) {
142     return;
143   }
144   if(currAircraft == scheduledAircraft.end())
145     {
146       currAircraft = scheduledAircraft.begin();
147     }
148   if (!((*currAircraft)->update(now)))
149     {
150       // NOTE: With traffic manager II, this statement below is no longer true
151       // after proper initialization, we shouldnt get here.
152       // But let's make sure
153       //SG_LOG( SG_GENERAL, SG_ALERT, "Failed to update aircraft schedule in traffic manager");
154     }
155   currAircraft++;
156 }
157
158 void FGTrafficManager::release(int id)
159 {
160   releaseList.push_back(id);
161 }
162
163 bool FGTrafficManager::isReleased(int id)
164 {
165   IdListIterator i = releaseList.begin();
166   while (i != releaseList.end())
167     {
168       if ((*i) == id)
169         {
170           releaseList.erase(i);
171           return true;
172         }
173       i++;
174     }
175   return false;
176 }
177 /*
178 void FGTrafficManager::readTimeTableFromFile(SGPath infileName)
179 {
180     string model;
181     string livery;
182     string homePort;
183     string registration;
184     string flightReq;
185     bool   isHeavy;
186     string acType;
187     string airline;
188     string m_class;
189     string FlightType;
190     double radius;
191     double offset;
192
193     char buffer[256];
194     string buffString;
195     vector <string> tokens, depTime,arrTime;
196     vector <string>::iterator it;
197     ifstream infile(infileName.str().c_str());
198     while (1) {
199          infile.getline(buffer, 256);
200          if (infile.eof()) {
201              break;
202          }
203          //cerr << "Read line : " << buffer << endl;
204          buffString = string(buffer);
205          tokens.clear();
206          Tokenize(buffString, tokens, " \t");
207          //for (it = tokens.begin(); it != tokens.end(); it++) {
208          //    cerr << "Tokens: " << *(it) << endl;
209          //}
210          //cerr << endl;
211          if (!tokens.empty()) {
212              if (tokens[0] == string("AC")) {
213                  if (tokens.size() != 13) {
214                      SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
215                      exit(1);
216                  }
217                  model          = tokens[12];
218                  livery         = tokens[6];
219                  homePort       = tokens[1];
220                  registration   = tokens[2];
221                  if (tokens[11] == string("false")) {
222                      isHeavy = false;
223                  } else {
224                      isHeavy = true;
225                  }
226                  acType         = tokens[4];
227                  airline        = tokens[5];
228                  flightReq      = tokens[3] + tokens[5];
229                  m_class        = tokens[10];
230                  FlightType     = tokens[9];
231                  radius         = atof(tokens[8].c_str());
232                  offset         = atof(tokens[7].c_str());;
233                  //cerr << "Found AC string " << model << " " << livery << " " << homePort << " " 
234                  //     << registration << " " << flightReq << " " << isHeavy << " " << acType << " " << airline << " " << m_class 
235                  //     << " " << FlightType << " " << radius << " " << offset << endl;
236                  scheduledAircraft.push_back(new FGAISchedule(model, 
237                                                               livery, 
238                                                               homePort,
239                                                               registration, 
240                                                               flightReq,
241                                                               isHeavy,
242                                                               acType, 
243                                                               airline, 
244                                                               m_class, 
245                                                               FlightType,
246                                                               radius,
247                                                               offset));
248              }
249              if (tokens[0] == string("FLIGHT")) {
250                  //cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
251                  if (tokens.size() != 10) {
252                      SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
253                      exit(1);
254                  }
255                  string callsign = tokens[1];
256                  string fltrules = tokens[2];
257                  string weekdays = tokens[3];
258                  string departurePort = tokens[5];
259                  string arrivalPort   = tokens[7];
260                  int    cruiseAlt     = atoi(tokens[8].c_str());
261                  string depTimeGen    = tokens[4];
262                  string arrTimeGen    = tokens[6];
263                  string repeat        = "WEEK";
264                  string requiredAircraft = tokens[9];
265                  
266                  if (weekdays.size() != 7) {
267                      cerr << "Found misconfigured weekdays string" << weekdays << endl;
268                      exit(1);
269                  }
270                  depTime.clear();
271                  arrTime.clear();
272                  Tokenize(depTimeGen, depTime, ":");
273                  Tokenize(arrTimeGen, arrTime, ":");
274                  double dep = atof(depTime[0].c_str()) + (atof(depTime[1].c_str()) / 60.0);
275                  double arr = atof(arrTime[0].c_str()) + (atof(arrTime[1].c_str()) / 60.0);
276                  //cerr << "Using " << dep << " " << arr << endl;
277                  bool arrivalWeekdayNeedsIncrement = false;
278                  if (arr < dep) {
279                        arrivalWeekdayNeedsIncrement = true;
280                  }
281                  for (int i = 0; i < 7; i++) {
282                      if (weekdays[i] != '.') {
283                          char buffer[4];
284                          snprintf(buffer, 4, "%d/", i);
285                          string departureTime = string(buffer) + depTimeGen + string(":00");
286                          string arrivalTime;
287                          if (!arrivalWeekdayNeedsIncrement) {
288                              arrivalTime   = string(buffer) + arrTimeGen + string(":00");
289                          }
290                          if (arrivalWeekdayNeedsIncrement && i != 6 ) {
291                              snprintf(buffer, 4, "%d/", i+1);
292                              arrivalTime   = string(buffer) + arrTimeGen + string(":00");
293                          }
294                          if (arrivalWeekdayNeedsIncrement && i == 6 ) {
295                              snprintf(buffer, 4, "%d/", 0);
296                              arrivalTime   = string(buffer) + arrTimeGen  + string(":00");
297                          }
298                          cerr << "Adding flight: " << callsign       << " "
299                                                    << fltrules       << " "
300                                                    <<  departurePort << " "
301                                                    <<  arrivalPort   << " "
302                                                    <<  cruiseAlt     << " "
303                                                    <<  departureTime << " "
304                                                    <<  arrivalTime   << " "
305                                                    <<  repeat        << " " 
306                                                    <<  requiredAircraft << endl;
307
308                          flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
309                                                                  fltrules,
310                                                                  departurePort,
311                                                                  arrivalPort,
312                                                                  cruiseAlt,
313                                                                  departureTime,
314                                                                  arrivalTime,
315                                                                  repeat,
316                                                                  requiredAircraft));
317                     }
318                 }
319              }
320          }
321
322     }
323     //exit(1);
324 }*/
325
326 /*
327 void FGTrafficManager::Tokenize(const string& str,
328                       vector<string>& tokens,
329                       const string& delimiters)
330 {
331     // Skip delimiters at beginning.
332     string::size_type lastPos = str.find_first_not_of(delimiters, 0);
333     // Find first "non-delimiter".
334     string::size_type pos     = str.find_first_of(delimiters, lastPos);
335
336     while (string::npos != pos || string::npos != lastPos)
337     {
338         // Found a token, add it to the vector.
339         tokens.push_back(str.substr(lastPos, pos - lastPos));
340         // Skip delimiters.  Note the "not_of"
341         lastPos = str.find_first_not_of(delimiters, pos);
342         // Find next "non-delimiter"
343         pos = str.find_first_of(delimiters, lastPos);
344     }
345 }
346 */
347
348 void  FGTrafficManager::startXML () {
349   //cout << "Start XML" << endl;
350   requiredAircraft = "";
351   homePort         = "";
352 }
353
354 void  FGTrafficManager::endXML () {
355   //cout << "End XML" << endl;
356 }
357
358 void  FGTrafficManager::startElement (const char * name, const XMLAttributes &atts) {
359   const char * attval;
360   //cout << "Start element " << name << endl;
361   //FGTrafficManager temp;
362   //for (int i = 0; i < atts.size(); i++)
363   //  if (string(atts.getName(i)) == string("include"))
364   attval = atts.getValue("include");
365   if (attval != 0)
366       {
367         //cout << "including " << attval << endl;
368         SGPath path = 
369           globals->get_fg_root();
370         path.append("/Traffic/");
371         path.append(attval);
372         readXML(path.str(), *this);
373       }
374   elementValueStack.push_back( "" );
375   //  cout << "  " << atts.getName(i) << '=' << atts.getValue(i) << endl; 
376 }
377
378 void  FGTrafficManager::endElement (const char * name) {
379   //cout << "End element " << name << endl;
380   string element(name);
381   string value = elementValueStack.back();
382   elementValueStack.pop_back();
383
384   if (element == string("model"))
385     mdl = value;
386   else if (element == string("livery"))
387     livery = value;
388   else if (element == string("home-port"))
389     homePort = value;
390   else if (element == string("registration"))
391     registration = value;
392   else if (element == string("airline"))
393     airline = value;
394   else if (element == string("actype"))
395     acType = value;
396   else if (element == string("required-aircraft"))
397     requiredAircraft = value;
398   else if (element == string("flighttype"))
399     flighttype = value;
400   else if (element == string("radius"))
401     radius = atoi(value.c_str());
402   else if (element == string("offset"))
403     offset = atoi(value.c_str());
404   else if (element == string("performance-class"))
405     m_class = value;
406   else if (element == string("heavy"))
407     {
408       if(value == string("true"))
409         heavy = true;
410       else
411         heavy = false;
412     }
413   else if (element == string("callsign"))
414     callsign = value;
415   else if (element == string("fltrules"))
416     fltrules = value;
417   else if (element == string("port"))
418     port = value;
419   else if (element == string("time"))
420     timeString = value;
421   else if (element == string("departure"))
422     {
423       departurePort = port;
424       departureTime = timeString;
425     }
426   else if (element == string("cruise-alt"))
427     cruiseAlt = atoi(value.c_str());
428   else if (element == string("arrival"))
429     {
430       arrivalPort = port;
431       arrivalTime = timeString;
432     }
433   else if (element == string("repeat"))
434     repeat = value;
435   else if (element == string("flight"))
436     {
437       // We have loaded and parsed all the information belonging to this flight
438       // so we temporarily store it. 
439       //cerr << "Pusing back flight " << callsign << endl;
440       //cerr << callsign  <<  " " << fltrules     << " "<< departurePort << " " <<  arrivalPort << " "
441       //   << cruiseAlt <<  " " << departureTime<< " "<< arrivalTime   << " " << repeat << endl;
442
443       //Prioritize aircraft 
444       string apt = fgGetString("/sim/presets/airport-id");
445       //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
446       //if (departurePort == apt) score++;
447       //flights.push_back(new FGScheduledFlight(callsign,
448         //                                fltrules,
449         //                                departurePort,
450         //                                arrivalPort,
451         //                                cruiseAlt,
452         //                                departureTime,
453         //                                arrivalTime,
454         //                                repeat));
455     if (requiredAircraft == "") {
456         char buffer[16];
457         snprintf(buffer, 16, "%d", acCounter);
458         requiredAircraft = buffer;
459     }
460     SG_LOG(SG_GENERAL, SG_DEBUG, "Adding flight: " << callsign       << " "
461                               << fltrules       << " "
462                               <<  departurePort << " "
463                               <<  arrivalPort   << " "
464                               <<  cruiseAlt     << " "
465                               <<  departureTime << " "
466                               <<  arrivalTime   << " "
467                               <<  repeat        << " " 
468                               <<  requiredAircraft);
469
470      flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
471                                                                  fltrules,
472                                                                  departurePort,
473                                                                  arrivalPort,
474                                                                  cruiseAlt,
475                                                                  departureTime,
476                                                                  arrivalTime,
477                                                                  repeat,
478                                                                  requiredAircraft));
479       requiredAircraft = "";
480   }
481   else if (element == string("aircraft"))
482     {
483       int proportion = (int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
484       int randval = rand() & 100;
485       if (randval < proportion) {
486           //scheduledAircraft.push_back(new FGAISchedule(mdl, 
487         //                                     livery, 
488         //                                     registration, 
489         //                                     heavy,
490         //                                     acType, 
491         //                                     airline, 
492         //                                     m_class, 
493         //                                     flighttype,
494         //                                     radius,
495         //                                     offset,
496         //                                     score,
497         //                                     flights));
498     if (requiredAircraft == "") {
499         char buffer[16];
500         snprintf(buffer, 16, "%d", acCounter);
501         requiredAircraft = buffer;
502     }
503     if (homePort == "") {
504         homePort = departurePort;
505     }
506             scheduledAircraft.push_back(new FGAISchedule(mdl, 
507                                                          livery, 
508                                                          homePort,
509                                                          registration, 
510                                                          requiredAircraft,
511                                                          heavy,
512                                                          acType, 
513                                                          airline, 
514                                                          m_class, 
515                                                          flighttype,
516                                                          radius,
517                                                          offset));
518
519      //  while(flights.begin() != flights.end()) {
520 //      flights.pop_back();
521 //       }
522         }
523     acCounter++;
524     requiredAircraft = "";
525     homePort = "";
526   //for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
527   //  {
528   //    delete (*flt);
529   //  }
530   //flights.clear();
531       SG_LOG( SG_GENERAL, SG_BULK, "Reading aircraft : " 
532               << registration 
533               << " with prioritization score " 
534               << score);
535       score = 0;
536     }
537 }
538
539 void  FGTrafficManager::data (const char * s, int len) {
540   string token = string(s,len);
541   //cout << "Character data " << string(s,len) << endl;
542   elementValueStack.back() += token;
543 }
544
545 void  FGTrafficManager::pi (const char * target, const char * data) {
546   //cout << "Processing instruction " << target << ' ' << data << endl;
547 }
548
549 void  FGTrafficManager::warning (const char * message, int line, int column) {
550   SG_LOG(SG_IO, SG_WARN, "Warning: " << message << " (" << line << ',' << column << ')');
551 }
552
553 void  FGTrafficManager::error (const char * message, int line, int column) {
554   SG_LOG(SG_IO, SG_ALERT, "Error: " << message << " (" << line << ',' << column << ')');
555 }
556