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 *****************************************************************************/
56 #include <simgear/compiler.h>
57 #include <simgear/misc/sg_path.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()
86 FGTrafficManager:: ~FGTrafficManager()
88 for (ScheduleVectorIterator sched = scheduledAircraft.begin(); sched != scheduledAircraft.end(); sched++)
92 scheduledAircraft.clear();
97 void FGTrafficManager::init()
100 ulDirEnt* dent, *dent2;
101 SGPath aircraftDir = globals->get_fg_root();
103 SGPath path = aircraftDir;
105 aircraftDir.append("AI/Traffic");
106 if ((d = ulOpenDir(aircraftDir.c_str())) != NULL)
108 while((dent = ulReadDir(d)) != NULL) {
109 if (string(dent->d_name) != string(".") &&
110 string(dent->d_name) != string("..") &&
113 SGPath currACDir = aircraftDir;
114 currACDir.append(dent->d_name);
115 if ((d2 = ulOpenDir(currACDir.c_str())) == NULL)
117 while ((dent2 = ulReadDir(d2)) != NULL) {
118 SGPath currFile = currACDir;
119 currFile.append(dent2->d_name);
120 if (currFile.extension() == string("xml"))
122 SGPath currFile = currACDir;
123 currFile.append(dent2->d_name);
124 SG_LOG(SG_GENERAL, SG_DEBUG, "Scanning " << currFile.str() << " for traffic");
125 readXML(currFile.str(),*this);
134 currAircraft = scheduledAircraft.begin();
135 currAircraftClosest = scheduledAircraft.begin();
138 void FGTrafficManager::update(double /*dt*/)
140 if (fgGetBool("/environment/metar/valid") == false) {
143 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
144 if (scheduledAircraft.size() == 0) {
148 SGVec3d userCart = SGVec3d::fromGeod(SGGeod::fromDeg(
149 fgGetDouble("/position/longitude-deg"),
150 fgGetDouble("/position/latitude-deg")));
152 if(currAircraft == scheduledAircraft.end())
154 currAircraft = scheduledAircraft.begin();
156 if (!((*currAircraft)->update(now, userCart)))
158 // NOTE: With traffic manager II, this statement below is no longer true
159 // after proper initialization, we shouldnt get here.
160 // But let's make sure
161 //SG_LOG( SG_GENERAL, SG_ALERT, "Failed to update aircraft schedule in traffic manager");
166 void FGTrafficManager::release(int id)
168 releaseList.push_back(id);
171 bool FGTrafficManager::isReleased(int id)
173 IdListIterator i = releaseList.begin();
174 while (i != releaseList.end())
178 releaseList.erase(i);
186 void FGTrafficManager::readTimeTableFromFile(SGPath infileName)
203 vector <string> tokens, depTime,arrTime;
204 vector <string>::iterator it;
205 ifstream infile(infileName.str().c_str());
207 infile.getline(buffer, 256);
211 //cerr << "Read line : " << buffer << endl;
212 buffString = string(buffer);
214 Tokenize(buffString, tokens, " \t");
215 //for (it = tokens.begin(); it != tokens.end(); it++) {
216 // cerr << "Tokens: " << *(it) << endl;
219 if (!tokens.empty()) {
220 if (tokens[0] == string("AC")) {
221 if (tokens.size() != 13) {
222 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
227 homePort = tokens[1];
228 registration = tokens[2];
229 if (tokens[11] == string("false")) {
236 flightReq = tokens[3] + tokens[5];
237 m_class = tokens[10];
238 FlightType = tokens[9];
239 radius = atof(tokens[8].c_str());
240 offset = atof(tokens[7].c_str());;
241 //cerr << "Found AC string " << model << " " << livery << " " << homePort << " "
242 // << registration << " " << flightReq << " " << isHeavy << " " << acType << " " << airline << " " << m_class
243 // << " " << FlightType << " " << radius << " " << offset << endl;
244 scheduledAircraft.push_back(new FGAISchedule(model,
257 if (tokens[0] == string("FLIGHT")) {
258 //cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
259 if (tokens.size() != 10) {
260 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
263 string callsign = tokens[1];
264 string fltrules = tokens[2];
265 string weekdays = tokens[3];
266 string departurePort = tokens[5];
267 string arrivalPort = tokens[7];
268 int cruiseAlt = atoi(tokens[8].c_str());
269 string depTimeGen = tokens[4];
270 string arrTimeGen = tokens[6];
271 string repeat = "WEEK";
272 string requiredAircraft = tokens[9];
274 if (weekdays.size() != 7) {
275 cerr << "Found misconfigured weekdays string" << weekdays << endl;
280 Tokenize(depTimeGen, depTime, ":");
281 Tokenize(arrTimeGen, arrTime, ":");
282 double dep = atof(depTime[0].c_str()) + (atof(depTime[1].c_str()) / 60.0);
283 double arr = atof(arrTime[0].c_str()) + (atof(arrTime[1].c_str()) / 60.0);
284 //cerr << "Using " << dep << " " << arr << endl;
285 bool arrivalWeekdayNeedsIncrement = false;
287 arrivalWeekdayNeedsIncrement = true;
289 for (int i = 0; i < 7; i++) {
290 if (weekdays[i] != '.') {
292 snprintf(buffer, 4, "%d/", i);
293 string departureTime = string(buffer) + depTimeGen + string(":00");
295 if (!arrivalWeekdayNeedsIncrement) {
296 arrivalTime = string(buffer) + arrTimeGen + string(":00");
298 if (arrivalWeekdayNeedsIncrement && i != 6 ) {
299 snprintf(buffer, 4, "%d/", i+1);
300 arrivalTime = string(buffer) + arrTimeGen + string(":00");
302 if (arrivalWeekdayNeedsIncrement && i == 6 ) {
303 snprintf(buffer, 4, "%d/", 0);
304 arrivalTime = string(buffer) + arrTimeGen + string(":00");
306 cerr << "Adding flight: " << callsign << " "
308 << departurePort << " "
309 << arrivalPort << " "
311 << departureTime << " "
312 << arrivalTime << " "
314 << requiredAircraft << endl;
316 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
335 void FGTrafficManager::Tokenize(const string& str,
336 vector<string>& tokens,
337 const string& delimiters)
339 // Skip delimiters at beginning.
340 string::size_type lastPos = str.find_first_not_of(delimiters, 0);
341 // Find first "non-delimiter".
342 string::size_type pos = str.find_first_of(delimiters, lastPos);
344 while (string::npos != pos || string::npos != lastPos)
346 // Found a token, add it to the vector.
347 tokens.push_back(str.substr(lastPos, pos - lastPos));
348 // Skip delimiters. Note the "not_of"
349 lastPos = str.find_first_not_of(delimiters, pos);
350 // Find next "non-delimiter"
351 pos = str.find_first_of(delimiters, lastPos);
356 void FGTrafficManager::startXML () {
357 //cout << "Start XML" << endl;
358 requiredAircraft = "";
362 void FGTrafficManager::endXML () {
363 //cout << "End XML" << endl;
366 void FGTrafficManager::startElement (const char * name, const XMLAttributes &atts) {
368 //cout << "Start element " << name << endl;
369 //FGTrafficManager temp;
370 //for (int i = 0; i < atts.size(); i++)
371 // if (string(atts.getName(i)) == string("include"))
372 attval = atts.getValue("include");
375 //cout << "including " << attval << endl;
377 globals->get_fg_root();
378 path.append("/Traffic/");
380 readXML(path.str(), *this);
382 elementValueStack.push_back( "" );
383 // cout << " " << atts.getName(i) << '=' << atts.getValue(i) << endl;
386 void FGTrafficManager::endElement (const char * name) {
387 //cout << "End element " << name << endl;
388 const string& value = elementValueStack.back();
390 if (!strcmp(name, "model"))
392 else if (!strcmp(name, "livery"))
394 else if (!strcmp(name, "home-port"))
396 else if (!strcmp(name, "registration"))
397 registration = value;
398 else if (!strcmp(name, "airline"))
400 else if (!strcmp(name, "actype"))
402 else if (!strcmp(name, "required-aircraft"))
403 requiredAircraft = value;
404 else if (!strcmp(name, "flighttype"))
406 else if (!strcmp(name, "radius"))
407 radius = atoi(value.c_str());
408 else if (!strcmp(name, "offset"))
409 offset = atoi(value.c_str());
410 else if (!strcmp(name, "performance-class"))
412 else if (!strcmp(name, "heavy"))
414 if(value == string("true"))
419 else if (!strcmp(name, "callsign"))
421 else if (!strcmp(name, "fltrules"))
423 else if (!strcmp(name, "port"))
425 else if (!strcmp(name, "time"))
427 else if (!strcmp(name, "departure"))
429 departurePort = port;
430 departureTime = timeString;
432 else if (!strcmp(name, "cruise-alt"))
433 cruiseAlt = atoi(value.c_str());
434 else if (!strcmp(name, "arrival"))
437 arrivalTime = timeString;
439 else if (!strcmp(name, "repeat"))
441 else if (!strcmp(name, "flight"))
443 // We have loaded and parsed all the information belonging to this flight
444 // so we temporarily store it.
445 //cerr << "Pusing back flight " << callsign << endl;
446 //cerr << callsign << " " << fltrules << " "<< departurePort << " " << arrivalPort << " "
447 // << cruiseAlt << " " << departureTime<< " "<< arrivalTime << " " << repeat << endl;
449 //Prioritize aircraft
450 string apt = fgGetString("/sim/presets/airport-id");
451 //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
452 //if (departurePort == apt) score++;
453 //flights.push_back(new FGScheduledFlight(callsign,
461 if (requiredAircraft == "") {
463 snprintf(buffer, 16, "%d", acCounter);
464 requiredAircraft = buffer;
466 SG_LOG(SG_GENERAL, SG_DEBUG, "Adding flight: " << callsign << " "
468 << departurePort << " "
469 << arrivalPort << " "
471 << departureTime << " "
472 << arrivalTime << " "
474 << requiredAircraft);
476 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
485 requiredAircraft = "";
487 else if (!strcmp(name, "aircraft"))
489 int proportion = (int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
490 int randval = rand() & 100;
491 if (randval < proportion) {
492 //scheduledAircraft.push_back(new FGAISchedule(mdl,
504 if (requiredAircraft == "") {
506 snprintf(buffer, 16, "%d", acCounter);
507 requiredAircraft = buffer;
509 if (homePort == "") {
510 homePort = departurePort;
512 scheduledAircraft.push_back(new FGAISchedule(mdl,
525 // while(flights.begin() != flights.end()) {
526 // flights.pop_back();
530 requiredAircraft = "";
532 //for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
537 SG_LOG( SG_GENERAL, SG_BULK, "Reading aircraft : "
539 << " with prioritization score "
543 elementValueStack.pop_back();
546 void FGTrafficManager::data (const char * s, int len) {
547 string token = string(s,len);
548 //cout << "Character data " << string(s,len) << endl;
549 elementValueStack.back() += token;
552 void FGTrafficManager::pi (const char * target, const char * data) {
553 //cout << "Processing instruction " << target << ' ' << data << endl;
556 void FGTrafficManager::warning (const char * message, int line, int column) {
557 SG_LOG(SG_IO, SG_WARN, "Warning: " << message << " (" << line << ',' << column << ')');
560 void FGTrafficManager::error (const char * message, int line, int column) {
561 SG_LOG(SG_IO, SG_ALERT, "Error: " << message << " (" << line << ',' << column << ')');