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