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