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"
60 /******************************************************************************
61 * the FGAISchedule class contains data members and code to maintain a
62 * schedule of Flights for an articically controlled aircraft.
63 *****************************************************************************/
64 FGAISchedule::FGAISchedule()
79 FGAISchedule::FGAISchedule(string mdl,
90 FGScheduledFlightVec flt)*/
91 FGAISchedule::FGAISchedule(string model,
108 flightIdentifier = flightId;
119 /*for (FGScheduledFlightVecIterator i = flt.begin();
122 flights.push_back(new FGScheduledFlight((*(*i))));*/
128 FGAISchedule::FGAISchedule(const FGAISchedule &other)
130 modelPath = other.modelPath;
131 homePort = other.homePort;
132 livery = other.livery;
133 registration = other.registration;
135 flightIdentifier = other.flightIdentifier;
136 flights = other.flights;
139 AIManagerRef = other.AIManagerRef;
140 acType = other.acType;
141 airline = other.airline;
142 m_class = other.m_class;
143 firstRun = other.firstRun;
144 radius = other.radius;
145 groundOffset = other.groundOffset;
146 flightType = other.flightType;
147 //score = other.score;
148 distanceToUser = other.distanceToUser;
149 currentDestination = other.currentDestination;
150 firstRun = other.firstRun;
154 FGAISchedule::~FGAISchedule()
156 /* for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
163 bool FGAISchedule::init()
166 //SGTime* currTimeDate = globals->get_time_params();
168 //tm *temp = currTimeDate->getGmt();
170 //sgTimeFormatTime(&targetTimeDate, buffer);
171 //cout << "Scheduled Time " << buffer << endl;
172 //cout << "Time :" << time(NULL) << " SGTime : " << sgTimeGetGMT(temp) << endl;
173 /*for (FGScheduledFlightVecIterator i = flights.begin();
177 //i->adjustTime(now);
178 if (!((*i)->initializeAirports()))
181 //sort(flights.begin(), flights.end());
182 // Since time isn't initialized yet when this function is called,
183 // Find the closest possible airport.
184 // This should give a reasonable initialization order.
185 //setClosestDistanceToUser();
189 bool FGAISchedule::update(time_t now)
199 double distanceToDest;
205 remainingTimeEnroute, deptime = 0;
210 if (fgGetBool("/sim/traffic-manager/enabled") == false)
213 aimgr = (FGAIManager *) globals-> get_subsystem("ai_model");
214 // Out-of-work aircraft seeks employment. Willing to work irregular hours ...
215 //cerr << "About to find a flight " << endl;
216 if (flights.empty()) {
217 //execute this loop at least once.
218 SG_LOG(SG_GENERAL, SG_INFO, "Scheduling for : " << modelPath << " " << registration << " " << homePort);
219 FGScheduledFlight *flight = 0;
221 flight = findAvailableFlight(currentDestination, flightIdentifier);
223 currentDestination = flight->getArrivalAirport()->getId();
225 dep = flight->getDepartureTime();
226 arr = flight->getArrivalTime();
227 string depT = asctime(gmtime(&dep));
228 string arrT = asctime(gmtime(&arr));
230 depT = depT.substr(0,24);
231 arrT = arrT.substr(0,24);
232 SG_LOG(SG_GENERAL, SG_INFO, " " << flight->getCallSign() << ":"
233 << " " << flight->getDepartureAirport()->getId() << ":"
234 << " " << depT << ":"
235 << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
236 << " " << arrT << ":");
237 flights.push_back(flight);
239 } while ((currentDestination != homePort) && (flight != 0));
240 SG_LOG(SG_GENERAL, SG_INFO, cerr << " Done " << endl);
242 //cerr << " Done " << endl;
243 // No flights available for this aircraft
244 if (flights.size() == 0) {
247 // Sort all the scheduled flights according to scheduled departure time.
248 // Because this is done at every update, we only need to check the status
249 // of the first listed flight.
250 //sort(flights.begin(), flights.end(), compareScheduledFlights);
252 if (fgGetBool("/sim/traffic-manager/instantaneous-action") == true) {
253 deptime = now + rand() % 300; // Wait up to 5 minutes until traffic starts moving to prevent too many aircraft
254 // from cluttering the gate areas.
255 cerr << "Scheduling " << registration << " for instantaneous action flight " << endl;
260 deptime = (*flights.begin())->getDepartureTime();
261 FGScheduledFlightVecIterator i = flights.begin();
262 SG_LOG (SG_GENERAL, SG_DEBUG,"Traffic Manager: Processing registration " << registration << " with callsign " << (*i)->getCallSign());
265 // Check if this aircraft has been released.
266 FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("Traffic Manager");
267 if (tmgr->isReleased(AIManagerRef))
273 userLatitude = fgGetDouble("/position/latitude-deg");
274 userLongitude = fgGetDouble("/position/longitude-deg");
276 //cerr << "Estimated minimum distance to user: " << distanceToUser << endl;
277 // This flight entry is entirely in the past, do we need to
278 // push it forward in time to the next scheduled departure.
279 if (((*i)->getDepartureTime() < now) && ((*i)->getArrivalTime() < now))
281 SG_LOG (SG_GENERAL, SG_DEBUG, "Traffic Manager: Flight is in the Past");
282 //cerr << modelPath << " " << registration << ": Flights from the past belong to the past :-)" << endl;
284 // Don't just update: check whether we need to load a new leg. etc.
285 // This update occurs for distant aircraft, so we can update the current leg
286 // and detach it from the current list of aircraft.
288 i = flights.erase(i);
292 // Departure time in the past and arrival time in the future.
293 // This flight is in progress, so we need to calculate it's
294 // approximate position and -if in range- create an AIAircraft
296 //if ((i->getDepartureTime() < now) && (i->getArrivalTime() > now))
298 // Part of this flight is in the future.
299 if ((*i)->getArrivalTime() > now)
302 dep = (*i)->getDepartureAirport();
303 arr = (*i)->getArrivalAirport ();
307 SGVec3d a = SGVec3d::fromGeoc(SGGeoc::fromDegM(dep->getLongitude(),
308 dep->getLatitude(), 1));
309 SGVec3d b = SGVec3d::fromGeoc(SGGeoc::fromDegM(arr->getLongitude(),
310 arr->getLatitude(), 1));
311 SGVec3d _cross = cross(b, a);
313 angle = sgACos(dot(a, b));
315 // Okay, at this point we have the angle between departure and
316 // arrival airport, in degrees. From here we can interpolate the
317 // position of the aircraft by calculating the ratio between
318 // total time enroute and elapsed time enroute.
320 totalTimeEnroute = (*i)->getArrivalTime() - (*i)->getDepartureTime();
321 if (now > (*i)->getDepartureTime())
323 //err << "Lat = " << lat << ", lon = " << lon << endl;
324 //cerr << "Time diff: " << now-i->getDepartureTime() << endl;
325 elapsedTimeEnroute = now - (*i)->getDepartureTime();
326 remainingTimeEnroute = (*i)->getArrivalTime() - now;
327 SG_LOG (SG_GENERAL, SG_DEBUG, "Traffic Manager: Flight is in progress.");
331 lat = dep->getLatitude();
332 lon = dep->getLongitude();
333 elapsedTimeEnroute = 0;
334 remainingTimeEnroute = totalTimeEnroute;
335 SG_LOG (SG_GENERAL, SG_DEBUG, "Traffic Manager: Flight is pending.");
338 angle *= ( (double) elapsedTimeEnroute/ (double) totalTimeEnroute);
341 //cout << "a = " << a[0] << " " << a[1] << " " << a[2]
342 // << "b = " << b[0] << " " << b[1] << " " << b[2] << endl;
344 sgdMakeRotMat4(matrix, angle, _cross.sg());
345 SGVec3d newPos(0, 0, 0);
346 for(int j = 0; j < 3; j++)
348 for (int k = 0; k<3; k++)
350 newPos[j] += matrix[j][k]*a[k];
354 if (now > (*i)->getDepartureTime())
356 SGGeoc geoc = SGGeoc::fromCart(newPos);
357 lat = geoc.getLatitudeDeg();
358 lon = geoc.getLongitudeDeg();
362 lat = dep->getLatitude();
363 lon = dep->getLongitude();
367 SGWayPoint current (lon,
369 (*i)->getCruiseAlt(),
370 SGWayPoint::SPHERICAL);
371 SGWayPoint user ( userLongitude,
373 (*i)->getCruiseAlt(),
374 SGWayPoint::SPHERICAL);
375 SGWayPoint dest ( arr->getLongitude(),
377 (*i)->getCruiseAlt(),
378 SGWayPoint::SPHERICAL);
379 // We really only need distance to user
380 // and course to destination
381 user.CourseAndDistance(current, &courseToUser, &distanceToUser);
382 dest.CourseAndDistance(current, &courseToDest, &distanceToDest);
383 speed = (distanceToDest*SG_METER_TO_NM) /
384 ((double) remainingTimeEnroute/3600.0);
387 // If distance between user and simulated aircaft is less
388 // then 500nm, create this flight. At jet speeds 500 nm is roughly
389 // one hour flight time, so that would be a good approximate point
390 // to start a more detailed simulation of this aircraft.
391 SG_LOG (SG_GENERAL, SG_DEBUG, "Traffic manager: " << registration << " is scheduled for a flight from "
392 << dep->getId() << " to " << arr->getId() << ". Current distance to user: "
393 << distanceToUser*SG_METER_TO_NM);
394 if ((distanceToUser*SG_METER_TO_NM) < TRAFFICTOAIDISTTOSTART)
396 string flightPlanName = dep->getId() + string("-") + arr->getId() +
398 SG_LOG (SG_GENERAL, SG_DEBUG, "Traffic manager: Creating AIModel");
400 //if ((i->getDepartureTime() < now))
402 // alt = i->getCruiseAlt() *100;
406 // alt = dep->_elevation+19;
409 // Only allow traffic to be created when the model path (or the AI version of mp) exists
410 SGPath mp(globals->get_fg_root());
413 mp.append(modelPath);
415 mp_ai.append(modelPath);
417 if (mp.exists() || mp_ai.exists())
419 FGAIAircraft *aircraft = new FGAIAircraft(this);
420 aircraft->setPerformance(m_class); //"jet_transport";
421 aircraft->setCompany(airline); //i->getAirline();
422 aircraft->setAcType(acType); //i->getAcType();
423 aircraft->setPath(modelPath.c_str());
424 //aircraft->setFlightPlan(flightPlanName);
425 aircraft->setLatitude(lat);
426 aircraft->setLongitude(lon);
427 aircraft->setAltitude((*i)->getCruiseAlt()*100); // convert from FL to feet
428 aircraft->setSpeed(speed);
429 aircraft->setBank(0);
430 aircraft->SetFlightPlan(new FGAIFlightPlan(aircraft, flightPlanName, courseToDest, deptime,
431 dep, arr,true, radius,
432 (*i)->getCruiseAlt()*100,
433 lat, lon, speed, flightType, acType,
435 aimgr->attach(aircraft);
438 AIManagerRef = aircraft->getID();
439 //cerr << "Class: " << m_class << ". acType: " << acType << ". Airline: " << airline << ". Speed = " << speed << ". From " << dep->getId() << " to " << arr->getId() << ". Time Fraction = " << (remainingTimeEnroute/(double) totalTimeEnroute) << endl;
440 //cerr << "Latitude : " << lat << ". Longitude : " << lon << endl;
441 //cerr << "Dep : " << dep->getLatitude()<< ", "<< dep->getLongitude() << endl;
442 //cerr << "Arr : " << arr->getLatitude()<< ", "<< arr->getLongitude() << endl;
443 //cerr << "Time remaining = " << (remainingTimeEnroute/3600.0) << endl;
444 //cerr << "Total time = " << (totalTimeEnroute/3600.0) << endl;
445 //cerr << "Distance remaining = " << distanceToDest*SG_METER_TO_NM << endl;
449 SG_LOG(SG_INPUT, SG_WARN, "TrafficManager: Could not load model " << mp.str());
455 // Both departure and arrival time are in the future, so this
456 // the aircraft is parked at the departure airport.
457 // Currently this status is mostly ignored, but in future
458 // versions, code should go here that -if within user range-
459 // positions these aircraft at parking locations at the airport.
460 if (((*i)->getDepartureTime() > now) && ((*i)->getArrivalTime() > now))
462 dep = (*i)->getDepartureAirport();
466 //cerr << "Traffic schedule got to beyond last clause" << endl;
467 // EMH: prevent a warning, should this be 'true' instead?
468 // DT: YES. Originally, this code couldn't be reached, but
469 // when the "if(!(AIManagerManager))" clause is false we
470 // fall through right to the end. This is a valid flow.
471 // the actual value is pretty innocent, only it triggers
472 // warning in TrafficManager::update().
473 // (which was added as a sanity check for myself in the first place. :-)
478 bool FGAISchedule::next()
480 FGScheduledFlightVecIterator i = flights.begin();
482 //FIXME: remove first entry,
483 // load new flights until back at home airport
484 // Lock loaded flights
485 //sort(flights.begin(), flights.end(), compareScheduledFlights);
487 i = flights.erase(i);
488 //cerr << "Next: scheduling for : " << modelPath << " " << registration << endl;
489 FGScheduledFlight *flight = findAvailableFlight(currentDestination, flightIdentifier);
491 currentDestination = flight->getArrivalAirport()->getId();
493 dep = flight->getDepartureTime();
494 arr = flight->getArrivalTime();
495 string depT = asctime(gmtime(&dep));
496 string arrT = asctime(gmtime(&arr));
498 depT = depT.substr(0,24);
499 arrT = arrT.substr(0,24);
500 //cerr << " " << flight->getCallSign() << ":"
501 // << " " << flight->getDepartureAirport()->getId() << ":"
502 // << " " << depT << ":"
503 // << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
504 // << " " << arrT << ":" << endl;
506 flights.push_back(flight);
511 //cerr << "FGAISchedule :: next needs updating" << endl;
515 FGScheduledFlight* FGAISchedule::findAvailableFlight (const string ¤tDestination,
518 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
520 FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("Traffic Manager");
521 FGScheduledFlightVecIterator fltBegin, fltEnd;
522 fltBegin = tmgr->getFirstFlight(req);
523 fltEnd = tmgr->getLastFlight(req);
526 //cerr << "Finding available flight " << endl;
528 // Traverse every registered flight
529 if (fltBegin == fltEnd) {
530 //cerr << "No Flights Scheduled for " << req << endl;
533 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
534 (*i)->adjustTime(now);
535 //sort(fltBegin, fltEnd, compareScheduledFlights);
536 //cerr << counter++ << endl;
538 sort(fltBegin, fltEnd, compareScheduledFlights);
539 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
542 if (!(*i)->isAvailable()) {
543 //cerr << (*i)->getCallSign() << "is no longer available" << endl;
546 if (!((*i)->getRequirement() == req)) {
549 if (!(((*i)->getArrivalAirport()) && ((*i)->getDepartureAirport()))) {
552 if (!(currentDestination.empty())) {
553 if (currentDestination != (*i)->getDepartureAirport()->getId()) {
554 //cerr << (*i)->getCallSign() << "Doesn't match destination" << endl;
555 //cerr << "Current Destination " << currentDestination << "Doesnt match flight's " <<
556 // (*i)->getArrivalAirport()->getId() << endl;
561 // So, if we actually get here, we have a winner
562 //cerr << "found flight: " << req << " : " << currentDestination << " : " <<
563 // (*i)->getArrivalAirport()->getId() << endl;
568 // if currentDestination has a value, does it match departure of next flight?
569 // is departure time later than planned arrival?
570 // is departure port valid?
571 // is arrival port valid?
572 //cerr << "Ack no flight found: " << endl;
576 double FGAISchedule::getSpeed()
578 FGScheduledFlightVecIterator i = flights.begin();
580 FGAirport* dep = (*i)->getDepartureAirport(),
581 *arr = (*i)->getArrivalAirport();
582 double dist = SGGeodesy::distanceNm(dep->geod(), arr->geod());
583 double remainingTimeEnroute = (*i)->getArrivalTime() - (*i)->getDepartureTime();
585 double speed = dist / (remainingTimeEnroute/3600.0);
586 SG_CLAMP_RANGE(speed, 300.0, 500.0);
590 bool compareSchedules(FGAISchedule*a, FGAISchedule*b)
592 //return (*a) < (*b);
596 // void FGAISchedule::setClosestDistanceToUser()
606 // elapsedTimeEnroute;
608 // double userLatitude = fgGetDouble("/position/latitude-deg");
609 // double userLongitude = fgGetDouble("/position/longitude-deg");
613 // #if defined( __CYGWIN__) || defined( __MINGW32__)
614 // #define HUGE HUGE_VAL
616 // distanceToUser = HUGE;
617 // FGScheduledFlightVecIterator i = flights.begin();
618 // while (i != flights.end())
620 // dep = i->getDepartureAirport();
624 // SGWayPoint user ( userLongitude,
626 // i->getCruiseAlt());
627 // SGWayPoint current (dep->getLongitude(),
628 // dep->getLatitude(),
630 // user.CourseAndDistance(current, &course, &dist);
631 // if (dist < distanceToUser)
633 // distanceToUser = dist;
634 // //cerr << "Found closest distance to user for " << registration << " to be " << distanceToUser << " at airport " << dep->getId() << endl;
638 // //return distToUser;