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/route/waypoint.hxx>
45 #include <simgear/structure/subsystem_mgr.hxx>
46 #include <simgear/xml/easyxml.hxx>
48 #include <AIModel/AIFlightPlan.hxx>
49 #include <AIModel/AIManager.hxx>
50 #include <AIModel/AIAircraft.hxx>
51 #include <Airports/simple.hxx>
52 #include <Main/fg_init.hxx> // That's pretty ugly, but I need fgFindAirportID
55 #include "SchedFlight.hxx"
56 #include "TrafficMgr.hxx"
58 /******************************************************************************
59 * the FGAISchedule class contains data members and code to maintain a
60 * schedule of Flights for an articically controlled aircraft.
61 *****************************************************************************/
62 FGAISchedule::FGAISchedule()
75 FGAISchedule::FGAISchedule(string mdl,
86 FGScheduledFlightVec flt)*/
87 FGAISchedule::FGAISchedule(string model,
104 flightIdentifier = flightId;
113 /*for (FGScheduledFlightVecIterator i = flt.begin();
116 flights.push_back(new FGScheduledFlight((*(*i))));*/
125 FGAISchedule::FGAISchedule(const FGAISchedule &other)
127 modelPath = other.modelPath;
128 homePort = other.homePort;
129 livery = other.livery;
130 registration = other.registration;
132 flightIdentifier = other.flightIdentifier;
133 flights = other.flights;
134 AIManagerRef = other.AIManagerRef;
135 acType = other.acType;
136 airline = other.airline;
137 m_class = other.m_class;
138 firstRun = other.firstRun;
139 radius = other.radius;
140 groundOffset = other.groundOffset;
141 flightType = other.flightType;
143 distanceToUser = other.distanceToUser;
144 currentDestination = other.currentDestination;
145 firstRun = other.firstRun;
146 runCount = other.runCount;
148 initialized = other.initialized;
153 FGAISchedule::~FGAISchedule()
155 /* for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
162 bool FGAISchedule::init()
165 //SGTime* currTimeDate = globals->get_time_params();
167 //tm *temp = currTimeDate->getGmt();
169 //sgTimeFormatTime(&targetTimeDate, buffer);
170 //cout << "Scheduled Time " << buffer << endl;
171 //cout << "Time :" << time(NULL) << " SGTime : " << sgTimeGetGMT(temp) << endl;
172 /*for (FGScheduledFlightVecIterator i = flights.begin();
176 //i->adjustTime(now);
177 if (!((*i)->initializeAirports()))
180 //sort(flights.begin(), flights.end());
181 // Since time isn't initialized yet when this function is called,
182 // Find the closest possible airport.
183 // This should give a reasonable initialization order.
184 //setClosestDistanceToUser();
188 bool FGAISchedule::update(time_t now, const SGVec3d& userCart)
190 if (!fgGetBool("/sim/traffic-manager/enabled"))
196 remainingTimeEnroute,
200 if (flights.empty()) { // No flights available for this aircraft
204 // Sort all the scheduled flights according to scheduled departure time.
205 // Because this is done at every update, we only need to check the status
206 // of the first listed flight.
207 //sort(flights.begin(), flights.end(), compareScheduledFlights);
210 if (fgGetBool("/sim/traffic-manager/instantaneous-action") == true) {
211 deptime = now; // + rand() % 300; // Wait up to 5 minutes until traffic starts moving to prevent too many aircraft
212 // from cluttering the gate areas.
217 FGScheduledFlight* flight = flights.front();
219 deptime = flight->getDepartureTime();
220 //cerr << "Settiing departure time " << deptime << endl;
224 // Check if this aircraft has been released.
225 FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("Traffic Manager");
226 if (tmgr->isReleased(AIManagerRef)) {
229 return true; // in visual range, let the AIManager handle it
233 // This flight entry is entirely in the past, do we need to
234 // push it forward in time to the next scheduled departure.
235 if (flight->getArrivalTime() < now) {
236 SG_LOG (SG_GENERAL, SG_BULK, "Traffic Manager: Flight is in the Past");
237 // Don't just update: check whether we need to load a new leg. etc.
238 // This update occurs for distant aircraft, so we can update the current leg
239 // and detach it from the current list of aircraft.
241 flights.erase(flights.begin()); // pop_front(), effectively
245 FGAirport* dep = flight->getDepartureAirport();
246 FGAirport* arr = flight->getArrivalAirport();
251 double speed = 450.0;
253 totalTimeEnroute = flight->getArrivalTime() - flight->getDepartureTime();
254 if (flight->getDepartureTime() < now) {
255 elapsedTimeEnroute = now - flight->getDepartureTime();
256 remainingTimeEnroute = totalTimeEnroute - elapsedTimeEnroute;
257 double x = elapsedTimeEnroute / (double) totalTimeEnroute;
259 // current pos is based on great-circle course between departure/arrival,
260 // with percentage of distance travelled, based upon percentage of time
262 double course, az2, distanceM;
263 SGGeodesy::inverse(dep->geod(), arr->geod(), course, az2, distanceM);
264 double coveredDistance = distanceM * x;
266 SGGeodesy::direct(dep->geod(), course, coveredDistance, position, az2);
268 SG_LOG (SG_GENERAL, SG_BULK, "Traffic Manager: Flight is in progress, %=" << x);
269 speed = ((distanceM - coveredDistance) * SG_METER_TO_NM) / 3600.0;
272 remainingTimeEnroute = totalTimeEnroute;
273 elapsedTimeEnroute = 0;
274 position = dep->geod();
275 SG_LOG (SG_GENERAL, SG_BULK, "Traffic Manager: Flight is pending, departure in "
276 << flight->getDepartureTime() - now << " seconds ");
279 // departure / arrival coincident
280 remainingTimeEnroute = totalTimeEnroute = 0.0;
281 elapsedTimeEnroute = 0;
282 position = dep->geod();
285 // cartesian calculations are more numerically stable over the (potentially)
286 // large distances involved here: see bug #80
287 distanceToUser = dist(userCart, SGVec3d::fromGeod(position)) * SG_METER_TO_NM;
289 // If distance between user and simulated aircaft is less
290 // then 500nm, create this flight. At jet speeds 500 nm is roughly
291 // one hour flight time, so that would be a good approximate point
292 // to start a more detailed simulation of this aircraft.
293 SG_LOG (SG_GENERAL, SG_BULK, "Traffic manager: " << registration << " is scheduled for a flight from "
294 << dep->getId() << " to " << arr->getId() << ". Current distance to user: "
296 if (distanceToUser >= TRAFFICTOAIDISTTOSTART) {
297 return true; // out of visual range, for the moment.
299 return createAIAircraft(flight, speed, deptime);
302 bool FGAISchedule::createAIAircraft(FGScheduledFlight* flight, double speedKnots, time_t deptime)
304 FGAirport* dep = flight->getDepartureAirport();
305 FGAirport* arr = flight->getArrivalAirport();
306 string flightPlanName = dep->getId() + "-" + arr->getId() + ".xml";
307 SG_LOG(SG_GENERAL, SG_INFO, "Traffic manager: Creating AIModel from:" << flightPlanName);
309 // Only allow traffic to be created when the model path (or the AI version of mp) exists
310 SGPath mp(globals->get_fg_root());
313 mp.append(modelPath);
315 mp_ai.append(modelPath);
317 if (!mp.exists() && !mp_ai.exists()) {
318 SG_LOG(SG_INPUT, SG_WARN, "TrafficManager: Could not load model " << mp.str());
322 FGAIAircraft *aircraft = new FGAIAircraft(this);
323 aircraft->setPerformance(m_class); //"jet_transport";
324 aircraft->setCompany(airline); //i->getAirline();
325 aircraft->setAcType(acType); //i->getAcType();
326 aircraft->setPath(modelPath.c_str());
327 //aircraft->setFlightPlan(flightPlanName);
328 aircraft->setLatitude(position.getLatitudeDeg());
329 aircraft->setLongitude(position.getLongitudeDeg());
330 aircraft->setAltitude(flight->getCruiseAlt()*100); // convert from FL to feet
331 aircraft->setSpeed(speedKnots);
332 aircraft->setBank(0);
334 courseToDest = SGGeodesy::courseDeg(position, arr->geod());
335 aircraft->SetFlightPlan(new FGAIFlightPlan(aircraft, flightPlanName, courseToDest, deptime,
336 dep, arr, true, radius,
337 flight->getCruiseAlt()*100,
338 position.getLatitudeDeg(),
339 position.getLongitudeDeg(),
340 speedKnots, flightType, acType,
344 FGAIManager* aimgr = (FGAIManager *) globals-> get_subsystem("ai_model");
345 aimgr->attach(aircraft);
346 AIManagerRef = aircraft->getID();
350 void FGAISchedule::scheduleFlights()
352 if (!flights.empty()) {
356 SG_LOG(SG_GENERAL, SG_BULK, "Scheduling for : " << modelPath << " " << registration << " " << homePort);
357 FGScheduledFlight *flight = NULL;
359 flight = findAvailableFlight(currentDestination, flightIdentifier);
364 currentDestination = flight->getArrivalAirport()->getId();
366 string departurePort = flight->getDepartureAirport()->getId();
367 //cerr << "Scheduled " << registration << " " << score << " for Flight "
368 // << flight-> getCallSign() << " from " << departurePort << " to " << currentDestination << endl;
369 if (fgGetString("/sim/presets/airport-id") == departurePort) {
377 dep = flight->getDepartureTime();
378 arr = flight->getArrivalTime();
379 string depT = asctime(gmtime(&dep));
380 string arrT = asctime(gmtime(&arr));
382 depT = depT.substr(0,24);
383 arrT = arrT.substr(0,24);
384 SG_LOG(SG_GENERAL, SG_BULK, " " << flight->getCallSign() << ":"
385 << " " << flight->getDepartureAirport()->getId() << ":"
386 << " " << depT << ":"
387 << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
388 << " " << arrT << ":");
390 flights.push_back(flight);
391 } while (currentDestination != homePort);
392 SG_LOG(SG_GENERAL, SG_BULK, " Done ");
395 bool FGAISchedule::next()
397 if (!flights.empty()) {
398 flights.front()->release();
399 flights.erase(flights.begin());
402 FGScheduledFlight *flight = findAvailableFlight(currentDestination, flightIdentifier);
407 currentDestination = flight->getArrivalAirport()->getId();
410 dep = flight->getDepartureTime();
411 arr = flight->getArrivalTime();
412 string depT = asctime(gmtime(&dep));
413 string arrT = asctime(gmtime(&arr));
415 depT = depT.substr(0,24);
416 arrT = arrT.substr(0,24);
417 //cerr << " " << flight->getCallSign() << ":"
418 // << " " << flight->getDepartureAirport()->getId() << ":"
419 // << " " << depT << ":"
420 // << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
421 // << " " << arrT << ":" << endl;
423 flights.push_back(flight);
427 FGScheduledFlight* FGAISchedule::findAvailableFlight (const string ¤tDestination,
430 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
432 FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("Traffic Manager");
433 FGScheduledFlightVecIterator fltBegin, fltEnd;
434 fltBegin = tmgr->getFirstFlight(req);
435 fltEnd = tmgr->getLastFlight(req);
438 //cerr << "Finding available flight " << endl;
440 // Traverse every registered flight
441 if (fltBegin == fltEnd) {
442 //cerr << "No Flights Scheduled for " << req << endl;
445 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
446 (*i)->adjustTime(now);
447 //sort(fltBegin, fltEnd, compareScheduledFlights);
448 //cerr << counter++ << endl;
450 std::sort(fltBegin, fltEnd, compareScheduledFlights);
451 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
454 if (!(*i)->isAvailable()) {
455 //cerr << (*i)->getCallSign() << "is no longer available" << endl;
458 if (!((*i)->getRequirement() == req)) {
461 if (!(((*i)->getArrivalAirport()) && ((*i)->getDepartureAirport()))) {
464 if (!(currentDestination.empty())) {
465 if (currentDestination != (*i)->getDepartureAirport()->getId()) {
466 //cerr << (*i)->getCallSign() << "Doesn't match destination" << endl;
467 //cerr << "Current Destination " << currentDestination << "Doesnt match flight's " <<
468 // (*i)->getArrivalAirport()->getId() << endl;
473 // So, if we actually get here, we have a winner
474 //cerr << "found flight: " << req << " : " << currentDestination << " : " <<
475 // (*i)->getArrivalAirport()->getId() << endl;
480 // if currentDestination has a value, does it match departure of next flight?
481 // is departure time later than planned arrival?
482 // is departure port valid?
483 // is arrival port valid?
484 //cerr << "Ack no flight found: " << endl;
488 double FGAISchedule::getSpeed()
490 FGScheduledFlightVecIterator i = flights.begin();
492 FGAirport* dep = (*i)->getDepartureAirport(),
493 *arr = (*i)->getArrivalAirport();
494 double dist = SGGeodesy::distanceNm(dep->geod(), arr->geod());
495 double remainingTimeEnroute = (*i)->getArrivalTime() - (*i)->getDepartureTime();
497 double speed = dist / (remainingTimeEnroute/3600.0);
498 SG_CLAMP_RANGE(speed, 300.0, 500.0);
502 void FGAISchedule::setScore ()
505 score = ((double) hits / (double) runCount);
507 if (homePort == fgGetString("/sim/presets/airport-id")) {
516 bool compareSchedules(FGAISchedule*a, FGAISchedule*b)
522 // void FGAISchedule::setClosestDistanceToUser()
531 // elapsedTimeEnroute;
533 // double userLatitude = fgGetDouble("/position/latitude-deg");
534 // double userLongitude = fgGetDouble("/position/longitude-deg");
538 // #if defined( __CYGWIN__) || defined( __MINGW32__)
539 // #define HUGE HUGE_VAL
541 // distanceToUser = HUGE;
542 // FGScheduledFlightVecIterator i = flights.begin();
543 // while (i != flights.end())
545 // dep = i->getDepartureAirport();
549 // SGWayPoint user ( userLongitude,
551 // i->getCruiseAlt());
552 // SGWayPoint current (dep->getLongitude(),
553 // dep->getLatitude(),
555 // user.CourseAndDistance(current, &course, &dist);
556 // if (dist < distanceToUser)
558 // distanceToUser = dist;
559 // //cerr << "Found closest distance to user for " << registration << " to be " << distanceToUser << " at airport " << dep->getId() << endl;
563 // //return distToUser;