]> git.mxchange.org Git - flightgear.git/blob - src/Traffic/TrafficMgr.cxx
5c56d545103b9731786063dcd788107e057fe686
[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 #include <boost/foreach.hpp>
54
55 #include <simgear/compiler.h>
56 #include <simgear/misc/sg_path.hxx>
57 #include <simgear/misc/sg_dir.hxx>
58 #include <simgear/props/props.hxx>
59 #include <simgear/structure/subsystem_mgr.hxx>
60 #include <simgear/xml/easyxml.hxx>
61 #include <simgear/threads/SGThread.hxx>
62 #include <simgear/threads/SGGuard.hxx>
63
64 #include <AIModel/AIAircraft.hxx>
65 #include <AIModel/AIFlightPlan.hxx>
66 #include <AIModel/AIBase.hxx>
67 #include <Airports/simple.hxx>
68 #include <Main/fg_init.hxx>
69
70 #include "TrafficMgr.hxx"
71
72 using std::sort;
73 using std::strcmp;
74 using std::endl;
75
76 /**
77  * Thread encapsulating parsing the traffic schedules. 
78  */
79 class ScheduleParseThread : public SGThread
80 {
81 public:
82   ScheduleParseThread(FGTrafficManager* traffic) :
83     _trafficManager(traffic),
84     _isFinished(false),
85     _cancelThread(false)
86   {
87     
88   }
89   
90   // if we're destroyed while running, ensure the thread exits cleanly
91   ~ScheduleParseThread()
92   {
93     _lock.lock();
94     if (!_isFinished) {
95       _cancelThread = true; // request cancellation so we don't wait ages
96       _lock.unlock();
97       join();
98     } else {
99       _lock.unlock();
100     }
101   }
102   
103   void setTrafficDir(const SGPath& trafficDirPath)
104   {
105     _trafficDirPath = trafficDirPath;
106   }
107   
108   bool isFinished() const
109   {
110     SGGuard<SGMutex> g(_lock);
111     return _isFinished;
112   }
113   
114   virtual void run()
115   {
116     SGTimeStamp st;
117     st.stamp();
118     
119     simgear::Dir trafficDir(_trafficDirPath);
120     simgear::PathList d = trafficDir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT);
121     
122     BOOST_FOREACH(SGPath p, d) {
123       simgear::Dir d2(p);
124       simgear::PathList trafficFiles = d2.children(simgear::Dir::TYPE_FILE, ".xml");
125       BOOST_FOREACH(SGPath xml, trafficFiles) {
126         _trafficManager->parseSchedule(xml);
127         if (_cancelThread) {
128           return;
129         }
130       }
131     } // of sub-directories in AI/Traffic iteration
132     
133   //  _trafficManager->parseSchedules(schedulesToRead);
134     SG_LOG(SG_AI, SG_INFO, "parsing traffic schedules took:" << st.elapsedMSec() << "msec");
135     
136     SGGuard<SGMutex> g(_lock);
137     _isFinished = true;
138   }
139 private:
140   FGTrafficManager* _trafficManager;
141   mutable SGMutex _lock;
142   bool _isFinished;
143   bool _cancelThread;
144   SGPath _trafficDirPath;
145 };
146
147 /******************************************************************************
148  * TrafficManager
149  *****************************************************************************/
150 FGTrafficManager::FGTrafficManager() :
151   inited(false),
152   doingInit(false),
153   waitingMetarTime(0.0),
154   cruiseAlt(0),
155   score(0),
156   runCount(0),
157   acCounter(0),
158   radius(0),
159   offset(0),
160   heavy(false),
161   enabled("/sim/traffic-manager/enabled"),
162   aiEnabled("/sim/ai/enabled"),
163   realWxEnabled("/environment/realwx/enabled"),
164   metarValid("/environment/metar/valid")
165 {
166 }
167
168 FGTrafficManager::~FGTrafficManager()
169 {
170     shutdown();
171 }
172
173 void FGTrafficManager::shutdown()
174 {
175     if (!inited) {
176       if (doingInit) {
177         scheduleParser.reset();
178         doingInit = false;
179       }
180       
181       return;
182     }
183   
184     // Save the heuristics data
185     bool saveData = false;
186     std::ofstream cachefile;
187     if (fgGetBool("/sim/traffic-manager/heuristics")) {
188         SGPath cacheData(globals->get_fg_home());
189         cacheData.append("ai");
190         const string airport = fgGetString("/sim/presets/airport-id");
191
192         if ((airport) != "") {
193             char buffer[128];
194             ::snprintf(buffer, 128, "%c/%c/%c/",
195                        airport[0], airport[1], airport[2]);
196             cacheData.append(buffer);
197             if (!cacheData.exists()) {
198                 cacheData.create_dir(0777);
199             }
200             cacheData.append(airport + "-cache.txt");
201             //cerr << "Saving AI traffic heuristics" << endl;
202             saveData = true;
203             cachefile.open(cacheData.str().c_str());
204             cachefile << "[TrafficManagerCachedata:ref:2011:09:04]" << endl;
205         }
206     }
207   
208     BOOST_FOREACH(FGAISchedule* acft, scheduledAircraft) {
209         if (saveData) {
210             cachefile << acft->getRegistration() << " "
211                 << acft->getRunCount() << " "
212                 << acft->getHits() << " "
213                 << acft->getLastUsed() << endl;
214         }
215         delete acft;
216     }
217     if (saveData) {
218         cachefile.close();
219     }
220     scheduledAircraft.clear();
221     flights.clear();
222
223     currAircraft = scheduledAircraft.begin();
224     doingInit = false;
225     inited = false;
226 }
227
228 /// caution - this is run on the helper thread to improve startup
229 /// responsiveness - do not access properties or global state from
230 /// here, since there's no locking protection at all
231 void FGTrafficManager::parseSchedule(const SGPath& path)
232 {
233   readXML(path.str(), *this);
234 }
235
236 void FGTrafficManager::init()
237 {
238     if (!enabled) {
239       return;
240     }
241
242     assert(!doingInit);
243     doingInit = true;
244     if (string(fgGetString("/sim/traffic-manager/datafile")).empty()) {
245         scheduleParser.reset(new ScheduleParseThread(this));
246         scheduleParser->setTrafficDir(SGPath(globals->get_fg_root(), "AI/Traffic"));      
247         scheduleParser->start();
248     } else {
249         fgSetBool("/sim/traffic-manager/heuristics", false);
250         SGPath path = string(fgGetString("/sim/traffic-manager/datafile"));
251         string ext = path.extension();
252         if (path.extension() == "xml") {
253             if (path.exists()) {
254                 readXML(path.str(), *this);
255             }
256         } else if (path.extension() == "conf") {
257             if (path.exists()) {
258                 readTimeTableFromFile(path);
259             }
260         } else {
261              SG_LOG(SG_AI, SG_ALERT,
262                                "Unknown data format " << path.str()
263                                 << " for traffic");
264         }
265         //exit(1);
266     }
267 }
268
269
270
271 void FGTrafficManager::finishInit()
272 {
273     assert(doingInit);
274     SG_LOG(SG_AI, SG_INFO, "finishing AI-Traffic init");
275     loadHeuristics();
276     
277     // Do sorting and scoring separately, to take advantage of the "homeport" variable
278     BOOST_FOREACH(FGAISchedule* schedule, scheduledAircraft) {
279         schedule->setScore();
280     }
281     
282     sort(scheduledAircraft.begin(), scheduledAircraft.end(),
283          compareSchedules);
284     currAircraft = scheduledAircraft.begin();
285     currAircraftClosest = scheduledAircraft.begin();
286     
287     doingInit = false;
288     inited = true;
289 }
290
291 void FGTrafficManager::loadHeuristics()
292 {
293     if (!fgGetBool("/sim/traffic-manager/heuristics")) {
294         return;
295     }
296   
297     HeuristicMap heurMap;
298     //cerr << "Processing Heuristics" << endl;
299     // Load the heuristics data
300     SGPath cacheData(globals->get_fg_home());
301     cacheData.append("ai");
302     string airport = fgGetString("/sim/presets/airport-id");
303     if ((airport) != "") {
304       char buffer[128];
305       ::snprintf(buffer, 128, "%c/%c/%c/",
306                  airport[0], airport[1], airport[2]);
307       cacheData.append(buffer);
308       cacheData.append(airport + "-cache.txt");
309       string revisionStr;
310       if (cacheData.exists()) {
311         std::ifstream data(cacheData.c_str());
312         data >> revisionStr;
313         if (revisionStr != "[TrafficManagerCachedata:ref:2011:09:04]") {
314           SG_LOG(SG_AI, SG_ALERT,"Traffic Manager Warning: discarding outdated cachefile " <<
315                  cacheData.c_str() << " for Airport " << airport);
316         } else {
317           while (1) {
318             Heuristic h; // = new Heuristic;
319             data >> h.registration >> h.runCount >> h.hits >> h.lastRun;
320             if (data.eof())
321               break;
322             HeuristicMapIterator itr = heurMap.find(h.registration);
323             if (itr != heurMap.end()) {
324               SG_LOG(SG_AI, SG_WARN,"Traffic Manager Warning: found duplicate tailnumber " <<
325                      h.registration << " for AI aircraft");
326             } else {
327               heurMap[h.registration] = h;
328             }
329           }
330         }
331       }
332     } 
333     
334   for(currAircraft = scheduledAircraft.begin(); currAircraft != scheduledAircraft.end(); ++currAircraft) {
335         const string& registration = (*currAircraft)->getRegistration();
336         HeuristicMapIterator itr = heurMap.find(registration);
337         if (itr != heurMap.end()) {
338             (*currAircraft)->setrunCount(itr->second.runCount);
339             (*currAircraft)->setHits(itr->second.hits);
340             (*currAircraft)->setLastUsed(itr->second.lastRun);
341         }
342     }
343 }
344
345 bool FGTrafficManager::metarReady(double dt)
346 {
347     // wait for valid METAR (when realWX is enabled only), since we need
348     // to know the active runway
349     if (metarValid || !realWxEnabled)
350     {
351         waitingMetarTime = 0.0;
352         return true;
353     }
354
355     // METAR timeout: when running offline, remote server is down etc
356     if (waitingMetarStation != fgGetString("/environment/metar/station-id"))
357     {
358         // station has changed: wait for reply, restart timeout
359         waitingMetarTime = 0.0;
360         waitingMetarStation = fgGetString("/environment/metar/station-id");
361         return false;
362     }
363
364     // timeout elapsed (10 seconds)?
365     if (waitingMetarTime > 20.0)
366     {
367         return true;
368     }
369
370     waitingMetarTime += dt;
371     return false;
372 }
373
374 void FGTrafficManager::update(double dt)
375 {
376     if (!enabled)
377     {
378         if (inited || doingInit)
379             shutdown();
380         return;
381     }
382
383     if (!metarReady(dt))
384         return;
385
386     if (!aiEnabled)
387     {
388         // traffic depends on AI module
389         aiEnabled = true;
390     }
391
392     if (!inited) {
393         if (!doingInit) {
394             init();
395         }
396         
397         if (!scheduleParser->isFinished()) {
398           return;
399         }
400       
401         finishInit();
402     }
403         
404     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
405     if (scheduledAircraft.empty()) {
406         return;
407     }
408
409     SGVec3d userCart = globals->get_aircraft_position_cart();
410
411     if (currAircraft == scheduledAircraft.end()) {
412         currAircraft = scheduledAircraft.begin();
413     }
414
415     //cerr << "Processing << " << (*currAircraft)->getRegistration() << " with score " << (*currAircraft)->getScore() << endl;
416     if ((*currAircraft)->update(now, userCart)) {
417         // schedule is done - process another aircraft in next iteration
418         currAircraft++;
419     }
420 }
421
422 void FGTrafficManager::readTimeTableFromFile(SGPath infileName)
423 {
424     string model;
425     string livery;
426     string homePort;
427     string registration;
428     string flightReq;
429     bool   isHeavy;
430     string acType;
431     string airline;
432     string m_class;
433     string FlightType;
434     double radius;
435     double offset;
436
437     char buffer[256];
438     string buffString;
439     vector <string> tokens, depTime,arrTime;
440     vector <string>::iterator it;
441     std::ifstream infile(infileName.str().c_str());
442     while (1) {
443          infile.getline(buffer, 256);
444          if (infile.eof()) {
445              break;
446          }
447          //cerr << "Read line : " << buffer << endl;
448          buffString = string(buffer);
449          tokens.clear();
450          Tokenize(buffString, tokens, " \t");
451          //for (it = tokens.begin(); it != tokens.end(); it++) {
452          //    cerr << "Tokens: " << *(it) << endl;
453          //}
454          //cerr << endl;
455          if (!tokens.empty()) {
456              if (tokens[0] == string("AC")) {
457                  if (tokens.size() != 13) {
458                      SG_LOG(SG_AI, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
459                      exit(1);
460                  }
461                  model          = tokens[12];
462                  livery         = tokens[6];
463                  homePort       = tokens[1];
464                  registration   = tokens[2];
465                  if (tokens[11] == string("false")) {
466                      isHeavy = false;
467                  } else {
468                      isHeavy = true;
469                  }
470                  acType         = tokens[4];
471                  airline        = tokens[5];
472                  flightReq      = tokens[3] + tokens[5];
473                  m_class        = tokens[10];
474                  FlightType     = tokens[9];
475                  radius         = atof(tokens[8].c_str());
476                  offset         = atof(tokens[7].c_str());;
477                  
478                  if (!FGAISchedule::validModelPath(model)) {
479                      SG_LOG(SG_AI, SG_WARN, "TrafficMgr: Missing model path:" <<
480                             model << " from " << infileName.str());
481                  } else {
482                  
483                  SG_LOG(SG_AI, SG_INFO, "Adding Aircraft" << model << " " << livery << " " << homePort << " "
484                                                                 << registration << " " << flightReq << " " << isHeavy 
485                                                                 << " " << acType << " " << airline << " " << m_class 
486                                                                 << " " << FlightType << " " << radius << " " << offset);
487                  scheduledAircraft.push_back(new FGAISchedule(model, 
488                                                               livery, 
489                                                               homePort,
490                                                               registration, 
491                                                               flightReq,
492                                                               isHeavy,
493                                                               acType, 
494                                                               airline, 
495                                                               m_class, 
496                                                               FlightType,
497                                                               radius,
498                                                               offset));
499                  } // of valid model path
500              }
501              if (tokens[0] == string("FLIGHT")) {
502                  //cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
503                  if (tokens.size() != 10) {
504                      SG_LOG(SG_AI, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
505                      exit(1);
506                  }
507                  string callsign = tokens[1];
508                  string fltrules = tokens[2];
509                  string weekdays = tokens[3];
510                  string departurePort = tokens[5];
511                  string arrivalPort   = tokens[7];
512                  int    cruiseAlt     = atoi(tokens[8].c_str());
513                  string depTimeGen    = tokens[4];
514                  string arrTimeGen    = tokens[6];
515                  string repeat        = "WEEK";
516                  string requiredAircraft = tokens[9];
517
518                  if (weekdays.size() != 7) {
519                      SG_LOG(SG_AI, SG_ALERT, "Found misconfigured weekdays string" << weekdays);
520                      exit(1);
521                  }
522                  depTime.clear();
523                  arrTime.clear();
524                  Tokenize(depTimeGen, depTime, ":");
525                  Tokenize(arrTimeGen, arrTime, ":");
526                  double dep = atof(depTime[0].c_str()) + (atof(depTime[1].c_str()) / 60.0);
527                  double arr = atof(arrTime[0].c_str()) + (atof(arrTime[1].c_str()) / 60.0);
528                  //cerr << "Using " << dep << " " << arr << endl;
529                  bool arrivalWeekdayNeedsIncrement = false;
530                  if (arr < dep) {
531                        arrivalWeekdayNeedsIncrement = true;
532                  }
533                  for (int i = 0; i < 7; i++) {
534                      int j = i+1;
535                      if (weekdays[i] != '.') {
536                          char buffer[4];
537                          snprintf(buffer, 4, "%d/", j);
538                          string departureTime = string(buffer) + depTimeGen + string(":00");
539                          string arrivalTime;
540                          if (!arrivalWeekdayNeedsIncrement) {
541                              arrivalTime   = string(buffer) + arrTimeGen + string(":00");
542                          }
543                          if (arrivalWeekdayNeedsIncrement && i != 6 ) {
544                              snprintf(buffer, 4, "%d/", j+1);
545                              arrivalTime   = string(buffer) + arrTimeGen + string(":00");
546                          }
547                          if (arrivalWeekdayNeedsIncrement && i == 6 ) {
548                              snprintf(buffer, 4, "%d/", 0);
549                              arrivalTime   = string(buffer) + arrTimeGen  + string(":00");
550                          }
551                          SG_LOG(SG_AI, SG_ALERT, "Adding flight " << callsign       << " "
552                                                       << fltrules       << " "
553                                                       <<  departurePort << " "
554                                                       <<  arrivalPort   << " "
555                                                       <<  cruiseAlt     << " "
556                                                       <<  departureTime << " "
557                                                       <<  arrivalTime   << " "
558                                                       << repeat        << " " 
559                                                       <<  requiredAircraft);
560
561                          flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
562                                                                  fltrules,
563                                                                  departurePort,
564                                                                  arrivalPort,
565                                                                  cruiseAlt,
566                                                                  departureTime,
567                                                                  arrivalTime,
568                                                                  repeat,
569                                                                  requiredAircraft));
570                     }
571                 }
572              }
573          }
574
575     }
576     //exit(1);
577 }
578
579
580 void FGTrafficManager::Tokenize(const string& str,
581                       vector<string>& tokens,
582                       const string& delimiters)
583 {
584     // Skip delimiters at beginning.
585     string::size_type lastPos = str.find_first_not_of(delimiters, 0);
586     // Find first "non-delimiter".
587     string::size_type pos     = str.find_first_of(delimiters, lastPos);
588
589     while (string::npos != pos || string::npos != lastPos)
590     {
591         // Found a token, add it to the vector.
592         tokens.push_back(str.substr(lastPos, pos - lastPos));
593         // Skip delimiters.  Note the "not_of"
594         lastPos = str.find_first_not_of(delimiters, pos);
595         // Find next "non-delimiter"
596         pos = str.find_first_of(delimiters, lastPos);
597     }
598 }
599
600
601 void FGTrafficManager::startXML()
602 {
603     //cout << "Start XML" << endl;
604     requiredAircraft = "";
605     homePort = "";
606 }
607
608 void FGTrafficManager::endXML()
609 {
610     //cout << "End XML" << endl;
611 }
612
613 void FGTrafficManager::startElement(const char *name,
614                                     const XMLAttributes & atts)
615 {
616     const char *attval;
617     //cout << "Start element " << name << endl;
618     //FGTrafficManager temp;
619     //for (int i = 0; i < atts.size(); i++)
620     //  if (string(atts.getName(i)) == string("include"))
621     attval = atts.getValue("include");
622     if (attval != 0) {
623         //cout << "including " << attval << endl;
624         SGPath path = globals->get_fg_root();
625         path.append("/Traffic/");
626         path.append(attval);
627         readXML(path.str(), *this);
628     }
629     elementValueStack.push_back("");
630     //  cout << "  " << atts.getName(i) << '=' << atts.getValue(i) << endl; 
631 }
632
633 void FGTrafficManager::endElement(const char *name)
634 {
635     //cout << "End element " << name << endl;
636     const string & value = elementValueStack.back();
637
638     if (!strcmp(name, "model"))
639         mdl = value;
640     else if (!strcmp(name, "livery"))
641         livery = value;
642     else if (!strcmp(name, "home-port"))
643         homePort = value;
644     else if (!strcmp(name, "registration"))
645         registration = value;
646     else if (!strcmp(name, "airline"))
647         airline = value;
648     else if (!strcmp(name, "actype"))
649         acType = value;
650     else if (!strcmp(name, "required-aircraft"))
651         requiredAircraft = value;
652     else if (!strcmp(name, "flighttype"))
653         flighttype = value;
654     else if (!strcmp(name, "radius"))
655         radius = atoi(value.c_str());
656     else if (!strcmp(name, "offset"))
657         offset = atoi(value.c_str());
658     else if (!strcmp(name, "performance-class"))
659         m_class = value;
660     else if (!strcmp(name, "heavy")) {
661         if (value == string("true"))
662             heavy = true;
663         else
664             heavy = false;
665     } else if (!strcmp(name, "callsign"))
666         callsign = value;
667     else if (!strcmp(name, "fltrules"))
668         fltrules = value;
669     else if (!strcmp(name, "port"))
670         port = value;
671     else if (!strcmp(name, "time"))
672         timeString = value;
673     else if (!strcmp(name, "departure")) {
674         departurePort = port;
675         departureTime = timeString;
676     } else if (!strcmp(name, "cruise-alt"))
677         cruiseAlt = atoi(value.c_str());
678     else if (!strcmp(name, "arrival")) {
679         arrivalPort = port;
680         arrivalTime = timeString;
681     } else if (!strcmp(name, "repeat"))
682         repeat = value;
683     else if (!strcmp(name, "flight")) {
684         // We have loaded and parsed all the information belonging to this flight
685         // so we temporarily store it. 
686         //cerr << "Pusing back flight " << callsign << endl;
687         //cerr << callsign  <<  " " << fltrules     << " "<< departurePort << " " <<  arrivalPort << " "
688         //   << cruiseAlt <<  " " << departureTime<< " "<< arrivalTime   << " " << repeat << endl;
689
690         //Prioritize aircraft 
691         string apt = fgGetString("/sim/presets/airport-id");
692         //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
693         //if (departurePort == apt) score++;
694         //flights.push_back(new FGScheduledFlight(callsign,
695         //                                fltrules,
696         //                                departurePort,
697         //                                arrivalPort,
698         //                                cruiseAlt,
699         //                                departureTime,
700         //                                arrivalTime,
701         //                                repeat));
702         if (requiredAircraft == "") {
703             char buffer[16];
704             snprintf(buffer, 16, "%d", acCounter);
705             requiredAircraft = buffer;
706         }
707         SG_LOG(SG_AI, SG_DEBUG, "Adding flight: " << callsign << " "
708                << fltrules << " "
709                << departurePort << " "
710                << arrivalPort << " "
711                << cruiseAlt << " "
712                << departureTime << " "
713                << arrivalTime << " " << repeat << " " << requiredAircraft);
714         // For database maintainance purposes, it may be convenient to
715         // 
716         if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
717              SG_LOG(SG_AI, SG_ALERT, "Traffic Dump FLIGHT," << callsign << ","
718                           << fltrules << ","
719                           << departurePort << ","
720                           << arrivalPort << ","
721                           << cruiseAlt << ","
722                           << departureTime << ","
723                           << arrivalTime << "," << repeat << "," << requiredAircraft);
724         }
725         flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
726                                                                   fltrules,
727                                                                   departurePort,
728                                                                   arrivalPort,
729                                                                   cruiseAlt,
730                                                                   departureTime,
731                                                                   arrivalTime,
732                                                                   repeat,
733                                                                   requiredAircraft));
734         requiredAircraft = "";
735     } else if (!strcmp(name, "aircraft")) {
736         endAircraft();
737     }
738     
739     elementValueStack.pop_back();
740 }
741
742 void FGTrafficManager::endAircraft()
743 {
744     string isHeavy = heavy ? "true" : "false";
745
746     if (missingModels.find(mdl) != missingModels.end()) {
747     // don't stat() or warn again
748         requiredAircraft = homePort = "";
749         return;
750     }
751     
752     if (!FGAISchedule::validModelPath(mdl)) {
753         missingModels.insert(mdl);
754         SG_LOG(SG_AI, SG_WARN, "TrafficMgr: Missing model path:" << mdl);
755         requiredAircraft = homePort = "";
756         return;
757     }
758         
759     int proportion =
760         (int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
761     int randval = rand() & 100;
762     if (randval > proportion) {
763         requiredAircraft = homePort = "";
764         return;
765     }
766     
767     if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
768         SG_LOG(SG_AI, SG_ALERT, "Traffic Dump AC," << homePort << "," << registration << "," << requiredAircraft
769                << "," << acType << "," << livery << "," 
770                << airline << ","  << m_class << "," << offset << "," << radius << "," << flighttype << "," << isHeavy << "," << mdl);
771     }
772
773     if (requiredAircraft == "") {
774         char buffer[16];
775         snprintf(buffer, 16, "%d", acCounter);
776         requiredAircraft = buffer;
777     }
778     if (homePort == "") {
779         homePort = departurePort;
780     }
781     
782     scheduledAircraft.push_back(new FGAISchedule(mdl,
783                                                  livery,
784                                                  homePort,
785                                                  registration,
786                                                  requiredAircraft,
787                                                  heavy,
788                                                  acType,
789                                                  airline,
790                                                  m_class,
791                                                  flighttype,
792                                                  radius, offset));
793             
794     acCounter++;
795     requiredAircraft = "";
796     homePort = "";
797     score = 0;
798 }
799     
800 void FGTrafficManager::data(const char *s, int len)
801 {
802     string token = string(s, len);
803     //cout << "Character data " << string(s,len) << endl;
804     elementValueStack.back() += token;
805 }
806
807 void FGTrafficManager::pi(const char *target, const char *data)
808 {
809     //cout << "Processing instruction " << target << ' ' << data << endl;
810 }
811
812 void FGTrafficManager::warning(const char *message, int line, int column)
813 {
814     SG_LOG(SG_IO, SG_WARN,
815            "Warning: " << message << " (" << line << ',' << column << ')');
816 }
817
818 void FGTrafficManager::error(const char *message, int line, int column)
819 {
820     SG_LOG(SG_IO, SG_ALERT,
821            "Error: " << message << " (" << line << ',' << column << ')');
822 }