1 /******************************************************************************
3 * Written by Durk Talsma, started May 5, 2004.
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.
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.
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.
20 **************************************************************************/
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.
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
33 * 4) Each aircraft leaves at exactly the departure time.
34 * 5) Each aircraft arrives at exactly the specified arrival time.
37 *****************************************************************************/
53 #include <boost/foreach.hpp>
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>
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>
70 #include "TrafficMgr.hxx"
77 * Thread encapsulating parsing the traffic schedules.
79 class ScheduleParseThread : public SGThread
82 ScheduleParseThread(FGTrafficManager* traffic) :
83 _trafficManager(traffic),
90 // if we're destroyed while running, ensure the thread exits cleanly
91 ~ScheduleParseThread()
95 _cancelThread = true; // request cancellation so we don't wait ages
103 void setTrafficDir(const SGPath& trafficDirPath)
105 _trafficDirPath = trafficDirPath;
108 bool isFinished() const
110 SGGuard<SGMutex> g(_lock);
119 simgear::Dir trafficDir(_trafficDirPath);
120 simgear::PathList d = trafficDir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT);
122 BOOST_FOREACH(SGPath p, d) {
124 simgear::PathList trafficFiles = d2.children(simgear::Dir::TYPE_FILE, ".xml");
125 BOOST_FOREACH(SGPath xml, trafficFiles) {
126 _trafficManager->parseSchedule(xml);
131 } // of sub-directories in AI/Traffic iteration
133 // _trafficManager->parseSchedules(schedulesToRead);
134 SG_LOG(SG_AI, SG_INFO, "parsing traffic schedules took:" << st.elapsedMSec() << "msec");
136 SGGuard<SGMutex> g(_lock);
140 FGTrafficManager* _trafficManager;
141 mutable SGMutex _lock;
144 SGPath _trafficDirPath;
147 /******************************************************************************
149 *****************************************************************************/
150 FGTrafficManager::FGTrafficManager() :
153 waitingMetarTime(0.0),
154 enabled("/sim/traffic-manager/enabled"),
155 aiEnabled("/sim/ai/enabled"),
156 realWxEnabled("/environment/realwx/enabled"),
157 metarValid("/environment/metar/valid")
164 FGTrafficManager::~FGTrafficManager()
169 void FGTrafficManager::shutdown()
173 scheduleParser.reset();
180 // Save the heuristics data
181 bool saveData = false;
182 std::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");
188 if ((airport) != "") {
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);
196 cacheData.append(airport + "-cache.txt");
197 //cerr << "Saving AI traffic heuristics" << endl;
199 cachefile.open(cacheData.str().c_str());
200 cachefile << "[TrafficManagerCachedata:ref:2011:09:04]" << endl;
204 BOOST_FOREACH(FGAISchedule* acft, scheduledAircraft) {
206 cachefile << acft->getRegistration() << " "
207 << acft->getRunCount() << " "
208 << acft->getHits() << " "
209 << acft->getLastUsed() << endl;
216 scheduledAircraft.clear();
219 currAircraft = scheduledAircraft.begin();
224 /// caution - this is run on the helper thread to improve startup
225 /// responsiveness - do not access properties or global state from
226 /// here, since there's no locking protection at all
227 void FGTrafficManager::parseSchedule(const SGPath& path)
229 readXML(path.str(), *this);
232 void FGTrafficManager::init()
240 if (string(fgGetString("/sim/traffic-manager/datafile")) == string("")) {
241 scheduleParser.reset(new ScheduleParseThread(this));
242 scheduleParser->setTrafficDir(SGPath(globals->get_fg_root(), "AI/Traffic"));
243 scheduleParser->start();
245 fgSetBool("/sim/traffic-manager/heuristics", false);
246 SGPath path = string(fgGetString("/sim/traffic-manager/datafile"));
247 string ext = path.extension();
248 if (path.extension() == "xml") {
250 readXML(path.str(), *this);
252 } else if (path.extension() == "conf") {
254 readTimeTableFromFile(path);
257 SG_LOG(SG_AI, SG_ALERT,
258 "Unknown data format " << path.str()
267 void FGTrafficManager::finishInit()
270 SG_LOG(SG_AI, SG_INFO, "finishing AI-Traffic init");
273 // Do sorting and scoring separately, to take advantage of the "homeport" variable
274 BOOST_FOREACH(FGAISchedule* schedule, scheduledAircraft) {
275 schedule->setScore();
278 sort(scheduledAircraft.begin(), scheduledAircraft.end(),
280 currAircraft = scheduledAircraft.begin();
281 currAircraftClosest = scheduledAircraft.begin();
287 void FGTrafficManager::loadHeuristics()
289 if (!fgGetBool("/sim/traffic-manager/heuristics")) {
293 HeuristicMap heurMap;
294 //cerr << "Processing Heuristics" << endl;
295 // Load the heuristics data
296 SGPath cacheData(globals->get_fg_home());
297 cacheData.append("ai");
298 string airport = fgGetString("/sim/presets/airport-id");
299 if ((airport) != "") {
301 ::snprintf(buffer, 128, "%c/%c/%c/",
302 airport[0], airport[1], airport[2]);
303 cacheData.append(buffer);
304 cacheData.append(airport + "-cache.txt");
306 if (cacheData.exists()) {
307 std::ifstream data(cacheData.c_str());
309 if (revisionStr != "[TrafficManagerCachedata:ref:2011:09:04]") {
310 SG_LOG(SG_GENERAL, SG_ALERT,"Traffic Manager Warning: discarding outdated cachefile " <<
311 cacheData.c_str() << " for Airport " << airport);
314 Heuristic h; // = new Heuristic;
315 data >> h.registration >> h.runCount >> h.hits >> h.lastRun;
318 HeuristicMapIterator itr = heurMap.find(h.registration);
319 if (itr != heurMap.end()) {
320 SG_LOG(SG_GENERAL, SG_WARN,"Traffic Manager Warning: found duplicate tailnumber " <<
321 h.registration << " for AI aircraft");
323 heurMap[h.registration] = h;
330 for(currAircraft = scheduledAircraft.begin(); currAircraft != scheduledAircraft.end(); ++currAircraft) {
331 string registration = (*currAircraft)->getRegistration();
332 HeuristicMapIterator itr = heurMap.find(registration);
333 if (itr != heurMap.end()) {
334 (*currAircraft)->setrunCount(itr->second.runCount);
335 (*currAircraft)->setHits(itr->second.hits);
336 (*currAircraft)->setLastUsed(itr->second.lastRun);
341 bool FGTrafficManager::metarReady(double dt)
343 // wait for valid METAR (when realWX is enabled only), since we need
344 // to know the active runway
345 if (metarValid || !realWxEnabled)
347 waitingMetarTime = 0.0;
351 // METAR timeout: when running offline, remote server is down etc
352 if (waitingMetarStation != fgGetString("/environment/metar/station-id"))
354 // station has changed: wait for reply, restart timeout
355 waitingMetarTime = 0.0;
356 waitingMetarStation = fgGetString("/environment/metar/station-id");
360 // timeout elapsed (10 seconds)?
361 if (waitingMetarTime > 20.0)
366 waitingMetarTime += dt;
370 void FGTrafficManager::update(double dt)
374 if (inited || doingInit)
384 // traffic depends on AI module
393 if (!scheduleParser->isFinished()) {
400 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
401 if (scheduledAircraft.empty()) {
405 SGVec3d userCart = globals->get_aircraft_position_cart();
407 if (currAircraft == scheduledAircraft.end()) {
408 currAircraft = scheduledAircraft.begin();
410 //cerr << "Processing << " << (*currAircraft)->getRegistration() << " with score " << (*currAircraft)->getScore() << endl;
411 if (!((*currAircraft)->update(now, userCart))) {
412 (*currAircraft)->taint();
417 void FGTrafficManager::readTimeTableFromFile(SGPath infileName)
434 vector <string> tokens, depTime,arrTime;
435 vector <string>::iterator it;
436 std::ifstream infile(infileName.str().c_str());
438 infile.getline(buffer, 256);
442 //cerr << "Read line : " << buffer << endl;
443 buffString = string(buffer);
445 Tokenize(buffString, tokens, " \t");
446 //for (it = tokens.begin(); it != tokens.end(); it++) {
447 // cerr << "Tokens: " << *(it) << endl;
450 if (!tokens.empty()) {
451 if (tokens[0] == string("AC")) {
452 if (tokens.size() != 13) {
453 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
458 homePort = tokens[1];
459 registration = tokens[2];
460 if (tokens[11] == string("false")) {
467 flightReq = tokens[3] + tokens[5];
468 m_class = tokens[10];
469 FlightType = tokens[9];
470 radius = atof(tokens[8].c_str());
471 offset = atof(tokens[7].c_str());;
473 if (!FGAISchedule::validModelPath(model)) {
474 SG_LOG(SG_GENERAL, SG_WARN, "TrafficMgr: Missing model path:" <<
475 model << " from " << infileName.str());
478 SG_LOG(SG_GENERAL, SG_INFO, "Adding Aircraft" << model << " " << livery << " " << homePort << " "
479 << registration << " " << flightReq << " " << isHeavy
480 << " " << acType << " " << airline << " " << m_class
481 << " " << FlightType << " " << radius << " " << offset);
482 scheduledAircraft.push_back(new FGAISchedule(model,
494 } // of valid model path
496 if (tokens[0] == string("FLIGHT")) {
497 //cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
498 if (tokens.size() != 10) {
499 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
502 string callsign = tokens[1];
503 string fltrules = tokens[2];
504 string weekdays = tokens[3];
505 string departurePort = tokens[5];
506 string arrivalPort = tokens[7];
507 int cruiseAlt = atoi(tokens[8].c_str());
508 string depTimeGen = tokens[4];
509 string arrTimeGen = tokens[6];
510 string repeat = "WEEK";
511 string requiredAircraft = tokens[9];
513 if (weekdays.size() != 7) {
514 SG_LOG(SG_GENERAL, SG_ALERT, "Found misconfigured weekdays string" << weekdays);
519 Tokenize(depTimeGen, depTime, ":");
520 Tokenize(arrTimeGen, arrTime, ":");
521 double dep = atof(depTime[0].c_str()) + (atof(depTime[1].c_str()) / 60.0);
522 double arr = atof(arrTime[0].c_str()) + (atof(arrTime[1].c_str()) / 60.0);
523 //cerr << "Using " << dep << " " << arr << endl;
524 bool arrivalWeekdayNeedsIncrement = false;
526 arrivalWeekdayNeedsIncrement = true;
528 for (int i = 0; i < 7; i++) {
530 if (weekdays[i] != '.') {
532 snprintf(buffer, 4, "%d/", j);
533 string departureTime = string(buffer) + depTimeGen + string(":00");
535 if (!arrivalWeekdayNeedsIncrement) {
536 arrivalTime = string(buffer) + arrTimeGen + string(":00");
538 if (arrivalWeekdayNeedsIncrement && i != 6 ) {
539 snprintf(buffer, 4, "%d/", j+1);
540 arrivalTime = string(buffer) + arrTimeGen + string(":00");
542 if (arrivalWeekdayNeedsIncrement && i == 6 ) {
543 snprintf(buffer, 4, "%d/", 0);
544 arrivalTime = string(buffer) + arrTimeGen + string(":00");
546 SG_LOG(SG_GENERAL, SG_ALERT, "Adding flight " << callsign << " "
548 << departurePort << " "
549 << arrivalPort << " "
551 << departureTime << " "
552 << arrivalTime << " "
554 << requiredAircraft);
556 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
575 void FGTrafficManager::Tokenize(const string& str,
576 vector<string>& tokens,
577 const string& delimiters)
579 // Skip delimiters at beginning.
580 string::size_type lastPos = str.find_first_not_of(delimiters, 0);
581 // Find first "non-delimiter".
582 string::size_type pos = str.find_first_of(delimiters, lastPos);
584 while (string::npos != pos || string::npos != lastPos)
586 // Found a token, add it to the vector.
587 tokens.push_back(str.substr(lastPos, pos - lastPos));
588 // Skip delimiters. Note the "not_of"
589 lastPos = str.find_first_not_of(delimiters, pos);
590 // Find next "non-delimiter"
591 pos = str.find_first_of(delimiters, lastPos);
596 void FGTrafficManager::startXML()
598 //cout << "Start XML" << endl;
599 requiredAircraft = "";
603 void FGTrafficManager::endXML()
605 //cout << "End XML" << endl;
608 void FGTrafficManager::startElement(const char *name,
609 const XMLAttributes & atts)
612 //cout << "Start element " << name << endl;
613 //FGTrafficManager temp;
614 //for (int i = 0; i < atts.size(); i++)
615 // if (string(atts.getName(i)) == string("include"))
616 attval = atts.getValue("include");
618 //cout << "including " << attval << endl;
619 SGPath path = globals->get_fg_root();
620 path.append("/Traffic/");
622 readXML(path.str(), *this);
624 elementValueStack.push_back("");
625 // cout << " " << atts.getName(i) << '=' << atts.getValue(i) << endl;
628 void FGTrafficManager::endElement(const char *name)
630 //cout << "End element " << name << endl;
631 const string & value = elementValueStack.back();
633 if (!strcmp(name, "model"))
635 else if (!strcmp(name, "livery"))
637 else if (!strcmp(name, "home-port"))
639 else if (!strcmp(name, "registration"))
640 registration = value;
641 else if (!strcmp(name, "airline"))
643 else if (!strcmp(name, "actype"))
645 else if (!strcmp(name, "required-aircraft"))
646 requiredAircraft = value;
647 else if (!strcmp(name, "flighttype"))
649 else if (!strcmp(name, "radius"))
650 radius = atoi(value.c_str());
651 else if (!strcmp(name, "offset"))
652 offset = atoi(value.c_str());
653 else if (!strcmp(name, "performance-class"))
655 else if (!strcmp(name, "heavy")) {
656 if (value == string("true"))
660 } else if (!strcmp(name, "callsign"))
662 else if (!strcmp(name, "fltrules"))
664 else if (!strcmp(name, "port"))
666 else if (!strcmp(name, "time"))
668 else if (!strcmp(name, "departure")) {
669 departurePort = port;
670 departureTime = timeString;
671 } else if (!strcmp(name, "cruise-alt"))
672 cruiseAlt = atoi(value.c_str());
673 else if (!strcmp(name, "arrival")) {
675 arrivalTime = timeString;
676 } else if (!strcmp(name, "repeat"))
678 else if (!strcmp(name, "flight")) {
679 // We have loaded and parsed all the information belonging to this flight
680 // so we temporarily store it.
681 //cerr << "Pusing back flight " << callsign << endl;
682 //cerr << callsign << " " << fltrules << " "<< departurePort << " " << arrivalPort << " "
683 // << cruiseAlt << " " << departureTime<< " "<< arrivalTime << " " << repeat << endl;
685 //Prioritize aircraft
686 string apt = fgGetString("/sim/presets/airport-id");
687 //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
688 //if (departurePort == apt) score++;
689 //flights.push_back(new FGScheduledFlight(callsign,
697 if (requiredAircraft == "") {
699 snprintf(buffer, 16, "%d", acCounter);
700 requiredAircraft = buffer;
702 SG_LOG(SG_GENERAL, SG_DEBUG, "Adding flight: " << callsign << " "
704 << departurePort << " "
705 << arrivalPort << " "
707 << departureTime << " "
708 << arrivalTime << " " << repeat << " " << requiredAircraft);
709 // For database maintainance purposes, it may be convenient to
711 if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
712 SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump FLIGHT," << callsign << ","
714 << departurePort << ","
715 << arrivalPort << ","
717 << departureTime << ","
718 << arrivalTime << "," << repeat << "," << requiredAircraft);
720 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
729 requiredAircraft = "";
730 } else if (!strcmp(name, "aircraft")) {
734 elementValueStack.pop_back();
737 void FGTrafficManager::endAircraft()
739 string isHeavy = heavy ? "true" : "false";
741 if (missingModels.find(mdl) != missingModels.end()) {
742 // don't stat() or warn again
743 requiredAircraft = homePort = "";
747 if (!FGAISchedule::validModelPath(mdl)) {
748 missingModels.insert(mdl);
749 SG_LOG(SG_GENERAL, SG_WARN, "TrafficMgr: Missing model path:" << mdl);
750 requiredAircraft = homePort = "";
755 (int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
756 int randval = rand() & 100;
757 if (randval > proportion) {
758 requiredAircraft = homePort = "";
762 if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
763 SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump AC," << homePort << "," << registration << "," << requiredAircraft
764 << "," << acType << "," << livery << ","
765 << airline << "," << m_class << "," << offset << "," << radius << "," << flighttype << "," << isHeavy << "," << mdl);
768 if (requiredAircraft == "") {
770 snprintf(buffer, 16, "%d", acCounter);
771 requiredAircraft = buffer;
773 if (homePort == "") {
774 homePort = departurePort;
777 scheduledAircraft.push_back(new FGAISchedule(mdl,
790 requiredAircraft = "";
795 void FGTrafficManager::data(const char *s, int len)
797 string token = string(s, len);
798 //cout << "Character data " << string(s,len) << endl;
799 elementValueStack.back() += token;
802 void FGTrafficManager::pi(const char *target, const char *data)
804 //cout << "Processing instruction " << target << ' ' << data << endl;
807 void FGTrafficManager::warning(const char *message, int line, int column)
809 SG_LOG(SG_IO, SG_WARN,
810 "Warning: " << message << " (" << line << ',' << column << ')');
813 void FGTrafficManager::error(const char *message, int line, int column)
815 SG_LOG(SG_IO, SG_ALERT,
816 "Error: " << message << " (" << line << ',' << column << ')');