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*/)
141 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
142 if (scheduledAircraft.size() == 0) {
146 SGVec3d userCart = SGVec3d::fromGeod(SGGeod::fromDeg(
147 fgGetDouble("/position/longitude-deg"),
148 fgGetDouble("/position/latitude-deg")));
150 if(currAircraft == scheduledAircraft.end())
152 currAircraft = scheduledAircraft.begin();
154 if (!((*currAircraft)->update(now, userCart)))
156 // NOTE: With traffic manager II, this statement below is no longer true
157 // after proper initialization, we shouldnt get here.
158 // But let's make sure
159 //SG_LOG( SG_GENERAL, SG_ALERT, "Failed to update aircraft schedule in traffic manager");
164 void FGTrafficManager::release(int id)
166 releaseList.push_back(id);
169 bool FGTrafficManager::isReleased(int id)
171 IdListIterator i = releaseList.begin();
172 while (i != releaseList.end())
176 releaseList.erase(i);
184 void FGTrafficManager::readTimeTableFromFile(SGPath infileName)
201 vector <string> tokens, depTime,arrTime;
202 vector <string>::iterator it;
203 ifstream infile(infileName.str().c_str());
205 infile.getline(buffer, 256);
209 //cerr << "Read line : " << buffer << endl;
210 buffString = string(buffer);
212 Tokenize(buffString, tokens, " \t");
213 //for (it = tokens.begin(); it != tokens.end(); it++) {
214 // cerr << "Tokens: " << *(it) << endl;
217 if (!tokens.empty()) {
218 if (tokens[0] == string("AC")) {
219 if (tokens.size() != 13) {
220 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
225 homePort = tokens[1];
226 registration = tokens[2];
227 if (tokens[11] == string("false")) {
234 flightReq = tokens[3] + tokens[5];
235 m_class = tokens[10];
236 FlightType = tokens[9];
237 radius = atof(tokens[8].c_str());
238 offset = atof(tokens[7].c_str());;
239 //cerr << "Found AC string " << model << " " << livery << " " << homePort << " "
240 // << registration << " " << flightReq << " " << isHeavy << " " << acType << " " << airline << " " << m_class
241 // << " " << FlightType << " " << radius << " " << offset << endl;
242 scheduledAircraft.push_back(new FGAISchedule(model,
255 if (tokens[0] == string("FLIGHT")) {
256 //cerr << "Found flight " << buffString << " size is : " << tokens.size() << endl;
257 if (tokens.size() != 10) {
258 SG_LOG(SG_GENERAL, SG_ALERT, "Error parsing traffic file " << infileName.str() << " at " << buffString);
261 string callsign = tokens[1];
262 string fltrules = tokens[2];
263 string weekdays = tokens[3];
264 string departurePort = tokens[5];
265 string arrivalPort = tokens[7];
266 int cruiseAlt = atoi(tokens[8].c_str());
267 string depTimeGen = tokens[4];
268 string arrTimeGen = tokens[6];
269 string repeat = "WEEK";
270 string requiredAircraft = tokens[9];
272 if (weekdays.size() != 7) {
273 cerr << "Found misconfigured weekdays string" << weekdays << endl;
278 Tokenize(depTimeGen, depTime, ":");
279 Tokenize(arrTimeGen, arrTime, ":");
280 double dep = atof(depTime[0].c_str()) + (atof(depTime[1].c_str()) / 60.0);
281 double arr = atof(arrTime[0].c_str()) + (atof(arrTime[1].c_str()) / 60.0);
282 //cerr << "Using " << dep << " " << arr << endl;
283 bool arrivalWeekdayNeedsIncrement = false;
285 arrivalWeekdayNeedsIncrement = true;
287 for (int i = 0; i < 7; i++) {
288 if (weekdays[i] != '.') {
290 snprintf(buffer, 4, "%d/", i);
291 string departureTime = string(buffer) + depTimeGen + string(":00");
293 if (!arrivalWeekdayNeedsIncrement) {
294 arrivalTime = string(buffer) + arrTimeGen + string(":00");
296 if (arrivalWeekdayNeedsIncrement && i != 6 ) {
297 snprintf(buffer, 4, "%d/", i+1);
298 arrivalTime = string(buffer) + arrTimeGen + string(":00");
300 if (arrivalWeekdayNeedsIncrement && i == 6 ) {
301 snprintf(buffer, 4, "%d/", 0);
302 arrivalTime = string(buffer) + arrTimeGen + string(":00");
304 cerr << "Adding flight: " << callsign << " "
306 << departurePort << " "
307 << arrivalPort << " "
309 << departureTime << " "
310 << arrivalTime << " "
312 << requiredAircraft << endl;
314 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
333 void FGTrafficManager::Tokenize(const string& str,
334 vector<string>& tokens,
335 const string& delimiters)
337 // Skip delimiters at beginning.
338 string::size_type lastPos = str.find_first_not_of(delimiters, 0);
339 // Find first "non-delimiter".
340 string::size_type pos = str.find_first_of(delimiters, lastPos);
342 while (string::npos != pos || string::npos != lastPos)
344 // Found a token, add it to the vector.
345 tokens.push_back(str.substr(lastPos, pos - lastPos));
346 // Skip delimiters. Note the "not_of"
347 lastPos = str.find_first_not_of(delimiters, pos);
348 // Find next "non-delimiter"
349 pos = str.find_first_of(delimiters, lastPos);
354 void FGTrafficManager::startXML () {
355 //cout << "Start XML" << endl;
356 requiredAircraft = "";
360 void FGTrafficManager::endXML () {
361 //cout << "End XML" << endl;
364 void FGTrafficManager::startElement (const char * name, const XMLAttributes &atts) {
366 //cout << "Start element " << name << endl;
367 //FGTrafficManager temp;
368 //for (int i = 0; i < atts.size(); i++)
369 // if (string(atts.getName(i)) == string("include"))
370 attval = atts.getValue("include");
373 //cout << "including " << attval << endl;
375 globals->get_fg_root();
376 path.append("/Traffic/");
378 readXML(path.str(), *this);
380 elementValueStack.push_back( "" );
381 // cout << " " << atts.getName(i) << '=' << atts.getValue(i) << endl;
384 void FGTrafficManager::endElement (const char * name) {
385 //cout << "End element " << name << endl;
386 const string& value = elementValueStack.back();
388 if (!strcmp(name, "model"))
390 else if (!strcmp(name, "livery"))
392 else if (!strcmp(name, "home-port"))
394 else if (!strcmp(name, "registration"))
395 registration = value;
396 else if (!strcmp(name, "airline"))
398 else if (!strcmp(name, "actype"))
400 else if (!strcmp(name, "required-aircraft"))
401 requiredAircraft = value;
402 else if (!strcmp(name, "flighttype"))
404 else if (!strcmp(name, "radius"))
405 radius = atoi(value.c_str());
406 else if (!strcmp(name, "offset"))
407 offset = atoi(value.c_str());
408 else if (!strcmp(name, "performance-class"))
410 else if (!strcmp(name, "heavy"))
412 if(value == string("true"))
417 else if (!strcmp(name, "callsign"))
419 else if (!strcmp(name, "fltrules"))
421 else if (!strcmp(name, "port"))
423 else if (!strcmp(name, "time"))
425 else if (!strcmp(name, "departure"))
427 departurePort = port;
428 departureTime = timeString;
430 else if (!strcmp(name, "cruise-alt"))
431 cruiseAlt = atoi(value.c_str());
432 else if (!strcmp(name, "arrival"))
435 arrivalTime = timeString;
437 else if (!strcmp(name, "repeat"))
439 else if (!strcmp(name, "flight"))
441 // We have loaded and parsed all the information belonging to this flight
442 // so we temporarily store it.
443 //cerr << "Pusing back flight " << callsign << endl;
444 //cerr << callsign << " " << fltrules << " "<< departurePort << " " << arrivalPort << " "
445 // << cruiseAlt << " " << departureTime<< " "<< arrivalTime << " " << repeat << endl;
447 //Prioritize aircraft
448 string apt = fgGetString("/sim/presets/airport-id");
449 //cerr << "Airport information: " << apt << " " << departurePort << " " << arrivalPort << endl;
450 //if (departurePort == apt) score++;
451 //flights.push_back(new FGScheduledFlight(callsign,
459 if (requiredAircraft == "") {
461 snprintf(buffer, 16, "%d", acCounter);
462 requiredAircraft = buffer;
464 SG_LOG(SG_GENERAL, SG_DEBUG, "Adding flight: " << callsign << " "
466 << departurePort << " "
467 << arrivalPort << " "
469 << departureTime << " "
470 << arrivalTime << " "
472 << requiredAircraft);
474 flights[requiredAircraft].push_back(new FGScheduledFlight(callsign,
483 requiredAircraft = "";
485 else if (!strcmp(name, "aircraft"))
487 int proportion = (int) (fgGetDouble("/sim/traffic-manager/proportion") * 100);
488 int randval = rand() & 100;
489 if (randval < proportion) {
490 //scheduledAircraft.push_back(new FGAISchedule(mdl,
502 if (requiredAircraft == "") {
504 snprintf(buffer, 16, "%d", acCounter);
505 requiredAircraft = buffer;
507 if (homePort == "") {
508 homePort = departurePort;
510 scheduledAircraft.push_back(new FGAISchedule(mdl,
523 // while(flights.begin() != flights.end()) {
524 // flights.pop_back();
528 requiredAircraft = "";
530 //for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
535 SG_LOG( SG_GENERAL, SG_BULK, "Reading aircraft : "
537 << " with prioritization score "
541 elementValueStack.pop_back();
544 void FGTrafficManager::data (const char * s, int len) {
545 string token = string(s,len);
546 //cout << "Character data " << string(s,len) << endl;
547 elementValueStack.back() += token;
550 void FGTrafficManager::pi (const char * target, const char * data) {
551 //cout << "Processing instruction " << target << ' ' << data << endl;
554 void FGTrafficManager::warning (const char * message, int line, int column) {
555 SG_LOG(SG_IO, SG_WARN, "Warning: " << message << " (" << line << ',' << column << ')');
558 void FGTrafficManager::error (const char * message, int line, int column) {
559 SG_LOG(SG_IO, SG_ALERT, "Error: " << message << " (" << line << ',' << column << ')');