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/route/waypoint.hxx>
60 #include <simgear/structure/subsystem_mgr.hxx>
61 #include <simgear/xml/easyxml.hxx>
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>
71 #include "TrafficMgr.hxx"
76 /******************************************************************************
78 *****************************************************************************/
79 FGTrafficManager::FGTrafficManager() :
82 enabled("/sim/traffic-manager/enabled"),
83 aiEnabled("/sim/ai/enabled"),
84 realWxEnabled("/environment/realwx/enabled"),
85 metarValid("/environment/metar/valid")
92 FGTrafficManager::~FGTrafficManager()
97 void FGTrafficManager::shutdown()
99 // Save the heuristics data
100 bool saveData = false;
102 if (fgGetBool("/sim/traffic-manager/heuristics")) {
103 SGPath cacheData(fgGetString("/sim/fg-home"));
104 cacheData.append("ai");
105 string airport = fgGetString("/sim/presets/airport-id");
107 if ((airport) != "") {
109 ::snprintf(buffer, 128, "%c/%c/%c/",
110 airport[0], airport[1], airport[2]);
111 cacheData.append(buffer);
112 if (!cacheData.exists()) {
113 cacheData.create_dir(0777);
115 cacheData.append(airport + "-cache.txt");
116 //cerr << "Saving AI traffic heuristics" << endl;
118 cachefile.open(cacheData.str().c_str());
119 cachefile << "[TrafficManagerCachedata:ref:2011:09:04]" << endl;
122 for (ScheduleVectorIterator sched = scheduledAircraft.begin();
123 sched != scheduledAircraft.end(); sched++) {
125 cachefile << (*sched)->getRegistration() << " "
126 << (*sched)->getRunCount() << " "
127 << (*sched)->getHits() << " "
128 << (*sched)->getLastUsed() << endl;
135 scheduledAircraft.clear();
139 currAircraft = scheduledAircraft.begin();
145 void FGTrafficManager::init()
153 if (string(fgGetString("/sim/traffic-manager/datafile")) == string("")) {
154 simgear::Dir trafficDir(SGPath(globals->get_fg_root(), "AI/Traffic"));
155 simgear::PathList d = trafficDir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT);
157 BOOST_FOREACH(SGPath p, d) {
159 simgear::PathList trafficFiles = d2.children(simgear::Dir::TYPE_FILE, ".xml");
160 schedulesToRead.insert(schedulesToRead.end(), trafficFiles.begin(), trafficFiles.end());
163 fgSetBool("/sim/traffic-manager/heuristics", false);
164 SGPath path = string(fgGetString("/sim/traffic-manager/datafile"));
165 string ext = path.extension();
166 if (path.extension() == "xml") {
168 readXML(path.str(), *this);
170 } else if (path.extension() == "conf") {
172 readTimeTableFromFile(path);
175 SG_LOG(SG_AI, SG_ALERT,
176 "Unknown data format " << path.str()
183 void FGTrafficManager::initStep()
186 if (schedulesToRead.empty()) {
191 SGPath path = schedulesToRead.front();
192 schedulesToRead.erase(schedulesToRead.begin());
193 SG_LOG(SG_AI, SG_DEBUG, path << " for traffic");
194 readXML(path.str(), *this);
197 void FGTrafficManager::finishInit()
200 SG_LOG(SG_AI, SG_INFO, "finishing AI-Traffic init");
203 // Do sorting and scoring separately, to take advantage of the "homeport| variable
204 for (currAircraft = scheduledAircraft.begin();
205 currAircraft != scheduledAircraft.end(); currAircraft++) {
206 (*currAircraft)->setScore();
209 sort(scheduledAircraft.begin(), scheduledAircraft.end(),
211 currAircraft = scheduledAircraft.begin();
212 currAircraftClosest = scheduledAircraft.begin();
218 void FGTrafficManager::loadHeuristics()
220 if (!fgGetBool("/sim/traffic-manager/heuristics")) {
224 HeuristicMap heurMap;
225 //cerr << "Processing Heuristics" << endl;
226 // Load the heuristics data
227 SGPath cacheData(fgGetString("/sim/fg-home"));
228 cacheData.append("ai");
229 string airport = fgGetString("/sim/presets/airport-id");
230 if ((airport) != "") {
232 ::snprintf(buffer, 128, "%c/%c/%c/",
233 airport[0], airport[1], airport[2]);
234 cacheData.append(buffer);
235 cacheData.append(airport + "-cache.txt");
237 if (cacheData.exists()) {
238 ifstream data(cacheData.c_str());
240 if (revisionStr != "[TrafficManagerCachedata:ref:2011:09:04]") {
241 SG_LOG(SG_GENERAL, SG_ALERT,"Traffic Manager Warning: discarding outdated cachefile " <<
242 cacheData.c_str() << " for Airport " << airport);
245 Heuristic h; // = new Heuristic;
246 data >> h.registration >> h.runCount >> h.hits >> h.lastRun;
249 HeuristicMapIterator itr = heurMap.find(h.registration);
250 if (itr != heurMap.end()) {
251 SG_LOG(SG_GENERAL, SG_WARN,"Traffic Manager Warning: found duplicate tailnumber " <<
252 h.registration << " for AI aircraft");
254 heurMap[h.registration] = h;
261 for(currAircraft = scheduledAircraft.begin(); currAircraft != scheduledAircraft.end(); ++currAircraft) {
262 string registration = (*currAircraft)->getRegistration();
263 HeuristicMapIterator itr = heurMap.find(registration);
264 if (itr != heurMap.end()) {
265 (*currAircraft)->setrunCount(itr->second.runCount);
266 (*currAircraft)->setHits(itr->second.hits);
267 (*currAircraft)->setLastUsed(itr->second.lastRun);
272 void FGTrafficManager::update(double /*dt */ )
276 if (inited || doingInit)
281 if ((realWxEnabled && !metarValid)) {
287 // traffic depends on AI module
298 return; // still more to do on next update() call
302 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
303 if (scheduledAircraft.size() == 0) {
307 SGVec3d userCart = globals->get_aircraft_positon_cart();
309 if (currAircraft == scheduledAircraft.end()) {
310 currAircraft = scheduledAircraft.begin();
312 //cerr << "Processing << " << (*currAircraft)->getRegistration() << " with score " << (*currAircraft)->getScore() << endl;
313 if (!((*currAircraft)->update(now, userCart))) {
314 (*currAircraft)->taint();
319 void FGTrafficManager::release(int id)
321 releaseList.push_back(id);
324 bool FGTrafficManager::isReleased(int id)
326 IdListIterator i = releaseList.begin();
327 while (i != releaseList.end()) {
329 releaseList.erase(i);
338 void FGTrafficManager::readTimeTableFromFile(SGPath infileName)
355 vector <string> tokens, depTime,arrTime;
356 vector <string>::iterator it;
357 ifstream infile(infileName.str().c_str());
359 infile.getline(buffer, 256);
363 //cerr << "Read line : " << buffer << endl;
364 buffString = string(buffer);
366 Tokenize(buffString, tokens, " \t");
367 //for (it = tokens.begin(); it != tokens.end(); it++) {
368 // cerr << "Tokens: " << *(it) << endl;
371 if (!tokens.empty()) {
372 if (tokens[0] == string("AC")) {
373 if (tokens.size() != 13) {
374 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
379 homePort = tokens[1];
380 registration = tokens[2];
381 if (tokens[11] == string("false")) {
388 flightReq = tokens[3] + tokens[5];
389 m_class = tokens[10];
390 FlightType = tokens[9];
391 radius = atof(tokens[8].c_str());
392 offset = atof(tokens[7].c_str());;
393 SG_LOG(SG_GENERAL, SG_ALERT, "Adding Aircraft" << model << " " << livery << " " << homePort << " "
394 << registration << " " << flightReq << " " << isHeavy
395 << " " << acType << " " << airline << " " << m_class
396 << " " << FlightType << " " << radius << " " << offset);
397 scheduledAircraft.push_back(new FGAISchedule(model,
410 if (tokens[0] == string("FLIGHT")) {
411 //cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
412 if (tokens.size() != 10) {
413 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
416 string callsign = tokens[1];
417 string fltrules = tokens[2];
418 string weekdays = tokens[3];
419 string departurePort = tokens[5];
420 string arrivalPort = tokens[7];
421 int cruiseAlt = atoi(tokens[8].c_str());
422 string depTimeGen = tokens[4];
423 string arrTimeGen = tokens[6];
424 string repeat = "WEEK";
425 string requiredAircraft = tokens[9];
427 if (weekdays.size() != 7) {
428 SG_LOG(SG_GENERAL, SG_ALERT, "Found misconfigured weekdays string" << weekdays);
433 Tokenize(depTimeGen, depTime, ":");
434 Tokenize(arrTimeGen, arrTime, ":");
435 double dep = atof(depTime[0].c_str()) + (atof(depTime[1].c_str()) / 60.0);
436 double arr = atof(arrTime[0].c_str()) + (atof(arrTime[1].c_str()) / 60.0);
437 //cerr << "Using " << dep << " " << arr << endl;
438 bool arrivalWeekdayNeedsIncrement = false;
440 arrivalWeekdayNeedsIncrement = true;
442 for (int i = 0; i < 7; i++) {
444 if (weekdays[i] != '.') {
446 snprintf(buffer, 4, "%d/", j);
447 string departureTime = string(buffer) + depTimeGen + string(":00");
449 if (!arrivalWeekdayNeedsIncrement) {
450 arrivalTime = string(buffer) + arrTimeGen + string(":00");
452 if (arrivalWeekdayNeedsIncrement && i != 6 ) {
453 snprintf(buffer, 4, "%d/", j+1);
454 arrivalTime = string(buffer) + arrTimeGen + string(":00");
456 if (arrivalWeekdayNeedsIncrement && i == 6 ) {
457 snprintf(buffer, 4, "%d/", 0);
458 arrivalTime = string(buffer) + arrTimeGen + string(":00");
460 SG_LOG(SG_GENERAL, SG_ALERT, "Adding flight " << callsign << " "
462 << departurePort << " "
463 << arrivalPort << " "
465 << departureTime << " "
466 << arrivalTime << " "
468 << requiredAircraft);
470 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
489 void FGTrafficManager::Tokenize(const string& str,
490 vector<string>& tokens,
491 const string& delimiters)
493 // Skip delimiters at beginning.
494 string::size_type lastPos = str.find_first_not_of(delimiters, 0);
495 // Find first "non-delimiter".
496 string::size_type pos = str.find_first_of(delimiters, lastPos);
498 while (string::npos != pos || string::npos != lastPos)
500 // Found a token, add it to the vector.
501 tokens.push_back(str.substr(lastPos, pos - lastPos));
502 // Skip delimiters. Note the "not_of"
503 lastPos = str.find_first_not_of(delimiters, pos);
504 // Find next "non-delimiter"
505 pos = str.find_first_of(delimiters, lastPos);
510 void FGTrafficManager::startXML()
512 //cout << "Start XML" << endl;
513 requiredAircraft = "";
517 void FGTrafficManager::endXML()
519 //cout << "End XML" << endl;
522 void FGTrafficManager::startElement(const char *name,
523 const XMLAttributes & atts)
526 //cout << "Start element " << name << endl;
527 //FGTrafficManager temp;
528 //for (int i = 0; i < atts.size(); i++)
529 // if (string(atts.getName(i)) == string("include"))
530 attval = atts.getValue("include");
532 //cout << "including " << attval << endl;
533 SGPath path = globals->get_fg_root();
534 path.append("/Traffic/");
536 readXML(path.str(), *this);
538 elementValueStack.push_back("");
539 // cout << " " << atts.getName(i) << '=' << atts.getValue(i) << endl;
542 void FGTrafficManager::endElement(const char *name)
544 //cout << "End element " << name << endl;
545 const string & value = elementValueStack.back();
547 if (!strcmp(name, "model"))
549 else if (!strcmp(name, "livery"))
551 else if (!strcmp(name, "home-port"))
553 else if (!strcmp(name, "registration"))
554 registration = value;
555 else if (!strcmp(name, "airline"))
557 else if (!strcmp(name, "actype"))
559 else if (!strcmp(name, "required-aircraft"))
560 requiredAircraft = value;
561 else if (!strcmp(name, "flighttype"))
563 else if (!strcmp(name, "radius"))
564 radius = atoi(value.c_str());
565 else if (!strcmp(name, "offset"))
566 offset = atoi(value.c_str());
567 else if (!strcmp(name, "performance-class"))
569 else if (!strcmp(name, "heavy")) {
570 if (value == string("true"))
574 } else if (!strcmp(name, "callsign"))
576 else if (!strcmp(name, "fltrules"))
578 else if (!strcmp(name, "port"))
580 else if (!strcmp(name, "time"))
582 else if (!strcmp(name, "departure")) {
583 departurePort = port;
584 departureTime = timeString;
585 } else if (!strcmp(name, "cruise-alt"))
586 cruiseAlt = atoi(value.c_str());
587 else if (!strcmp(name, "arrival")) {
589 arrivalTime = timeString;
590 } else if (!strcmp(name, "repeat"))
592 else if (!strcmp(name, "flight")) {
593 // We have loaded and parsed all the information belonging to this flight
594 // so we temporarily store it.
595 //cerr << "Pusing back flight " << callsign << endl;
596 //cerr << callsign << " " << fltrules << " "<< departurePort << " " << arrivalPort << " "
597 // << cruiseAlt << " " << departureTime<< " "<< arrivalTime << " " << repeat << endl;
599 //Prioritize aircraft
600 string apt = fgGetString("/sim/presets/airport-id");
601 //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
602 //if (departurePort == apt) score++;
603 //flights.push_back(new FGScheduledFlight(callsign,
611 if (requiredAircraft == "") {
613 snprintf(buffer, 16, "%d", acCounter);
614 requiredAircraft = buffer;
616 SG_LOG(SG_GENERAL, SG_DEBUG, "Adding flight: " << callsign << " "
618 << departurePort << " "
619 << arrivalPort << " "
621 << departureTime << " "
622 << arrivalTime << " " << repeat << " " << requiredAircraft);
623 // For database maintainance purposes, it may be convenient to
625 if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
626 SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump FLIGHT," << callsign << ","
628 << departurePort << ","
629 << arrivalPort << ","
631 << departureTime << ","
632 << arrivalTime << "," << repeat << "," << requiredAircraft);
634 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
643 requiredAircraft = "";
644 } else if (!strcmp(name, "aircraft")) {
652 cerr << "Traffic Dump AC," << homePort << "," << registration << "," << requiredAircraft
653 << "," << acType << "," << livery << ","
654 << airline << "," << offset << "," << radius << "," << flighttype << "," << isHeavy << "," << mdl << endl;*/
656 (int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
657 int randval = rand() & 100;
658 if (randval <= proportion) {
659 if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
660 SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump AC," << homePort << "," << registration << "," << requiredAircraft
661 << "," << acType << "," << livery << ","
662 << airline << "," << m_class << "," << offset << "," << radius << "," << flighttype << "," << isHeavy << "," << mdl);
664 //scheduledAircraft.push_back(new FGAISchedule(mdl,
676 if (requiredAircraft == "") {
678 snprintf(buffer, 16, "%d", acCounter);
679 requiredAircraft = buffer;
681 if (homePort == "") {
682 homePort = departurePort;
684 scheduledAircraft.push_back(new FGAISchedule(mdl,
696 // while(flights.begin() != flights.end()) {
697 // flights.pop_back();
700 cerr << "Skipping : " << randval;
703 requiredAircraft = "";
705 //for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
710 SG_LOG(SG_GENERAL, SG_BULK, "Reading aircraft : "
711 << registration << " with prioritization score " << score);
714 elementValueStack.pop_back();
717 void FGTrafficManager::data(const char *s, int len)
719 string token = string(s, len);
720 //cout << "Character data " << string(s,len) << endl;
721 elementValueStack.back() += token;
724 void FGTrafficManager::pi(const char *target, const char *data)
726 //cout << "Processing instruction " << target << ' ' << data << endl;
729 void FGTrafficManager::warning(const char *message, int line, int column)
731 SG_LOG(SG_IO, SG_WARN,
732 "Warning: " << message << " (" << line << ',' << column << ')');
735 void FGTrafficManager::error(const char *message, int line, int column)
737 SG_LOG(SG_IO, SG_ALERT,
738 "Error: " << message << " (" << line << ',' << column << ')');