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 *****************************************************************************/
55 #include <simgear/compiler.h>
56 #include <simgear/misc/sg_path.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"
74 /******************************************************************************
76 *****************************************************************************/
77 FGTrafficManager::FGTrafficManager()
84 FGTrafficManager:: ~FGTrafficManager()
86 for (ScheduleVectorIterator sched = scheduledAircraft.begin(); sched != scheduledAircraft.end(); sched++)
90 scheduledAircraft.clear();
95 void FGTrafficManager::init()
98 ulDirEnt* dent, *dent2;
99 SGPath aircraftDir = globals->get_fg_root();
101 SGPath path = aircraftDir;
103 aircraftDir.append("AI/Traffic");
104 if ((d = ulOpenDir(aircraftDir.c_str())) != NULL)
106 while((dent = ulReadDir(d)) != NULL) {
107 if (string(dent->d_name) != string(".") &&
108 string(dent->d_name) != string("..") &&
111 SGPath currACDir = aircraftDir;
112 currACDir.append(dent->d_name);
113 if ((d2 = ulOpenDir(currACDir.c_str())) == NULL)
115 while ((dent2 = ulReadDir(d2)) != NULL) {
116 SGPath currFile = currACDir;
117 currFile.append(dent2->d_name);
118 if (currFile.extension() == string("xml"))
120 SGPath currFile = currACDir;
121 currFile.append(dent2->d_name);
122 SG_LOG(SG_GENERAL, SG_INFO, "Scanning " << currFile.str() << " for traffic");
123 readXML(currFile.str(),*this);
131 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
133 currAircraft = scheduledAircraft.begin();
134 currAircraftClosest = scheduledAircraft.begin();
137 void FGTrafficManager::update(double /*dt*/)
140 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
141 if (scheduledAircraft.size() == 0) {
144 if(currAircraft == scheduledAircraft.end())
146 currAircraft = scheduledAircraft.begin();
148 if (!((*currAircraft)->update(now)))
150 // NOTE: With traffic manager II, this statement below is no longer true
151 // after proper initialization, we shouldnt get here.
152 // But let's make sure
153 //SG_LOG( SG_GENERAL, SG_ALERT, "Failed to update aircraft schedule in traffic manager");
158 void FGTrafficManager::release(int id)
160 releaseList.push_back(id);
163 bool FGTrafficManager::isReleased(int id)
165 IdListIterator i = releaseList.begin();
166 while (i != releaseList.end())
170 releaseList.erase(i);
178 void FGTrafficManager::readTimeTableFromFile(SGPath infileName)
195 vector <string> tokens, depTime,arrTime;
196 vector <string>::iterator it;
197 ifstream infile(infileName.str().c_str());
199 infile.getline(buffer, 256);
203 //cerr << "Read line : " << buffer << endl;
204 buffString = string(buffer);
206 Tokenize(buffString, tokens, " \t");
207 //for (it = tokens.begin(); it != tokens.end(); it++) {
208 // cerr << "Tokens: " << *(it) << endl;
211 if (!tokens.empty()) {
212 if (tokens[0] == string("AC")) {
213 if (tokens.size() != 13) {
214 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
219 homePort = tokens[1];
220 registration = tokens[2];
221 if (tokens[11] == string("false")) {
228 flightReq = tokens[3] + tokens[5];
229 m_class = tokens[10];
230 FlightType = tokens[9];
231 radius = atof(tokens[8].c_str());
232 offset = atof(tokens[7].c_str());;
233 //cerr << "Found AC string " << model << " " << livery << " " << homePort << " "
234 // << registration << " " << flightReq << " " << isHeavy << " " << acType << " " << airline << " " << m_class
235 // << " " << FlightType << " " << radius << " " << offset << endl;
236 scheduledAircraft.push_back(new FGAISchedule(model,
249 if (tokens[0] == string("FLIGHT")) {
250 //cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
251 if (tokens.size() != 10) {
252 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
255 string callsign = tokens[1];
256 string fltrules = tokens[2];
257 string weekdays = tokens[3];
258 string departurePort = tokens[5];
259 string arrivalPort = tokens[7];
260 int cruiseAlt = atoi(tokens[8].c_str());
261 string depTimeGen = tokens[4];
262 string arrTimeGen = tokens[6];
263 string repeat = "WEEK";
264 string requiredAircraft = tokens[9];
266 if (weekdays.size() != 7) {
267 cerr << "Found misconfigured weekdays string" << weekdays << endl;
272 Tokenize(depTimeGen, depTime, ":");
273 Tokenize(arrTimeGen, arrTime, ":");
274 double dep = atof(depTime[0].c_str()) + (atof(depTime[1].c_str()) / 60.0);
275 double arr = atof(arrTime[0].c_str()) + (atof(arrTime[1].c_str()) / 60.0);
276 //cerr << "Using " << dep << " " << arr << endl;
277 bool arrivalWeekdayNeedsIncrement = false;
279 arrivalWeekdayNeedsIncrement = true;
281 for (int i = 0; i < 7; i++) {
282 if (weekdays[i] != '.') {
284 snprintf(buffer, 4, "%d/", i);
285 string departureTime = string(buffer) + depTimeGen + string(":00");
287 if (!arrivalWeekdayNeedsIncrement) {
288 arrivalTime = string(buffer) + arrTimeGen + string(":00");
290 if (arrivalWeekdayNeedsIncrement && i != 6 ) {
291 snprintf(buffer, 4, "%d/", i+1);
292 arrivalTime = string(buffer) + arrTimeGen + string(":00");
294 if (arrivalWeekdayNeedsIncrement && i == 6 ) {
295 snprintf(buffer, 4, "%d/", 0);
296 arrivalTime = string(buffer) + arrTimeGen + string(":00");
298 cerr << "Adding flight: " << callsign << " "
300 << departurePort << " "
301 << arrivalPort << " "
303 << departureTime << " "
304 << arrivalTime << " "
306 << requiredAircraft << endl;
308 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
327 void FGTrafficManager::Tokenize(const string& str,
328 vector<string>& tokens,
329 const string& delimiters)
331 // Skip delimiters at beginning.
332 string::size_type lastPos = str.find_first_not_of(delimiters, 0);
333 // Find first "non-delimiter".
334 string::size_type pos = str.find_first_of(delimiters, lastPos);
336 while (string::npos != pos || string::npos != lastPos)
338 // Found a token, add it to the vector.
339 tokens.push_back(str.substr(lastPos, pos - lastPos));
340 // Skip delimiters. Note the "not_of"
341 lastPos = str.find_first_not_of(delimiters, pos);
342 // Find next "non-delimiter"
343 pos = str.find_first_of(delimiters, lastPos);
348 void FGTrafficManager::startXML () {
349 //cout << "Start XML" << endl;
350 requiredAircraft = "";
354 void FGTrafficManager::endXML () {
355 //cout << "End XML" << endl;
358 void FGTrafficManager::startElement (const char * name, const XMLAttributes &atts) {
360 //cout << "Start element " << name << endl;
361 //FGTrafficManager temp;
362 //for (int i = 0; i < atts.size(); i++)
363 // if (string(atts.getName(i)) == string("include"))
364 attval = atts.getValue("include");
367 //cout << "including " << attval << endl;
369 globals->get_fg_root();
370 path.append("/Traffic/");
372 readXML(path.str(), *this);
374 elementValueStack.push_back( "" );
375 // cout << " " << atts.getName(i) << '=' << atts.getValue(i) << endl;
378 void FGTrafficManager::endElement (const char * name) {
379 //cout << "End element " << name << endl;
380 string element(name);
381 string value = elementValueStack.back();
382 elementValueStack.pop_back();
384 if (element == string("model"))
386 else if (element == string("livery"))
388 else if (element == string("home-port"))
390 else if (element == string("registration"))
391 registration = value;
392 else if (element == string("airline"))
394 else if (element == string("actype"))
396 else if (element == string("required-aircraft"))
397 requiredAircraft = value;
398 else if (element == string("flighttype"))
400 else if (element == string("radius"))
401 radius = atoi(value.c_str());
402 else if (element == string("offset"))
403 offset = atoi(value.c_str());
404 else if (element == string("performance-class"))
406 else if (element == string("heavy"))
408 if(value == string("true"))
413 else if (element == string("callsign"))
415 else if (element == string("fltrules"))
417 else if (element == string("port"))
419 else if (element == string("time"))
421 else if (element == string("departure"))
423 departurePort = port;
424 departureTime = timeString;
426 else if (element == string("cruise-alt"))
427 cruiseAlt = atoi(value.c_str());
428 else if (element == string("arrival"))
431 arrivalTime = timeString;
433 else if (element == string("repeat"))
435 else if (element == string("flight"))
437 // We have loaded and parsed all the information belonging to this flight
438 // so we temporarily store it.
439 //cerr << "Pusing back flight " << callsign << endl;
440 //cerr << callsign << " " << fltrules << " "<< departurePort << " " << arrivalPort << " "
441 // << cruiseAlt << " " << departureTime<< " "<< arrivalTime << " " << repeat << endl;
443 //Prioritize aircraft
444 string apt = fgGetString("/sim/presets/airport-id");
445 //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
446 //if (departurePort == apt) score++;
447 //flights.push_back(new FGScheduledFlight(callsign,
455 if (requiredAircraft == "") {
457 snprintf(buffer, 16, "%d", acCounter);
458 requiredAircraft = buffer;
460 SG_LOG(SG_GENERAL, SG_DEBUG, "Adding flight: " << callsign << " "
462 << departurePort << " "
463 << arrivalPort << " "
465 << departureTime << " "
466 << arrivalTime << " "
468 << requiredAircraft);
470 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
479 requiredAircraft = "";
481 else if (element == string("aircraft"))
483 int proportion = (int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
484 int randval = rand() & 100;
485 if (randval < proportion) {
486 //scheduledAircraft.push_back(new FGAISchedule(mdl,
498 if (requiredAircraft == "") {
500 snprintf(buffer, 16, "%d", acCounter);
501 requiredAircraft = buffer;
503 if (homePort == "") {
504 homePort = departurePort;
506 scheduledAircraft.push_back(new FGAISchedule(mdl,
519 // while(flights.begin() != flights.end()) {
520 // flights.pop_back();
524 requiredAircraft = "";
526 //for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
531 SG_LOG( SG_GENERAL, SG_BULK, "Reading aircraft : "
533 << " with prioritization score "
539 void FGTrafficManager::data (const char * s, int len) {
540 string token = string(s,len);
541 //cout << "Character data " << string(s,len) << endl;
542 elementValueStack.back() += token;
545 void FGTrafficManager::pi (const char * target, const char * data) {
546 //cout << "Processing instruction " << target << ' ' << data << endl;
549 void FGTrafficManager::warning (const char * message, int line, int column) {
550 SG_LOG(SG_IO, SG_WARN, "Warning: " << message << " (" << line << ',' << column << ')');
553 void FGTrafficManager::error (const char * message, int line, int column) {
554 SG_LOG(SG_IO, SG_ALERT, "Error: " << message << " (" << line << ',' << column << ')');