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 *****************************************************************************/
54 #include <simgear/compiler.h>
55 #include <simgear/misc/sg_path.hxx>
56 #include <simgear/misc/sg_dir.hxx>
57 #include <simgear/props/props.hxx>
58 #include <simgear/route/waypoint.hxx>
59 #include <simgear/structure/subsystem_mgr.hxx>
60 #include <simgear/xml/easyxml.hxx>
62 #include <AIModel/AIAircraft.hxx>
63 #include <AIModel/AIFlightPlan.hxx>
64 #include <AIModel/AIBase.hxx>
65 #include <Airports/simple.hxx>
66 #include <Main/fg_init.hxx>
70 #include "TrafficMgr.hxx"
75 /******************************************************************************
77 *****************************************************************************/
78 FGTrafficManager::FGTrafficManager() :
80 enabled("/sim/traffic-manager/enabled"),
81 aiEnabled("/sim/ai/enabled"),
82 realWxEnabled("/environment/realwx/enabled"),
83 metarValid("/environment/metar/valid")
90 FGTrafficManager::~FGTrafficManager()
92 // Save the heuristics data
93 bool saveData = false;
95 if (fgGetBool("/sim/traffic-manager/heuristics")) {
96 SGPath cacheData(fgGetString("/sim/fg-home"));
97 cacheData.append("ai");
98 string airport = fgGetString("/sim/presets/airport-id");
100 if ((airport) != "") {
102 ::snprintf(buffer, 128, "%c/%c/%c/",
103 airport[0], airport[1], airport[2]);
104 cacheData.append(buffer);
105 if (!cacheData.exists()) {
106 cacheData.create_dir(0777);
108 cacheData.append(airport + "-cache.txt");
109 //cerr << "Saving AI traffic heuristics" << endl;
111 cachefile.open(cacheData.str().c_str());
112 cachefile << "[TrafficManagerCachedata:ref:2011:09:04]" << endl;
115 for (ScheduleVectorIterator sched = scheduledAircraft.begin();
116 sched != scheduledAircraft.end(); sched++) {
118 cachefile << (*sched)->getRegistration() << " "
119 << (*sched)->getRunCount() << " "
120 << (*sched)->getHits() << " "
121 << (*sched)->getLastUsed() << endl;
128 scheduledAircraft.clear();
133 void FGTrafficManager::init()
135 if (!enabled || !aiEnabled) {
139 heuristicsVector heuristics;
140 HeuristicMap heurMap;
142 if (string(fgGetString("/sim/traffic-manager/datafile")) == string("")) {
143 simgear::Dir trafficDir(SGPath(globals->get_fg_root(), "AI/Traffic"));
144 simgear::PathList d = trafficDir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT);
146 for (unsigned int i=0; i<d.size(); ++i) {
147 simgear::Dir d2(d[i]);
148 simgear::PathList trafficFiles = d2.children(simgear::Dir::TYPE_FILE, ".xml");
149 for (unsigned int j=0; j<trafficFiles.size(); ++j) {
150 SGPath curFile = trafficFiles[j];
151 SG_LOG(SG_GENERAL, SG_DEBUG,
152 "Scanning " << curFile.str() << " for traffic");
153 readXML(curFile.str(), *this);
157 fgSetBool("/sim/traffic-manager/heuristics", false);
158 SGPath path = string(fgGetString("/sim/traffic-manager/datafile"));
159 string ext = path.extension();
160 if (path.extension() == "xml") {
162 readXML(path.str(), *this);
164 } else if (path.extension() == "conf") {
166 readTimeTableFromFile(path);
169 SG_LOG(SG_GENERAL, SG_ALERT,
170 "Unknown data format " << path.str()
175 if (fgGetBool("/sim/traffic-manager/heuristics")) {
176 //cerr << "Processing Heuristics" << endl;
177 // Load the heuristics data
178 SGPath cacheData(fgGetString("/sim/fg-home"));
179 cacheData.append("ai");
180 string airport = fgGetString("/sim/presets/airport-id");
181 if ((airport) != "") {
183 ::snprintf(buffer, 128, "%c/%c/%c/",
184 airport[0], airport[1], airport[2]);
185 cacheData.append(buffer);
186 cacheData.append(airport + "-cache.txt");
188 if (cacheData.exists()) {
189 ifstream data(cacheData.c_str());
191 if (revisionStr != "[TrafficManagerCachedata:ref:2011:09:04]") {
192 SG_LOG(SG_GENERAL, SG_ALERT,"Traffic Manager Warning: discarding outdated cachefile " <<
193 cacheData.c_str() << " for Airport " << airport);
196 Heuristic h; // = new Heuristic;
197 data >> h.registration >> h.runCount >> h.hits >> h.lastRun;
200 HeuristicMapIterator itr = heurMap.find(h.registration);
201 if (itr != heurMap.end()) {
202 SG_LOG(SG_GENERAL, SG_WARN,"Traffic Manager Warning: found duplicate tailnumber " <<
203 h.registration << " for AI aircraft");
205 heurMap[h.registration] = h;
206 heuristics.push_back(h);
212 for (currAircraft = scheduledAircraft.begin();
213 currAircraft != scheduledAircraft.end(); currAircraft++) {
214 string registration = (*currAircraft)->getRegistration();
215 HeuristicMapIterator itr = heurMap.find(registration);
216 //cerr << "Processing heuristics for" << (*currAircraft)->getRegistration() << endl;
217 if (itr == heurMap.end()) {
218 //cerr << "No heuristics found for " << registration << endl;
220 (*currAircraft)->setrunCount(itr->second.runCount);
221 (*currAircraft)->setHits(itr->second.hits);
222 (*currAircraft)->setLastUsed(itr->second.lastRun);
223 //cerr <<"Runcount " << itr->second.runCount << ". Hits " << itr->second.hits << ". Last run " << itr->second.lastRun<< endl;
226 //cerr << "Done" << endl;
227 //for (heuristicsVectorIterator hvi = heuristics.begin();
228 // hvi != heuristics.end(); hvi++) {
232 // Do sorting and scoring separately, to take advantage of the "homeport| variable
233 for (currAircraft = scheduledAircraft.begin();
234 currAircraft != scheduledAircraft.end(); currAircraft++) {
235 (*currAircraft)->setScore();
238 sort(scheduledAircraft.begin(), scheduledAircraft.end(),
240 currAircraft = scheduledAircraft.begin();
241 currAircraftClosest = scheduledAircraft.begin();
245 void FGTrafficManager::update(double /*dt */ )
247 if (!enabled || !aiEnabled || (realWxEnabled && !metarValid)) {
252 // lazy-initialization, we've been enabled at run-time
253 SG_LOG(SG_GENERAL, SG_INFO, "doing lazy-init of TrafficManager");
257 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
258 if (scheduledAircraft.size() == 0) {
263 SGVec3d::fromGeod(SGGeod::
264 fromDeg(fgGetDouble("/position/longitude-deg"),
265 fgGetDouble("/position/latitude-deg")));
267 if (currAircraft == scheduledAircraft.end()) {
268 currAircraft = scheduledAircraft.begin();
270 //cerr << "Processing << " << (*currAircraft)->getRegistration() << " with score " << (*currAircraft)->getScore() << endl;
271 if (!((*currAircraft)->update(now, userCart))) {
272 (*currAircraft)->taint();
277 void FGTrafficManager::release(int id)
279 releaseList.push_back(id);
282 bool FGTrafficManager::isReleased(int id)
284 IdListIterator i = releaseList.begin();
285 while (i != releaseList.end()) {
287 releaseList.erase(i);
296 void FGTrafficManager::readTimeTableFromFile(SGPath infileName)
313 vector <string> tokens, depTime,arrTime;
314 vector <string>::iterator it;
315 ifstream infile(infileName.str().c_str());
317 infile.getline(buffer, 256);
321 //cerr << "Read line : " << buffer << endl;
322 buffString = string(buffer);
324 Tokenize(buffString, tokens, " \t");
325 //for (it = tokens.begin(); it != tokens.end(); it++) {
326 // cerr << "Tokens: " << *(it) << endl;
329 if (!tokens.empty()) {
330 if (tokens[0] == string("AC")) {
331 if (tokens.size() != 13) {
332 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
337 homePort = tokens[1];
338 registration = tokens[2];
339 if (tokens[11] == string("false")) {
346 flightReq = tokens[3] + tokens[5];
347 m_class = tokens[10];
348 FlightType = tokens[9];
349 radius = atof(tokens[8].c_str());
350 offset = atof(tokens[7].c_str());;
351 SG_LOG(SG_GENERAL, SG_ALERT, "Adding Aircraft" << model << " " << livery << " " << homePort << " "
352 << registration << " " << flightReq << " " << isHeavy
353 << " " << acType << " " << airline << " " << m_class
354 << " " << FlightType << " " << radius << " " << offset);
355 scheduledAircraft.push_back(new FGAISchedule(model,
368 if (tokens[0] == string("FLIGHT")) {
369 //cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
370 if (tokens.size() != 10) {
371 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
374 string callsign = tokens[1];
375 string fltrules = tokens[2];
376 string weekdays = tokens[3];
377 string departurePort = tokens[5];
378 string arrivalPort = tokens[7];
379 int cruiseAlt = atoi(tokens[8].c_str());
380 string depTimeGen = tokens[4];
381 string arrTimeGen = tokens[6];
382 string repeat = "WEEK";
383 string requiredAircraft = tokens[9];
385 if (weekdays.size() != 7) {
386 SG_LOG(SG_GENERAL, SG_ALERT, "Found misconfigured weekdays string" << weekdays);
391 Tokenize(depTimeGen, depTime, ":");
392 Tokenize(arrTimeGen, arrTime, ":");
393 double dep = atof(depTime[0].c_str()) + (atof(depTime[1].c_str()) / 60.0);
394 double arr = atof(arrTime[0].c_str()) + (atof(arrTime[1].c_str()) / 60.0);
395 //cerr << "Using " << dep << " " << arr << endl;
396 bool arrivalWeekdayNeedsIncrement = false;
398 arrivalWeekdayNeedsIncrement = true;
400 for (int i = 0; i < 7; i++) {
402 if (weekdays[i] != '.') {
404 snprintf(buffer, 4, "%d/", j);
405 string departureTime = string(buffer) + depTimeGen + string(":00");
407 if (!arrivalWeekdayNeedsIncrement) {
408 arrivalTime = string(buffer) + arrTimeGen + string(":00");
410 if (arrivalWeekdayNeedsIncrement && i != 6 ) {
411 snprintf(buffer, 4, "%d/", j+1);
412 arrivalTime = string(buffer) + arrTimeGen + string(":00");
414 if (arrivalWeekdayNeedsIncrement && i == 6 ) {
415 snprintf(buffer, 4, "%d/", 0);
416 arrivalTime = string(buffer) + arrTimeGen + string(":00");
418 SG_LOG(SG_GENERAL, SG_ALERT, "Adding flight " << callsign << " "
420 << departurePort << " "
421 << arrivalPort << " "
423 << departureTime << " "
424 << arrivalTime << " "
426 << requiredAircraft);
428 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
447 void FGTrafficManager::Tokenize(const string& str,
448 vector<string>& tokens,
449 const string& delimiters)
451 // Skip delimiters at beginning.
452 string::size_type lastPos = str.find_first_not_of(delimiters, 0);
453 // Find first "non-delimiter".
454 string::size_type pos = str.find_first_of(delimiters, lastPos);
456 while (string::npos != pos || string::npos != lastPos)
458 // Found a token, add it to the vector.
459 tokens.push_back(str.substr(lastPos, pos - lastPos));
460 // Skip delimiters. Note the "not_of"
461 lastPos = str.find_first_not_of(delimiters, pos);
462 // Find next "non-delimiter"
463 pos = str.find_first_of(delimiters, lastPos);
468 void FGTrafficManager::startXML()
470 //cout << "Start XML" << endl;
471 requiredAircraft = "";
475 void FGTrafficManager::endXML()
477 //cout << "End XML" << endl;
480 void FGTrafficManager::startElement(const char *name,
481 const XMLAttributes & atts)
484 //cout << "Start element " << name << endl;
485 //FGTrafficManager temp;
486 //for (int i = 0; i < atts.size(); i++)
487 // if (string(atts.getName(i)) == string("include"))
488 attval = atts.getValue("include");
490 //cout << "including " << attval << endl;
491 SGPath path = globals->get_fg_root();
492 path.append("/Traffic/");
494 readXML(path.str(), *this);
496 elementValueStack.push_back("");
497 // cout << " " << atts.getName(i) << '=' << atts.getValue(i) << endl;
500 void FGTrafficManager::endElement(const char *name)
502 //cout << "End element " << name << endl;
503 const string & value = elementValueStack.back();
505 if (!strcmp(name, "model"))
507 else if (!strcmp(name, "livery"))
509 else if (!strcmp(name, "home-port"))
511 else if (!strcmp(name, "registration"))
512 registration = value;
513 else if (!strcmp(name, "airline"))
515 else if (!strcmp(name, "actype"))
517 else if (!strcmp(name, "required-aircraft"))
518 requiredAircraft = value;
519 else if (!strcmp(name, "flighttype"))
521 else if (!strcmp(name, "radius"))
522 radius = atoi(value.c_str());
523 else if (!strcmp(name, "offset"))
524 offset = atoi(value.c_str());
525 else if (!strcmp(name, "performance-class"))
527 else if (!strcmp(name, "heavy")) {
528 if (value == string("true"))
532 } else if (!strcmp(name, "callsign"))
534 else if (!strcmp(name, "fltrules"))
536 else if (!strcmp(name, "port"))
538 else if (!strcmp(name, "time"))
540 else if (!strcmp(name, "departure")) {
541 departurePort = port;
542 departureTime = timeString;
543 } else if (!strcmp(name, "cruise-alt"))
544 cruiseAlt = atoi(value.c_str());
545 else if (!strcmp(name, "arrival")) {
547 arrivalTime = timeString;
548 } else if (!strcmp(name, "repeat"))
550 else if (!strcmp(name, "flight")) {
551 // We have loaded and parsed all the information belonging to this flight
552 // so we temporarily store it.
553 //cerr << "Pusing back flight " << callsign << endl;
554 //cerr << callsign << " " << fltrules << " "<< departurePort << " " << arrivalPort << " "
555 // << cruiseAlt << " " << departureTime<< " "<< arrivalTime << " " << repeat << endl;
557 //Prioritize aircraft
558 string apt = fgGetString("/sim/presets/airport-id");
559 //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
560 //if (departurePort == apt) score++;
561 //flights.push_back(new FGScheduledFlight(callsign,
569 if (requiredAircraft == "") {
571 snprintf(buffer, 16, "%d", acCounter);
572 requiredAircraft = buffer;
574 SG_LOG(SG_GENERAL, SG_DEBUG, "Adding flight: " << callsign << " "
576 << departurePort << " "
577 << arrivalPort << " "
579 << departureTime << " "
580 << arrivalTime << " " << repeat << " " << requiredAircraft);
581 // For database maintainance purposes, it may be convenient to
583 if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
584 SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump FLIGHT," << callsign << ","
586 << departurePort << ","
587 << arrivalPort << ","
589 << departureTime << ","
590 << arrivalTime << "," << repeat << "," << requiredAircraft);
592 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
601 requiredAircraft = "";
602 } else if (!strcmp(name, "aircraft")) {
610 cerr << "Traffic Dump AC," << homePort << "," << registration << "," << requiredAircraft
611 << "," << acType << "," << livery << ","
612 << airline << "," << offset << "," << radius << "," << flighttype << "," << isHeavy << "," << mdl << endl;*/
614 (int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
615 int randval = rand() & 100;
616 if (randval <= proportion) {
617 if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
618 SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump AC," << homePort << "," << registration << "," << requiredAircraft
619 << "," << acType << "," << livery << ","
620 << airline << "," << m_class << "," << offset << "," << radius << "," << flighttype << "," << isHeavy << "," << mdl);
622 //scheduledAircraft.push_back(new FGAISchedule(mdl,
634 if (requiredAircraft == "") {
636 snprintf(buffer, 16, "%d", acCounter);
637 requiredAircraft = buffer;
639 if (homePort == "") {
640 homePort = departurePort;
642 scheduledAircraft.push_back(new FGAISchedule(mdl,
654 // while(flights.begin() != flights.end()) {
655 // flights.pop_back();
658 cerr << "Skipping : " << randval;
661 requiredAircraft = "";
663 //for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
668 SG_LOG(SG_GENERAL, SG_BULK, "Reading aircraft : "
669 << registration << " with prioritization score " << score);
672 elementValueStack.pop_back();
675 void FGTrafficManager::data(const char *s, int len)
677 string token = string(s, len);
678 //cout << "Character data " << string(s,len) << endl;
679 elementValueStack.back() += token;
682 void FGTrafficManager::pi(const char *target, const char *data)
684 //cout << "Processing instruction " << target << ' ' << data << endl;
687 void FGTrafficManager::warning(const char *message, int line, int column)
689 SG_LOG(SG_IO, SG_WARN,
690 "Warning: " << message << " (" << line << ',' << column << ')');
693 void FGTrafficManager::error(const char *message, int line, int column)
695 SG_LOG(SG_IO, SG_ALERT,
696 "Error: " << message << " (" << line << ',' << column << ')');