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()
85 FGTrafficManager::~FGTrafficManager()
87 // Save the heuristics data
88 bool saveData = false;
90 if (fgGetBool("/sim/traffic-manager/heuristics")) {
91 SGPath cacheData(fgGetString("/sim/fg-home"));
92 cacheData.append("ai");
93 string airport = fgGetString("/sim/presets/airport-id");
95 if ((airport) != "") {
97 ::snprintf(buffer, 128, "%c/%c/%c/",
98 airport[0], airport[1], airport[2]);
99 cacheData.append(buffer);
100 if (!cacheData.exists()) {
101 cacheData.create_dir(0777);
103 cacheData.append(airport + "-cache.txt");
104 //cerr << "Saving AI traffic heuristics" << endl;
106 cachefile.open(cacheData.str().c_str());
109 for (ScheduleVectorIterator sched = scheduledAircraft.begin();
110 sched != scheduledAircraft.end(); sched++) {
112 cachefile << (*sched)->getRegistration() << " "
113 << (*sched)->getRunCount() << " "
114 << (*sched)->getHits() << endl;
121 scheduledAircraft.clear();
126 void FGTrafficManager::init()
128 heuristicsVector heuristics;
129 HeuristicMap heurMap;
131 if (string(fgGetString("/sim/traffic-manager/datafile")) == string("")) {
132 simgear::Dir trafficDir(SGPath(globals->get_fg_root(), "AI/Traffic"));
133 simgear::PathList d = trafficDir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT);
135 for (unsigned int i=0; i<d.size(); ++i) {
136 simgear::Dir d2(d[i]);
137 simgear::PathList trafficFiles = d2.children(simgear::Dir::TYPE_FILE, ".xml");
138 for (unsigned int j=0; j<trafficFiles.size(); ++j) {
139 SGPath curFile = trafficFiles[j];
140 SG_LOG(SG_GENERAL, SG_DEBUG,
141 "Scanning " << curFile.str() << " for traffic");
142 readXML(curFile.str(), *this);
146 fgSetBool("/sim/traffic-manager/heuristics", false);
147 SGPath path = string(fgGetString("/sim/traffic-manager/datafile"));
148 string ext = path.extension();
149 if (path.extension() == "xml") {
151 readXML(path.str(), *this);
153 } else if (path.extension() == "conf") {
155 readTimeTableFromFile(path);
158 SG_LOG(SG_GENERAL, SG_ALERT,
159 "Unknown data format " << path.str()
164 if (fgGetBool("/sim/traffic-manager/heuristics")) {
165 //cerr << "Processing Heuristics" << endl;
166 // Load the heuristics data
167 SGPath cacheData(fgGetString("/sim/fg-home"));
168 cacheData.append("ai");
169 string airport = fgGetString("/sim/presets/airport-id");
170 if ((airport) != "") {
172 ::snprintf(buffer, 128, "%c/%c/%c/",
173 airport[0], airport[1], airport[2]);
174 cacheData.append(buffer);
175 cacheData.append(airport + "-cache.txt");
176 if (cacheData.exists()) {
177 ifstream data(cacheData.c_str());
179 Heuristic h; // = new Heuristic;
180 data >> h.registration >> h.runCount >> h.hits;
183 HeuristicMapIterator itr = heurMap.find(h.registration);
184 if (itr != heurMap.end()) {
185 SG_LOG(SG_GENERAL, SG_WARN,"Traffic Manager Warning: found duplicate tailnumber " <<
186 h.registration << " for AI aircraft");
188 heurMap[h.registration] = h;
189 heuristics.push_back(h);
193 for (currAircraft = scheduledAircraft.begin();
194 currAircraft != scheduledAircraft.end(); currAircraft++) {
195 string registration = (*currAircraft)->getRegistration();
196 HeuristicMapIterator itr = heurMap.find(registration);
197 //cerr << "Processing heuristics for" << (*currAircraft)->getRegistration() << endl;
198 if (itr == heurMap.end()) {
199 //cerr << "No heuristics found for " << registration << endl;
201 (*currAircraft)->setrunCount(itr->second.runCount);
202 (*currAircraft)->setHits(itr->second.hits);
203 //cerr <<"Runcount " << itr->second->runCount << ".Hits " << itr->second->hits << endl;
206 //cerr << "Done" << endl;
207 //for (heuristicsVectorIterator hvi = heuristics.begin();
208 // hvi != heuristics.end(); hvi++) {
212 // Do sorting and scoring separately, to take advantage of the "homeport| variable
213 for (currAircraft = scheduledAircraft.begin();
214 currAircraft != scheduledAircraft.end(); currAircraft++) {
215 (*currAircraft)->setScore();
217 sort(scheduledAircraft.begin(), scheduledAircraft.end(),
219 currAircraft = scheduledAircraft.begin();
220 currAircraftClosest = scheduledAircraft.begin();
223 void FGTrafficManager::update(double /*dt */ )
225 if (fgGetBool("/environment/metar/valid") == false) {
228 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
229 if (scheduledAircraft.size() == 0) {
234 SGVec3d::fromGeod(SGGeod::
235 fromDeg(fgGetDouble("/position/longitude-deg"),
236 fgGetDouble("/position/latitude-deg")));
238 if (currAircraft == scheduledAircraft.end()) {
239 currAircraft = scheduledAircraft.begin();
241 //cerr << "Processing << " << (*currAircraft)->getRegistration() << " with score " << (*currAircraft)->getScore() << endl;
242 if (!((*currAircraft)->update(now, userCart))) {
243 // NOTE: With traffic manager II, this statement below is no longer true
244 // after proper initialization, we shouldnt get here.
245 // But let's make sure
246 //SG_LOG( SG_GENERAL, SG_ALERT, "Failed to update aircraft schedule in traffic manager");
251 void FGTrafficManager::release(int id)
253 releaseList.push_back(id);
256 bool FGTrafficManager::isReleased(int id)
258 IdListIterator i = releaseList.begin();
259 while (i != releaseList.end()) {
261 releaseList.erase(i);
270 void FGTrafficManager::readTimeTableFromFile(SGPath infileName)
287 vector <string> tokens, depTime,arrTime;
288 vector <string>::iterator it;
289 ifstream infile(infileName.str().c_str());
291 infile.getline(buffer, 256);
295 //cerr << "Read line : " << buffer << endl;
296 buffString = string(buffer);
298 Tokenize(buffString, tokens, " \t");
299 //for (it = tokens.begin(); it != tokens.end(); it++) {
300 // cerr << "Tokens: " << *(it) << endl;
303 if (!tokens.empty()) {
304 if (tokens[0] == string("AC")) {
305 if (tokens.size() != 13) {
306 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
311 homePort = tokens[1];
312 registration = tokens[2];
313 if (tokens[11] == string("false")) {
320 flightReq = tokens[3] + tokens[5];
321 m_class = tokens[10];
322 FlightType = tokens[9];
323 radius = atof(tokens[8].c_str());
324 offset = atof(tokens[7].c_str());;
325 SG_LOG(SG_GENERAL, SG_ALERT, "Adding Aircraft" << model << " " << livery << " " << homePort << " "
326 << registration << " " << flightReq << " " << isHeavy
327 << " " << acType << " " << airline << " " << m_class
328 << " " << FlightType << " " << radius << " " << offset);
329 scheduledAircraft.push_back(new FGAISchedule(model,
342 if (tokens[0] == string("FLIGHT")) {
343 //cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
344 if (tokens.size() != 10) {
345 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
348 string callsign = tokens[1];
349 string fltrules = tokens[2];
350 string weekdays = tokens[3];
351 string departurePort = tokens[5];
352 string arrivalPort = tokens[7];
353 int cruiseAlt = atoi(tokens[8].c_str());
354 string depTimeGen = tokens[4];
355 string arrTimeGen = tokens[6];
356 string repeat = "WEEK";
357 string requiredAircraft = tokens[9];
359 if (weekdays.size() != 7) {
360 SG_LOG(SG_GENERAL, SG_ALERT, "Found misconfigured weekdays string" << weekdays);
365 Tokenize(depTimeGen, depTime, ":");
366 Tokenize(arrTimeGen, arrTime, ":");
367 double dep = atof(depTime[0].c_str()) + (atof(depTime[1].c_str()) / 60.0);
368 double arr = atof(arrTime[0].c_str()) + (atof(arrTime[1].c_str()) / 60.0);
369 //cerr << "Using " << dep << " " << arr << endl;
370 bool arrivalWeekdayNeedsIncrement = false;
372 arrivalWeekdayNeedsIncrement = true;
374 for (int i = 0; i < 7; i++) {
376 if (weekdays[i] != '.') {
378 snprintf(buffer, 4, "%d/", j);
379 string departureTime = string(buffer) + depTimeGen + string(":00");
381 if (!arrivalWeekdayNeedsIncrement) {
382 arrivalTime = string(buffer) + arrTimeGen + string(":00");
384 if (arrivalWeekdayNeedsIncrement && i != 6 ) {
385 snprintf(buffer, 4, "%d/", j+1);
386 arrivalTime = string(buffer) + arrTimeGen + string(":00");
388 if (arrivalWeekdayNeedsIncrement && i == 6 ) {
389 snprintf(buffer, 4, "%d/", 0);
390 arrivalTime = string(buffer) + arrTimeGen + string(":00");
392 SG_LOG(SG_GENERAL, SG_ALERT, "Adding flight " << callsign << " "
394 << departurePort << " "
395 << arrivalPort << " "
397 << departureTime << " "
398 << arrivalTime << " "
400 << requiredAircraft);
402 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
421 void FGTrafficManager::Tokenize(const string& str,
422 vector<string>& tokens,
423 const string& delimiters)
425 // Skip delimiters at beginning.
426 string::size_type lastPos = str.find_first_not_of(delimiters, 0);
427 // Find first "non-delimiter".
428 string::size_type pos = str.find_first_of(delimiters, lastPos);
430 while (string::npos != pos || string::npos != lastPos)
432 // Found a token, add it to the vector.
433 tokens.push_back(str.substr(lastPos, pos - lastPos));
434 // Skip delimiters. Note the "not_of"
435 lastPos = str.find_first_not_of(delimiters, pos);
436 // Find next "non-delimiter"
437 pos = str.find_first_of(delimiters, lastPos);
442 void FGTrafficManager::startXML()
444 //cout << "Start XML" << endl;
445 requiredAircraft = "";
449 void FGTrafficManager::endXML()
451 //cout << "End XML" << endl;
454 void FGTrafficManager::startElement(const char *name,
455 const XMLAttributes & atts)
458 //cout << "Start element " << name << endl;
459 //FGTrafficManager temp;
460 //for (int i = 0; i < atts.size(); i++)
461 // if (string(atts.getName(i)) == string("include"))
462 attval = atts.getValue("include");
464 //cout << "including " << attval << endl;
465 SGPath path = globals->get_fg_root();
466 path.append("/Traffic/");
468 readXML(path.str(), *this);
470 elementValueStack.push_back("");
471 // cout << " " << atts.getName(i) << '=' << atts.getValue(i) << endl;
474 void FGTrafficManager::endElement(const char *name)
476 //cout << "End element " << name << endl;
477 const string & value = elementValueStack.back();
479 if (!strcmp(name, "model"))
481 else if (!strcmp(name, "livery"))
483 else if (!strcmp(name, "home-port"))
485 else if (!strcmp(name, "registration"))
486 registration = value;
487 else if (!strcmp(name, "airline"))
489 else if (!strcmp(name, "actype"))
491 else if (!strcmp(name, "required-aircraft"))
492 requiredAircraft = value;
493 else if (!strcmp(name, "flighttype"))
495 else if (!strcmp(name, "radius"))
496 radius = atoi(value.c_str());
497 else if (!strcmp(name, "offset"))
498 offset = atoi(value.c_str());
499 else if (!strcmp(name, "performance-class"))
501 else if (!strcmp(name, "heavy")) {
502 if (value == string("true"))
506 } else if (!strcmp(name, "callsign"))
508 else if (!strcmp(name, "fltrules"))
510 else if (!strcmp(name, "port"))
512 else if (!strcmp(name, "time"))
514 else if (!strcmp(name, "departure")) {
515 departurePort = port;
516 departureTime = timeString;
517 } else if (!strcmp(name, "cruise-alt"))
518 cruiseAlt = atoi(value.c_str());
519 else if (!strcmp(name, "arrival")) {
521 arrivalTime = timeString;
522 } else if (!strcmp(name, "repeat"))
524 else if (!strcmp(name, "flight")) {
525 // We have loaded and parsed all the information belonging to this flight
526 // so we temporarily store it.
527 //cerr << "Pusing back flight " << callsign << endl;
528 //cerr << callsign << " " << fltrules << " "<< departurePort << " " << arrivalPort << " "
529 // << cruiseAlt << " " << departureTime<< " "<< arrivalTime << " " << repeat << endl;
531 //Prioritize aircraft
532 string apt = fgGetString("/sim/presets/airport-id");
533 //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
534 //if (departurePort == apt) score++;
535 //flights.push_back(new FGScheduledFlight(callsign,
543 if (requiredAircraft == "") {
545 snprintf(buffer, 16, "%d", acCounter);
546 requiredAircraft = buffer;
548 SG_LOG(SG_GENERAL, SG_DEBUG, "Adding flight: " << callsign << " "
550 << departurePort << " "
551 << arrivalPort << " "
553 << departureTime << " "
554 << arrivalTime << " " << repeat << " " << requiredAircraft);
555 // For database maintainance purposes, it may be convenient to
557 if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
558 SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump FLIGHT," << callsign << ","
560 << departurePort << ","
561 << arrivalPort << ","
563 << departureTime << ","
564 << arrivalTime << "," << repeat << "," << requiredAircraft);
566 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
575 requiredAircraft = "";
576 } else if (!strcmp(name, "aircraft")) {
584 cerr << "Traffic Dump AC," << homePort << "," << registration << "," << requiredAircraft
585 << "," << acType << "," << livery << ","
586 << airline << "," << offset << "," << radius << "," << flighttype << "," << isHeavy << "," << mdl << endl;*/
588 (int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
589 int randval = rand() & 100;
590 if (randval <= proportion) {
591 if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
592 SG_LOG(SG_GENERAL, SG_ALERT, "Traffic Dump AC," << homePort << "," << registration << "," << requiredAircraft
593 << "," << acType << "," << livery << ","
594 << airline << "," << m_class << "," << offset << "," << radius << "," << flighttype << "," << isHeavy << "," << mdl);
596 //scheduledAircraft.push_back(new FGAISchedule(mdl,
608 if (requiredAircraft == "") {
610 snprintf(buffer, 16, "%d", acCounter);
611 requiredAircraft = buffer;
613 if (homePort == "") {
614 homePort = departurePort;
616 scheduledAircraft.push_back(new FGAISchedule(mdl,
628 // while(flights.begin() != flights.end()) {
629 // flights.pop_back();
632 cerr << "Skipping : " << randval;
635 requiredAircraft = "";
637 //for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
642 SG_LOG(SG_GENERAL, SG_BULK, "Reading aircraft : "
643 << registration << " with prioritization score " << score);
646 elementValueStack.pop_back();
649 void FGTrafficManager::data(const char *s, int len)
651 string token = string(s, len);
652 //cout << "Character data " << string(s,len) << endl;
653 elementValueStack.back() += token;
656 void FGTrafficManager::pi(const char *target, const char *data)
658 //cout << "Processing instruction " << target << ' ' << data << endl;
661 void FGTrafficManager::warning(const char *message, int line, int column)
663 SG_LOG(SG_IO, SG_WARN,
664 "Warning: " << message << " (" << line << ',' << column << ')');
667 void FGTrafficManager::error(const char *message, int line, int column)
669 SG_LOG(SG_IO, SG_ALERT,
670 "Error: " << message << " (" << line << ',' << column << ')');