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 ****************************************************************************
22 *****************************************************************************/
40 #include <simgear/compiler.h>
41 #include <simgear/sg_inlines.h>
42 #include <simgear/math/sg_geodesy.hxx>
43 #include <simgear/props/props.hxx>
44 #include <simgear/structure/subsystem_mgr.hxx>
45 #include <simgear/xml/easyxml.hxx>
47 #include <AIModel/AIFlightPlan.hxx>
48 #include <AIModel/AIManager.hxx>
49 #include <AIModel/AIAircraft.hxx>
50 #include <Airports/simple.hxx>
51 #include <Main/fg_init.hxx> // That's pretty ugly, but I need fgFindAirportID
54 #include "SchedFlight.hxx"
55 #include "TrafficMgr.hxx"
57 /******************************************************************************
58 * the FGAISchedule class contains data members and code to maintain a
59 * schedule of Flights for an artificially controlled aircraft.
60 *****************************************************************************/
61 FGAISchedule::FGAISchedule()
75 FGAISchedule::FGAISchedule(const string& model,
79 const string& flightId,
92 flightIdentifier = flightId;
101 /*for (FGScheduledFlightVecIterator i = flt.begin();
104 flights.push_back(new FGScheduledFlight((*(*i))));*/
114 FGAISchedule::FGAISchedule(const FGAISchedule &other)
116 modelPath = other.modelPath;
117 homePort = other.homePort;
118 livery = other.livery;
119 registration = other.registration;
121 flightIdentifier = other.flightIdentifier;
122 flights = other.flights;
123 aiAircraft = other.aiAircraft;
124 acType = other.acType;
125 airline = other.airline;
126 m_class = other.m_class;
127 firstRun = other.firstRun;
128 radius = other.radius;
129 groundOffset = other.groundOffset;
130 flightType = other.flightType;
132 distanceToUser = other.distanceToUser;
133 currentDestination = other.currentDestination;
134 firstRun = other.firstRun;
135 runCount = other.runCount;
137 lastRun = other.lastRun;
138 initialized = other.initialized;
144 FGAISchedule::~FGAISchedule()
146 // remove related object from AI manager
149 aiAircraft->setDie(true);
152 /* for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
159 bool FGAISchedule::init()
162 //SGTime* currTimeDate = globals->get_time_params();
164 //tm *temp = currTimeDate->getGmt();
166 //sgTimeFormatTime(&targetTimeDate, buffer);
167 //cout << "Scheduled Time " << buffer << endl;
168 //cout << "Time :" << time(NULL) << " SGTime : " << sgTimeGetGMT(temp) << endl;
169 /*for (FGScheduledFlightVecIterator i = flights.begin();
173 //i->adjustTime(now);
174 if (!((*i)->initializeAirports()))
177 //sort(flights.begin(), flights.end());
178 // Since time isn't initialized yet when this function is called,
179 // Find the closest possible airport.
180 // This should give a reasonable initialization order.
181 //setClosestDistanceToUser();
185 bool FGAISchedule::update(time_t now, const SGVec3d& userCart)
190 //remainingTimeEnroute,
195 scheduleFlights(now);
196 if (flights.empty()) { // No flights available for this aircraft
201 // Sort all the scheduled flights according to scheduled departure time.
202 // Because this is done at every update, we only need to check the status
203 // of the first listed flight.
204 //sort(flights.begin(), flights.end(), compareScheduledFlights);
207 if (fgGetBool("/sim/traffic-manager/instantaneous-action") == true) {
208 deptime = now; // + rand() % 300; // Wait up to 5 minutes until traffic starts moving to prevent too many aircraft
209 // from cluttering the gate areas.
214 FGScheduledFlight* flight = flights.front();
216 deptime = flight->getDepartureTime();
217 //cerr << "Setting departure time " << deptime << endl;
221 if (aiAircraft->getDie()) {
224 return true; // in visual range, let the AIManager handle it
228 // This flight entry is entirely in the past, do we need to
229 // push it forward in time to the next scheduled departure.
230 if (flight->getArrivalTime() < now) {
231 SG_LOG (SG_AI, SG_BULK, "Traffic Manager: Flight is in the Past");
232 // Don't just update: check whether we need to load a new leg. etc.
233 // This update occurs for distant aircraft, so we can update the current leg
234 // and detach it from the current list of aircraft.
236 flights.erase(flights.begin()); // pop_front(), effectively
240 FGAirport* dep = flight->getDepartureAirport();
241 FGAirport* arr = flight->getArrivalAirport();
246 double speed = 450.0;
248 totalTimeEnroute = flight->getArrivalTime() - flight->getDepartureTime();
249 if (flight->getDepartureTime() < now) {
250 elapsedTimeEnroute = now - flight->getDepartureTime();
251 //remainingTimeEnroute = totalTimeEnroute - elapsedTimeEnroute;
252 double x = elapsedTimeEnroute / (double) totalTimeEnroute;
254 // current pos is based on great-circle course between departure/arrival,
255 // with percentage of distance travelled, based upon percentage of time
257 double course, az2, distanceM;
258 SGGeodesy::inverse(dep->geod(), arr->geod(), course, az2, distanceM);
259 double coveredDistance = distanceM * x;
261 SGGeodesy::direct(dep->geod(), course, coveredDistance, position, az2);
263 SG_LOG (SG_AI, SG_BULK, "Traffic Manager: Flight is in progress, %=" << x);
264 speed = ((distanceM - coveredDistance) * SG_METER_TO_NM) / 3600.0;
267 //remainingTimeEnroute = totalTimeEnroute;
268 elapsedTimeEnroute = 0;
269 position = dep->geod();
270 SG_LOG (SG_AI, SG_BULK, "Traffic Manager: Flight is pending, departure in "
271 << flight->getDepartureTime() - now << " seconds ");
274 // departure / arrival coincident
275 //remainingTimeEnroute = totalTimeEnroute = 0.0;
276 elapsedTimeEnroute = 0;
277 position = dep->geod();
280 // cartesian calculations are more numerically stable over the (potentially)
281 // large distances involved here: see bug #80
282 distanceToUser = dist(userCart, SGVec3d::fromGeod(position)) * SG_METER_TO_NM;
284 // If distance between user and simulated aircaft is less
285 // then 500nm, create this flight. At jet speeds 500 nm is roughly
286 // one hour flight time, so that would be a good approximate point
287 // to start a more detailed simulation of this aircraft.
288 SG_LOG (SG_AI, SG_BULK, "Traffic manager: " << registration << " is scheduled for a flight from "
289 << dep->getId() << " to " << arr->getId() << ". Current distance to user: "
291 if (distanceToUser >= TRAFFICTOAIDISTTOSTART) {
292 return true; // out of visual range, for the moment.
294 return createAIAircraft(flight, speed, deptime);
297 bool FGAISchedule::validModelPath(const std::string& modelPath)
299 SGPath mp(globals->get_fg_root());
302 mp.append(modelPath);
304 mp_ai.append(modelPath);
306 return mp.exists() || mp_ai.exists();
309 bool FGAISchedule::createAIAircraft(FGScheduledFlight* flight, double speedKnots, time_t deptime)
311 FGAirport* dep = flight->getDepartureAirport();
312 FGAirport* arr = flight->getArrivalAirport();
313 string flightPlanName = dep->getId() + "-" + arr->getId() + ".xml";
314 SG_LOG(SG_AI, SG_INFO, "Traffic manager: Creating AIModel from:" << flightPlanName);
316 // Only allow traffic to be created when the model path (or the AI version of mp) exists
317 SGPath mp(globals->get_fg_root());
320 mp.append(modelPath);
322 mp_ai.append(modelPath);
324 if (!mp.exists() && !mp_ai.exists()) {
325 SG_LOG(SG_AI, SG_WARN, "TrafficManager: Could not load model " << mp_ai.str());
329 aiAircraft = new FGAIAircraft(this);
330 aiAircraft->setPerformance(acType, m_class); //"jet_transport";
331 aiAircraft->setCompany(airline); //i->getAirline();
332 aiAircraft->setAcType(acType); //i->getAcType();
333 aiAircraft->setPath(modelPath.c_str());
334 //aircraft->setFlightPlan(flightPlanName);
335 aiAircraft->setLatitude(position.getLatitudeDeg());
336 aiAircraft->setLongitude(position.getLongitudeDeg());
337 aiAircraft->setAltitude(flight->getCruiseAlt()*100); // convert from FL to feet
338 aiAircraft->setSpeed(0);
339 aiAircraft->setBank(0);
341 courseToDest = SGGeodesy::courseDeg(position, arr->geod());
342 FGAIFlightPlan *fp = new FGAIFlightPlan(aiAircraft, flightPlanName, courseToDest, deptime,
343 dep, arr, true, radius,
344 flight->getCruiseAlt()*100,
345 position.getLatitudeDeg(),
346 position.getLongitudeDeg(),
347 speedKnots, flightType, acType,
349 if (fp->isValidPlan()) {
350 aiAircraft->SetFlightPlan(fp);
351 FGAIManager* aimgr = (FGAIManager *) globals-> get_subsystem("ai-model");
352 aimgr->attach(aiAircraft);
357 //hand back the flights that had already been scheduled
358 while (!flights.empty()) {
359 flights.front()->release();
360 flights.erase(flights.begin());
366 // Create an initial heading for user controlled aircraft.
367 void FGAISchedule::setHeading()
369 courseToDest = SGGeodesy::courseDeg((*flights.begin())->getDepartureAirport()->geod(), (*flights.begin())->getArrivalAirport()->geod());
372 void FGAISchedule::scheduleFlights(time_t now)
374 if (!flights.empty()) {
377 //string startingPort;
378 string userPort = fgGetString("/sim/presets/airport-id");
379 SG_LOG(SG_AI, SG_BULK, "Scheduling Flights for : " << modelPath << " " << registration << " " << homePort);
380 FGScheduledFlight *flight = NULL;
382 if (currentDestination.empty()) {
383 flight = findAvailableFlight(userPort, flightIdentifier, now, (now+6400));
385 flight = findAvailableFlight(currentDestination, flightIdentifier);
387 flight = findAvailableFlight(currentDestination, flightIdentifier);
392 currentDestination = flight->getArrivalAirport()->getId();
393 //cerr << "Current destination " << currentDestination << endl;
395 string departurePort = flight->getDepartureAirport()->getId();
396 if (userPort == departurePort) {
407 dep = flight->getDepartureTime();
408 arr = flight->getArrivalTime();
409 string depT = asctime(gmtime(&dep));
410 string arrT = asctime(gmtime(&arr));
412 depT = depT.substr(0,24);
413 arrT = arrT.substr(0,24);
414 SG_LOG(SG_AI, SG_BULK, " Flight " << flight->getCallSign() << ":"
415 << " " << flight->getDepartureAirport()->getId() << ":"
416 << " " << depT << ":"
417 << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
418 << " " << arrT << ":");
420 flights.push_back(flight);
421 } while (currentDestination != homePort);
422 SG_LOG(SG_AI, SG_BULK, " Done ");
425 bool FGAISchedule::next()
427 if (!flights.empty()) {
428 flights.front()->release();
429 flights.erase(flights.begin());
432 FGScheduledFlight *flight = findAvailableFlight(currentDestination, flightIdentifier);
437 currentDestination = flight->getArrivalAirport()->getId();
440 dep = flight->getDepartureTime();
441 arr = flight->getArrivalTime();
442 string depT = asctime(gmtime(&dep));
443 string arrT = asctime(gmtime(&arr));
445 depT = depT.substr(0,24);
446 arrT = arrT.substr(0,24);
447 //cerr << " " << flight->getCallSign() << ":"
448 // << " " << flight->getDepartureAirport()->getId() << ":"
449 // << " " << depT << ":"
450 // << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
451 // << " " << arrT << ":" << endl;
453 flights.push_back(flight);
457 FGScheduledFlight* FGAISchedule::findAvailableFlight (const string ¤tDestination,
459 time_t min, time_t max)
461 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
463 FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("traffic-manager");
464 FGScheduledFlightVecIterator fltBegin, fltEnd;
465 fltBegin = tmgr->getFirstFlight(req);
466 fltEnd = tmgr->getLastFlight(req);
469 //cerr << "Finding available flight " << endl;
471 // Traverse every registered flight
472 if (fltBegin == fltEnd) {
473 //cerr << "No Flights Scheduled for " << req << endl;
476 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
477 (*i)->adjustTime(now);
478 //sort(fltBegin, fltEnd, compareScheduledFlights);
479 //cerr << counter++ << endl;
481 std::sort(fltBegin, fltEnd, compareScheduledFlights);
482 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
485 if (!(*i)->isAvailable()) {
486 //cerr << (*i)->getCallSign() << "is no longer available" << endl;
489 if (!((*i)->getRequirement() == req)) {
492 if (!(((*i)->getArrivalAirport()) && ((*i)->getDepartureAirport()))) {
495 if (!(currentDestination.empty())) {
496 if (currentDestination != (*i)->getDepartureAirport()->getId()) {
497 //cerr << (*i)->getCallSign() << "Doesn't match destination" << endl;
498 //cerr << "Current Destination " << currentDestination << "Doesnt match flight's " <<
499 // (*i)->getArrivalAirport()->getId() << endl;
503 if (flights.size()) {
504 time_t arrival = flights.back()->getArrivalTime();
505 int groundTime = groundTimeFromRadius();
506 if ((*i)->getDepartureTime() < (arrival+(groundTime)))
510 time_t dep = (*i)->getDepartureTime();
511 if ((dep < min) || (dep > max))
515 // So, if we actually get here, we have a winner
516 //cerr << "found flight: " << req << " : " << currentDestination << " : " <<
517 // (*i)->getArrivalAirport()->getId() << endl;
522 // if currentDestination has a value, does it match departure of next flight?
523 // is departure time later than planned arrival?
524 // is departure port valid?
525 // is arrival port valid?
526 //cerr << "Ack no flight found: " << endl;
530 int FGAISchedule::groundTimeFromRadius()
534 else if (radius < 15)
536 else if (radius < 20)
538 else if (radius < 25)
540 else if (radius < 30)
547 double FGAISchedule::getSpeed()
549 FGScheduledFlightVecIterator i = flights.begin();
551 FGAirport* dep = (*i)->getDepartureAirport(),
552 *arr = (*i)->getArrivalAirport();
553 double dist = SGGeodesy::distanceNm(dep->geod(), arr->geod());
554 double remainingTimeEnroute = (*i)->getArrivalTime() - (*i)->getDepartureTime();
556 double speed = dist / (remainingTimeEnroute/3600.0);
557 SG_CLAMP_RANGE(speed, 300.0, 500.0);
561 void FGAISchedule::setScore ()
564 score = ((double) hits / (double) runCount);
566 if (homePort == fgGetString("/sim/presets/airport-id")) {
575 bool compareSchedules(FGAISchedule*a, FGAISchedule*b)
580 bool FGAISchedule::operator< (const FGAISchedule &other) const
582 //cerr << "Sorting " << registration << " and " << other.registration << endl;
583 double currentScore = score * (1.5 - lastRun);
584 double otherScore = other.score * (1.5 - other.lastRun);
585 return currentScore > otherScore;