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