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/structure/exception.hxx>
62 #include <simgear/xml/easyxml.hxx>
63 #include <simgear/threads/SGThread.hxx>
64 #include <simgear/threads/SGGuard.hxx>
65 #include <simgear/scene/tsync/terrasync.hxx>
67 #include <AIModel/AIAircraft.hxx>
68 #include <AIModel/AIFlightPlan.hxx>
69 #include <AIModel/AIBase.hxx>
70 #include <Airports/airport.hxx>
71 #include <Main/fg_init.hxx>
73 #include "TrafficMgr.hxx"
82 * Thread encapsulating parsing the traffic schedules.
84 class ScheduleParseThread : public SGThread, public XMLVisitor
87 ScheduleParseThread(FGTrafficManager* traffic) :
88 _trafficManager(traffic),
101 // if we're destroyed while running, ensure the thread exits cleanly
102 ~ScheduleParseThread()
106 _cancelThread = true; // request cancellation so we don't wait ages
114 void setTrafficDirs(const PathList& dirs)
116 _trafficDirPaths = dirs;
119 bool isFinished() const
121 SGGuard<SGMutex> g(_lock);
127 BOOST_FOREACH(SGPath p, _trafficDirPaths) {
134 SGGuard<SGMutex> g(_lock);
140 //cout << "Start XML" << endl;
141 requiredAircraft = "";
147 //cout << "End XML" << endl;
150 void startElement(const char *name,
151 const XMLAttributes & atts)
154 //cout << "Start element " << name << endl;
155 //FGTrafficManager temp;
156 //for (int i = 0; i < atts.size(); i++)
157 // if (string(atts.getName(i)) == string("include"))
158 attval = atts.getValue("include");
160 //cout << "including " << attval << endl;
161 SGPath path = globals->get_fg_root();
162 path.append("/Traffic/");
164 readXML(path.str(), *this);
166 elementValueStack.push_back("");
167 // cout << " " << atts.getName(i) << '=' << atts.getValue(i) << endl;
170 void endElement(const char *name)
172 //cout << "End element " << name << endl;
173 const string & value = elementValueStack.back();
175 if (!strcmp(name, "model"))
177 else if (!strcmp(name, "livery"))
179 else if (!strcmp(name, "home-port"))
181 else if (!strcmp(name, "registration"))
182 registration = value;
183 else if (!strcmp(name, "airline"))
185 else if (!strcmp(name, "actype"))
187 else if (!strcmp(name, "required-aircraft"))
188 requiredAircraft = value;
189 else if (!strcmp(name, "flighttype"))
191 else if (!strcmp(name, "radius"))
192 radius = atoi(value.c_str());
193 else if (!strcmp(name, "offset"))
194 offset = atoi(value.c_str());
195 else if (!strcmp(name, "performance-class"))
197 else if (!strcmp(name, "heavy")) {
198 if (value == string("true"))
202 } else if (!strcmp(name, "callsign"))
204 else if (!strcmp(name, "fltrules"))
206 else if (!strcmp(name, "port"))
208 else if (!strcmp(name, "time"))
210 else if (!strcmp(name, "departure")) {
211 departurePort = port;
212 departureTime = timeString;
213 } else if (!strcmp(name, "cruise-alt"))
214 cruiseAlt = atoi(value.c_str());
215 else if (!strcmp(name, "arrival")) {
217 arrivalTime = timeString;
218 } else if (!strcmp(name, "repeat"))
220 else if (!strcmp(name, "flight")) {
221 // We have loaded and parsed all the information belonging to this flight
222 // so we temporarily store it.
223 //cerr << "Pusing back flight " << callsign << endl;
224 //cerr << callsign << " " << fltrules << " "<< departurePort << " " << arrivalPort << " "
225 // << cruiseAlt << " " << departureTime<< " "<< arrivalTime << " " << repeat << endl;
227 //Prioritize aircraft
228 string apt = fgGetString("/sim/presets/airport-id");
229 //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
230 //if (departurePort == apt) score++;
231 //flights.push_back(new FGScheduledFlight(callsign,
239 if (requiredAircraft == "") {
241 snprintf(buffer, 16, "%d", acCounter);
242 requiredAircraft = buffer;
244 SG_LOG(SG_AI, SG_DEBUG, "Adding flight: " << callsign << " "
246 << departurePort << " "
247 << arrivalPort << " "
249 << departureTime << " "
250 << arrivalTime << " " << repeat << " " << requiredAircraft);
251 // For database maintainance purposes, it may be convenient to
253 if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
254 SG_LOG(SG_AI, SG_ALERT, "Traffic Dump FLIGHT," << callsign << ","
256 << departurePort << ","
257 << arrivalPort << ","
259 << departureTime << ","
260 << arrivalTime << "," << repeat << "," << requiredAircraft);
263 _trafficManager->flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
272 requiredAircraft = "";
273 } else if (!strcmp(name, "aircraft")) {
277 elementValueStack.pop_back();
281 void data(const char *s, int len)
283 string token = string(s, len);
284 //cout << "Character data " << string(s,len) << endl;
285 elementValueStack.back() += token;
288 void pi(const char *target, const char *data)
290 //cout << "Processing instruction " << target << ' ' << data << endl;
293 void warning(const char *message, int line, int column)
295 SG_LOG(SG_IO, SG_WARN,
296 "Warning: " << message << " (" << line << ',' << column << ')');
299 void error(const char *message, int line, int column)
301 SG_LOG(SG_IO, SG_ALERT,
302 "Error: " << message << " (" << line << ',' << column << ')');
308 string isHeavy = heavy ? "true" : "false";
310 if (missingModels.find(mdl) != missingModels.end()) {
311 // don't stat() or warn again
312 requiredAircraft = homePort = "";
316 if (!FGAISchedule::validModelPath(mdl)) {
317 missingModels.insert(mdl);
318 SG_LOG(SG_AI, SG_WARN, "TrafficMgr: Missing model path:" << mdl);
319 requiredAircraft = homePort = "";
324 (int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
325 int randval = rand() & 100;
326 if (randval > proportion) {
327 requiredAircraft = homePort = "";
331 if (fgGetBool("/sim/traffic-manager/dumpdata") == true) {
332 SG_LOG(SG_AI, SG_ALERT, "Traffic Dump AC," << homePort << "," << registration << "," << requiredAircraft
333 << "," << acType << "," << livery << ","
334 << airline << "," << m_class << "," << offset << "," << radius << "," << flighttype << "," << isHeavy << "," << mdl);
337 if (requiredAircraft == "") {
339 snprintf(buffer, 16, "%d", acCounter);
340 requiredAircraft = buffer;
342 if (homePort == "") {
343 homePort = departurePort;
346 // caution, modifying the scheduled aircraft strucutre from the
347 // 'wrong' thread. This is safe becuase FGTrafficManager won't touch
348 // the structure while we exist.
349 _trafficManager->scheduledAircraft.push_back(new FGAISchedule(mdl,
362 requiredAircraft = "";
367 void parseTrafficDir(const SGPath& path)
372 simgear::Dir trafficDir(path);
373 simgear::PathList d = trafficDir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT);
375 BOOST_FOREACH(SGPath p, d) {
377 SG_LOG(SG_AI, SG_INFO, "parsing traffic in:" << p);
378 simgear::PathList trafficFiles = d2.children(simgear::Dir::TYPE_FILE, ".xml");
379 BOOST_FOREACH(SGPath xml, trafficFiles) {
380 readXML(xml.str(), *this);
385 } // of sub-directories iteration
387 SG_LOG(SG_AI, SG_INFO, "parsing traffic schedules took:" << st.elapsedMSec() << "msec");
390 FGTrafficManager* _trafficManager;
391 mutable SGMutex _lock;
394 PathList _trafficDirPaths;
398 string_list elementValueStack;
399 // record model paths which are missing, to avoid duplicate
400 // warnings when parsing traffic schedules.
401 std::set<std::string> missingModels;
403 std::string mdl, livery, registration, callsign, fltrules,
404 port, timeString, departurePort, departureTime, arrivalPort, arrivalTime,
405 repeat, acType, airline, m_class, flighttype, requiredAircraft, homePort;
407 int score, acCounter;
408 double radius, offset;
413 /******************************************************************************
415 *****************************************************************************/
416 FGTrafficManager::FGTrafficManager() :
419 trafficSyncRequested(false),
420 waitingMetarTime(0.0),
421 enabled("/sim/traffic-manager/enabled"),
422 aiEnabled("/sim/ai/enabled"),
423 realWxEnabled("/environment/realwx/enabled"),
424 metarValid("/environment/metar/valid")
428 FGTrafficManager::~FGTrafficManager()
433 void FGTrafficManager::shutdown()
437 scheduleParser.reset();
444 // Save the heuristics data
445 bool saveData = false;
446 std::ofstream cachefile;
447 if (fgGetBool("/sim/traffic-manager/heuristics")) {
448 SGPath cacheData(globals->get_fg_home());
449 cacheData.append("ai");
450 const string airport = fgGetString("/sim/presets/airport-id");
452 if ((airport) != "") {
454 ::snprintf(buffer, 128, "%c/%c/%c/",
455 airport[0], airport[1], airport[2]);
456 cacheData.append(buffer);
457 if (!cacheData.exists()) {
458 cacheData.create_dir(0755);
460 cacheData.append(airport + "-cache.txt");
461 //cerr << "Saving AI traffic heuristics" << endl;
463 cachefile.open(cacheData.str().c_str());
464 cachefile << "[TrafficManagerCachedata:ref:2011:09:04]" << endl;
468 BOOST_FOREACH(FGAISchedule* acft, scheduledAircraft) {
470 cachefile << acft->getRegistration() << " "
471 << acft->getRunCount() << " "
472 << acft->getHits() << " "
473 << acft->getLastUsed() << endl;
480 scheduledAircraft.clear();
483 currAircraft = scheduledAircraft.begin();
486 trafficSyncRequested = false;
489 void FGTrafficManager::init()
495 // TorstenD: don't start the traffic manager before the FDM is initialized
496 // The FDM needs the scenery loaded and will wait for our spawned AIModels PagedLOD Nodes
497 // to appear if they are close (less than 1000m) to our position
498 if( !fgGetBool("/sim/signals/fdm-initialized") )
502 simgear::SGTerraSync* terraSync = static_cast<simgear::SGTerraSync*>(globals->get_subsystem("terrasync"));
503 bool doDataSync = fgGetBool("/sim/terrasync/ai-data-enabled");
504 if (doDataSync && terraSync) {
505 if (!trafficSyncRequested) {
506 SG_LOG(SG_AI, SG_INFO, "Sync of AI traffic via TerraSync enabled");
507 terraSync->scheduleDataDir("AI/Traffic");
508 trafficSyncRequested = true;
511 if (terraSync->isDataDirPending("AI/Traffic")) {
512 return; // remain in the init state
515 SG_LOG(SG_AI, SG_INFO, "Traffic files sync complete");
519 if (string(fgGetString("/sim/traffic-manager/datafile")).empty()) {
520 PathList dirs = globals->get_data_paths("AI/Traffic");
522 // temporary flag to restrict loading while traffic data is found
523 // through terrasync /and/ fgdata. Ultimatley we *do* want to be able to
526 if (dirs.size() > 1) {
527 SGPath p = dirs.back();
528 if (simgear::strutils::starts_with(p.str(), globals->get_fg_root())) {
538 scheduleParser.reset(new ScheduleParseThread(this));
539 scheduleParser->setTrafficDirs(dirs);
540 scheduleParser->start();
542 fgSetBool("/sim/traffic-manager/heuristics", false);
543 SGPath path = string(fgGetString("/sim/traffic-manager/datafile"));
544 string ext = path.extension();
545 if (path.extension() == "xml") {
547 // use a SchedulerParser to parse, but run it in this thread,
548 // i.e don't start it
549 ScheduleParseThread parser(this);
550 readXML(path.str(), parser);
552 } else if (path.extension() == "conf") {
554 readTimeTableFromFile(path);
557 SG_LOG(SG_AI, SG_ALERT,
558 "Unknown data format " << path.str()
567 void FGTrafficManager::finishInit()
570 SG_LOG(SG_AI, SG_INFO, "finishing AI-Traffic init");
573 // Do sorting and scoring separately, to take advantage of the "homeport" variable
574 BOOST_FOREACH(FGAISchedule* schedule, scheduledAircraft) {
575 schedule->setScore();
578 sort(scheduledAircraft.begin(), scheduledAircraft.end(),
580 currAircraft = scheduledAircraft.begin();
581 currAircraftClosest = scheduledAircraft.begin();
587 void FGTrafficManager::loadHeuristics()
589 if (!fgGetBool("/sim/traffic-manager/heuristics")) {
593 HeuristicMap heurMap;
594 //cerr << "Processing Heuristics" << endl;
595 // Load the heuristics data
596 SGPath cacheData(globals->get_fg_home());
597 cacheData.append("ai");
598 string airport = fgGetString("/sim/presets/airport-id");
599 if ((airport) != "") {
601 ::snprintf(buffer, 128, "%c/%c/%c/",
602 airport[0], airport[1], airport[2]);
603 cacheData.append(buffer);
604 cacheData.append(airport + "-cache.txt");
606 if (cacheData.exists()) {
607 std::ifstream data(cacheData.c_str());
609 if (revisionStr != "[TrafficManagerCachedata:ref:2011:09:04]") {
610 SG_LOG(SG_AI, SG_ALERT,"Traffic Manager Warning: discarding outdated cachefile " <<
611 cacheData.c_str() << " for Airport " << airport);
614 Heuristic h; // = new Heuristic;
615 data >> h.registration >> h.runCount >> h.hits >> h.lastRun;
618 HeuristicMapIterator itr = heurMap.find(h.registration);
619 if (itr != heurMap.end()) {
620 SG_LOG(SG_AI, SG_WARN,"Traffic Manager Warning: found duplicate tailnumber " <<
621 h.registration << " for AI aircraft");
623 heurMap[h.registration] = h;
630 for(currAircraft = scheduledAircraft.begin(); currAircraft != scheduledAircraft.end(); ++currAircraft) {
631 const string& registration = (*currAircraft)->getRegistration();
632 HeuristicMapIterator itr = heurMap.find(registration);
633 if (itr != heurMap.end()) {
634 (*currAircraft)->setrunCount(itr->second.runCount);
635 (*currAircraft)->setHits(itr->second.hits);
636 (*currAircraft)->setLastUsed(itr->second.lastRun);
641 bool FGTrafficManager::metarReady(double dt)
643 // wait for valid METAR (when realWX is enabled only), since we need
644 // to know the active runway
645 if (metarValid || !realWxEnabled)
647 waitingMetarTime = 0.0;
651 // METAR timeout: when running offline, remote server is down etc
652 if (waitingMetarStation != fgGetString("/environment/metar/station-id"))
654 // station has changed: wait for reply, restart timeout
655 waitingMetarTime = 0.0;
656 waitingMetarStation = fgGetString("/environment/metar/station-id");
660 // timeout elapsed (10 seconds)?
661 if (waitingMetarTime > 20.0)
666 waitingMetarTime += dt;
670 void FGTrafficManager::update(double dt)
674 if (inited || doingInit)
684 // traffic depends on AI module
693 if (!doingInit || !scheduleParser->isFinished()) {
700 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
701 if (scheduledAircraft.empty()) {
705 SGVec3d userCart = globals->get_aircraft_position_cart();
707 if (currAircraft == scheduledAircraft.end()) {
708 currAircraft = scheduledAircraft.begin();
711 //cerr << "Processing << " << (*currAircraft)->getRegistration() << " with score " << (*currAircraft)->getScore() << endl;
712 if ((*currAircraft)->update(now, userCart)) {
713 // schedule is done - process another aircraft in next iteration
718 void FGTrafficManager::readTimeTableFromFile(SGPath infileName)
735 vector <string> tokens, depTime,arrTime;
736 vector <string>::iterator it;
737 std::ifstream infile(infileName.str().c_str());
739 infile.getline(buffer, 256);
743 //cerr << "Read line : " << buffer << endl;
744 buffString = string(buffer);
746 Tokenize(buffString, tokens, " \t");
747 //for (it = tokens.begin(); it != tokens.end(); it++) {
748 // cerr << "Tokens: " << *(it) << endl;
751 if (!tokens.empty()) {
752 if (tokens[0] == string("AC")) {
753 if (tokens.size() != 13) {
754 throw sg_io_exception("Error parsing traffic file @ " + buffString, sg_location(infileName.str()));
760 homePort = tokens[1];
761 registration = tokens[2];
762 if (tokens[11] == string("false")) {
769 flightReq = tokens[3] + tokens[5];
770 m_class = tokens[10];
771 FlightType = tokens[9];
772 radius = atof(tokens[8].c_str());
773 offset = atof(tokens[7].c_str());;
775 if (!FGAISchedule::validModelPath(model)) {
776 SG_LOG(SG_AI, SG_WARN, "TrafficMgr: Missing model path:" <<
777 model << " from " << infileName.str());
780 SG_LOG(SG_AI, SG_INFO, "Adding Aircraft" << model << " " << livery << " " << homePort << " "
781 << registration << " " << flightReq << " " << isHeavy
782 << " " << acType << " " << airline << " " << m_class
783 << " " << FlightType << " " << radius << " " << offset);
784 scheduledAircraft.push_back(new FGAISchedule(model,
796 } // of valid model path
798 if (tokens[0] == string("FLIGHT")) {
799 //cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
800 if (tokens.size() != 10) {
801 SG_LOG(SG_AI, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
804 string callsign = tokens[1];
805 string fltrules = tokens[2];
806 string weekdays = tokens[3];
807 string departurePort = tokens[5];
808 string arrivalPort = tokens[7];
809 int cruiseAlt = atoi(tokens[8].c_str());
810 string depTimeGen = tokens[4];
811 string arrTimeGen = tokens[6];
812 string repeat = "WEEK";
813 string requiredAircraft = tokens[9];
815 if (weekdays.size() != 7) {
816 SG_LOG(SG_AI, SG_ALERT, "Found misconfigured weekdays string" << weekdays);
821 Tokenize(depTimeGen, depTime, ":");
822 Tokenize(arrTimeGen, arrTime, ":");
823 double dep = atof(depTime[0].c_str()) + (atof(depTime[1].c_str()) / 60.0);
824 double arr = atof(arrTime[0].c_str()) + (atof(arrTime[1].c_str()) / 60.0);
825 //cerr << "Using " << dep << " " << arr << endl;
826 bool arrivalWeekdayNeedsIncrement = false;
828 arrivalWeekdayNeedsIncrement = true;
830 for (int i = 0; i < 7; i++) {
832 if (weekdays[i] != '.') {
834 snprintf(buffer, 4, "%d/", j);
835 string departureTime = string(buffer) + depTimeGen + string(":00");
837 if (!arrivalWeekdayNeedsIncrement) {
838 arrivalTime = string(buffer) + arrTimeGen + string(":00");
840 if (arrivalWeekdayNeedsIncrement && i != 6 ) {
841 snprintf(buffer, 4, "%d/", j+1);
842 arrivalTime = string(buffer) + arrTimeGen + string(":00");
844 if (arrivalWeekdayNeedsIncrement && i == 6 ) {
845 snprintf(buffer, 4, "%d/", 0);
846 arrivalTime = string(buffer) + arrTimeGen + string(":00");
848 SG_LOG(SG_AI, SG_ALERT, "Adding flight " << callsign << " "
850 << departurePort << " "
851 << arrivalPort << " "
853 << departureTime << " "
854 << arrivalTime << " "
856 << requiredAircraft);
858 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
877 void FGTrafficManager::Tokenize(const string& str,
878 vector<string>& tokens,
879 const string& delimiters)
881 // Skip delimiters at beginning.
882 string::size_type lastPos = str.find_first_not_of(delimiters, 0);
883 // Find first "non-delimiter".
884 string::size_type pos = str.find_first_of(delimiters, lastPos);
886 while (string::npos != pos || string::npos != lastPos)
888 // Found a token, add it to the vector.
889 tokens.push_back(str.substr(lastPos, pos - lastPos));
890 // Skip delimiters. Note the "not_of"
891 lastPos = str.find_first_not_of(delimiters, pos);
892 // Find next "non-delimiter"
893 pos = str.find_first_of(delimiters, lastPos);