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()
74 scheduleComplete(false)
79 FGAISchedule::FGAISchedule(const string& model,
83 const string& flightId,
103 scheduleComplete(false)
109 flightIdentifier = flightId;
114 /*for (FGScheduledFlightVecIterator i = flt.begin();
117 flights.push_back(new FGScheduledFlight((*(*i))));*/
120 FGAISchedule::FGAISchedule(const FGAISchedule &other)
122 modelPath = other.modelPath;
123 homePort = other.homePort;
124 livery = other.livery;
125 registration = other.registration;
127 flightIdentifier = other.flightIdentifier;
128 flights = other.flights;
129 aiAircraft = other.aiAircraft;
130 acType = other.acType;
131 airline = other.airline;
132 m_class = other.m_class;
133 firstRun = other.firstRun;
134 radius = other.radius;
135 groundOffset = other.groundOffset;
136 flightType = other.flightType;
138 distanceToUser = other.distanceToUser;
139 currentDestination = other.currentDestination;
140 firstRun = other.firstRun;
141 runCount = other.runCount;
143 lastRun = other.lastRun;
144 courseToDest = other.courseToDest;
145 initialized = other.initialized;
147 scheduleComplete = other.scheduleComplete;
152 FGAISchedule::~FGAISchedule()
154 // remove related object from AI manager
157 aiAircraft->setDie(true);
160 /* for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
167 bool FGAISchedule::init()
170 //SGTime* currTimeDate = globals->get_time_params();
172 //tm *temp = currTimeDate->getGmt();
174 //sgTimeFormatTime(&targetTimeDate, buffer);
175 //cout << "Scheduled Time " << buffer << endl;
176 //cout << "Time :" << time(NULL) << " SGTime : " << sgTimeGetGMT(temp) << endl;
177 /*for (FGScheduledFlightVecIterator i = flights.begin();
181 //i->adjustTime(now);
182 if (!((*i)->initializeAirports()))
185 //sort(flights.begin(), flights.end());
186 // Since time isn't initialized yet when this function is called,
187 // Find the closest possible airport.
188 // This should give a reasonable initialization order.
189 //setClosestDistanceToUser();
194 * Returns true when processing is complete.
195 * Returns false when processing was aborted due to timeout, so
196 * more time required - and another call is requested (next sim iteration).
198 bool FGAISchedule::update(time_t now, const SGVec3d& userCart)
201 time_t totalTimeEnroute,
203 //remainingTimeEnroute,
207 return true; // processing complete
210 if (!scheduleComplete) {
211 scheduleComplete = scheduleFlights(now);
214 if (!scheduleComplete) {
215 return false; // not ready yet, continue processing in next iteration
218 if (flights.empty()) { // No flights available for this aircraft
220 return true; // processing complete
224 // Sort all the scheduled flights according to scheduled departure time.
225 // Because this is done at every update, we only need to check the status
226 // of the first listed flight.
227 //sort(flights.begin(), flights.end(), compareScheduledFlights);
230 if (fgGetBool("/sim/traffic-manager/instantaneous-action") == true) {
231 deptime = now; // + rand() % 300; // Wait up to 5 minutes until traffic starts moving to prevent too many aircraft
232 // from cluttering the gate areas.
237 FGScheduledFlight* flight = flights.front();
239 deptime = flight->getDepartureTime();
240 //cerr << "Setting departure time " << deptime << endl;
244 if (aiAircraft->getDie()) {
247 return true; // in visual range, let the AIManager handle it
251 // This flight entry is entirely in the past, do we need to
252 // push it forward in time to the next scheduled departure.
253 if (flight->getArrivalTime() < now) {
254 SG_LOG (SG_AI, SG_BULK, "Traffic Manager: Flight is in the Past");
255 // Don't just update: check whether we need to load a new leg. etc.
256 // This update occurs for distant aircraft, so we can update the current leg
257 // and detach it from the current list of aircraft.
259 flights.erase(flights.begin()); // pop_front(), effectively
260 return true; // processing complete
263 FGAirport* dep = flight->getDepartureAirport();
264 FGAirport* arr = flight->getArrivalAirport();
266 return true; // processing complete
269 double speed = 450.0;
271 totalTimeEnroute = flight->getArrivalTime() - flight->getDepartureTime();
272 if (flight->getDepartureTime() < now) {
273 elapsedTimeEnroute = now - flight->getDepartureTime();
274 //remainingTimeEnroute = totalTimeEnroute - elapsedTimeEnroute;
275 double x = elapsedTimeEnroute / (double) totalTimeEnroute;
277 // current pos is based on great-circle course between departure/arrival,
278 // with percentage of distance travelled, based upon percentage of time
280 double course, az2, distanceM;
281 SGGeodesy::inverse(dep->geod(), arr->geod(), course, az2, distanceM);
282 double coveredDistance = distanceM * x;
284 SGGeodesy::direct(dep->geod(), course, coveredDistance, position, az2);
286 SG_LOG (SG_AI, SG_BULK, "Traffic Manager: Flight is in progress, %=" << x);
287 speed = ((distanceM - coveredDistance) * SG_METER_TO_NM) / 3600.0;
290 //remainingTimeEnroute = totalTimeEnroute;
291 elapsedTimeEnroute = 0;
292 position = dep->geod();
293 SG_LOG (SG_AI, SG_BULK, "Traffic Manager: Flight is pending, departure in "
294 << flight->getDepartureTime() - now << " seconds ");
297 // departure / arrival coincident
298 //remainingTimeEnroute = totalTimeEnroute = 0.0;
299 elapsedTimeEnroute = 0;
300 position = dep->geod();
303 // cartesian calculations are more numerically stable over the (potentially)
304 // large distances involved here: see bug #80
305 distanceToUser = dist(userCart, SGVec3d::fromGeod(position)) * SG_METER_TO_NM;
308 // If distance between user and simulated aircraft is less
309 // then 500nm, create this flight. At jet speeds 500 nm is roughly
310 // one hour flight time, so that would be a good approximate point
311 // to start a more detailed simulation of this aircraft.
312 SG_LOG (SG_AI, SG_BULK, "Traffic manager: " << registration << " is scheduled for a flight from "
313 << dep->getId() << " to " << arr->getId() << ". Current distance to user: "
315 if (distanceToUser >= TRAFFICTOAIDISTTOSTART) {
316 return true; // out of visual range, for the moment.
319 if (!createAIAircraft(flight, speed, deptime)) {
324 return true; // processing complete
327 bool FGAISchedule::validModelPath(const std::string& modelPath)
329 SGPath mp(globals->get_fg_root());
332 mp.append(modelPath);
334 mp_ai.append(modelPath);
336 return mp.exists() || mp_ai.exists();
339 bool FGAISchedule::createAIAircraft(FGScheduledFlight* flight, double speedKnots, time_t deptime)
341 FGAirport* dep = flight->getDepartureAirport();
342 FGAirport* arr = flight->getArrivalAirport();
343 string flightPlanName = dep->getId() + "-" + arr->getId() + ".xml";
344 SG_LOG(SG_AI, SG_INFO, "Traffic manager: Creating AIModel from:" << flightPlanName);
346 // Only allow traffic to be created when the model path (or the AI version of mp) exists
347 SGPath mp(globals->get_fg_root());
350 mp.append(modelPath);
352 mp_ai.append(modelPath);
354 if (!mp.exists() && !mp_ai.exists()) {
355 SG_LOG(SG_AI, SG_WARN, "TrafficManager: Could not load model " << mp_ai.str());
359 aiAircraft = new FGAIAircraft(this);
360 aiAircraft->setPerformance(acType, m_class); //"jet_transport";
361 aiAircraft->setCompany(airline); //i->getAirline();
362 aiAircraft->setAcType(acType); //i->getAcType();
363 aiAircraft->setPath(modelPath.c_str());
364 //aircraft->setFlightPlan(flightPlanName);
365 aiAircraft->setLatitude(position.getLatitudeDeg());
366 aiAircraft->setLongitude(position.getLongitudeDeg());
367 aiAircraft->setAltitude(flight->getCruiseAlt()*100); // convert from FL to feet
368 aiAircraft->setSpeed(0);
369 aiAircraft->setBank(0);
371 courseToDest = SGGeodesy::courseDeg(position, arr->geod());
372 FGAIFlightPlan *fp = new FGAIFlightPlan(aiAircraft, flightPlanName, courseToDest, deptime,
373 dep, arr, true, radius,
374 flight->getCruiseAlt()*100,
375 position.getLatitudeDeg(),
376 position.getLongitudeDeg(),
377 speedKnots, flightType, acType,
379 if (fp->isValidPlan()) {
380 aiAircraft->SetFlightPlan(fp);
381 FGAIManager* aimgr = (FGAIManager *) globals-> get_subsystem("ai-model");
382 aimgr->attach(aiAircraft);
387 //hand back the flights that had already been scheduled
388 while (!flights.empty()) {
389 flights.front()->release();
390 flights.erase(flights.begin());
396 // Create an initial heading for user controlled aircraft.
397 void FGAISchedule::setHeading()
399 courseToDest = SGGeodesy::courseDeg((*flights.begin())->getDepartureAirport()->geod(), (*flights.begin())->getArrivalAirport()->geod());
402 bool FGAISchedule::scheduleFlights(time_t now)
404 //string startingPort;
405 const string& userPort = fgGetString("/sim/presets/airport-id");
406 SG_LOG(SG_AI, SG_BULK, "Scheduling Flights for : " << modelPath << " " << registration << " " << homePort);
407 FGScheduledFlight *flight = NULL;
412 if (currentDestination.empty())
413 flight = findAvailableFlight(userPort, flightIdentifier, now, (now+6400));
416 if ((!flight)||(!first)) {
417 flight = findAvailableFlight(currentDestination, flightIdentifier);
424 currentDestination = flight->getArrivalAirport()->getId();
425 //cerr << "Current destination " << currentDestination << endl;
427 const string& departurePort = flight->getDepartureAirport()->getId();
428 if (userPort == departurePort) {
438 if (sglog().would_log(SG_AI, SG_BULK))
441 dep = flight->getDepartureTime();
442 arr = flight->getArrivalTime();
443 string depT = asctime(gmtime(&dep));
444 string arrT = asctime(gmtime(&arr));
445 depT = depT.substr(0,24);
446 arrT = arrT.substr(0,24);
447 SG_LOG(SG_AI, SG_BULK, " Flight " << flight->getCallSign() << ":"
448 << " " << flight->getDepartureAirport()->getId() << ":"
449 << " " << depT << ":"
450 << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
451 << " " << arrT << ":");
454 flights.push_back(flight);
456 // continue processing until complete, or preempt after timeout
457 } while ((currentDestination != homePort)&&
458 (start.elapsedMSec()<3.0));
460 if (flight && (currentDestination != homePort))
462 // processing preempted, need to continue in next iteration
466 SG_LOG(SG_AI, SG_BULK, " Done ");
470 bool FGAISchedule::next()
472 if (!flights.empty()) {
473 flights.front()->release();
474 flights.erase(flights.begin());
477 FGScheduledFlight *flight = findAvailableFlight(currentDestination, flightIdentifier);
482 currentDestination = flight->getArrivalAirport()->getId();
485 dep = flight->getDepartureTime();
486 arr = flight->getArrivalTime();
487 string depT = asctime(gmtime(&dep));
488 string arrT = asctime(gmtime(&arr));
490 depT = depT.substr(0,24);
491 arrT = arrT.substr(0,24);
492 //cerr << " " << flight->getCallSign() << ":"
493 // << " " << flight->getDepartureAirport()->getId() << ":"
494 // << " " << depT << ":"
495 // << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
496 // << " " << arrT << ":" << endl;
498 flights.push_back(flight);
502 FGScheduledFlight* FGAISchedule::findAvailableFlight (const string ¤tDestination,
504 time_t min, time_t max)
506 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
508 FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("traffic-manager");
509 FGScheduledFlightVecIterator fltBegin, fltEnd;
510 fltBegin = tmgr->getFirstFlight(req);
511 fltEnd = tmgr->getLastFlight(req);
514 //cerr << "Finding available flight " << endl;
516 // Traverse every registered flight
517 if (fltBegin == fltEnd) {
518 //cerr << "No Flights Scheduled for " << req << endl;
521 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
522 (*i)->adjustTime(now);
523 //sort(fltBegin, fltEnd, compareScheduledFlights);
524 //cerr << counter++ << endl;
526 std::sort(fltBegin, fltEnd, compareScheduledFlights);
527 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
530 if (!(*i)->isAvailable()) {
531 //cerr << (*i)->getCallSign() << "is no longer available" << endl;
534 if (!((*i)->getRequirement() == req)) {
537 if (!(((*i)->getArrivalAirport()) && ((*i)->getDepartureAirport()))) {
540 if (!(currentDestination.empty())) {
541 if (currentDestination != (*i)->getDepartureAirport()->getId()) {
542 //cerr << (*i)->getCallSign() << "Doesn't match destination" << endl;
543 //cerr << "Current Destination " << currentDestination << "Doesnt match flight's " <<
544 // (*i)->getArrivalAirport()->getId() << endl;
548 if (flights.size()) {
549 time_t arrival = flights.back()->getArrivalTime();
550 int groundTime = groundTimeFromRadius();
551 if ((*i)->getDepartureTime() < (arrival+(groundTime)))
555 time_t dep = (*i)->getDepartureTime();
556 if ((dep < min) || (dep > max))
560 // So, if we actually get here, we have a winner
561 //cerr << "found flight: " << req << " : " << currentDestination << " : " <<
562 // (*i)->getArrivalAirport()->getId() << endl;
567 // if currentDestination has a value, does it match departure of next flight?
568 // is departure time later than planned arrival?
569 // is departure port valid?
570 // is arrival port valid?
571 //cerr << "Ack no flight found: " << endl;
575 int FGAISchedule::groundTimeFromRadius()
579 else if (radius < 15)
581 else if (radius < 20)
583 else if (radius < 25)
585 else if (radius < 30)
592 double FGAISchedule::getSpeed()
594 FGScheduledFlightVecIterator i = flights.begin();
596 FGAirport* dep = (*i)->getDepartureAirport(),
597 *arr = (*i)->getArrivalAirport();
598 double dist = SGGeodesy::distanceNm(dep->geod(), arr->geod());
599 double remainingTimeEnroute = (*i)->getArrivalTime() - (*i)->getDepartureTime();
601 double speed = dist / (remainingTimeEnroute/3600.0);
602 SG_CLAMP_RANGE(speed, 300.0, 500.0);
606 void FGAISchedule::setScore ()
609 score = ((double) hits / (double) runCount);
611 if (homePort == fgGetString("/sim/presets/airport-id")) {
620 bool compareSchedules(FGAISchedule*a, FGAISchedule*b)
625 bool FGAISchedule::operator< (const FGAISchedule &other) const
627 //cerr << "Sorting " << registration << " and " << other.registration << endl;
628 double currentScore = score * (1.5 - lastRun);
629 double otherScore = other.score * (1.5 - other.lastRun);
630 return currentScore > otherScore;