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)
203 remainingTimeEnroute, deptime = 0;
208 if (fgGetBool("/sim/traffic-manager/enabled") == false)
211 aimgr = (FGAIManager *) globals-> get_subsystem("ai_model");
212 // Out-of-work aircraft seeks employment. Willing to work irregular hours ...
213 //cerr << "About to find a flight " << endl;
214 if (flights.empty()) {
215 //execute this loop at least once.
216 SG_LOG(SG_GENERAL, SG_BULK, "Scheduling for : " << modelPath << " " << registration << " " << homePort);
217 FGScheduledFlight *flight = 0;
219 flight = findAvailableFlight(currentDestination, flightIdentifier);
221 currentDestination = flight->getArrivalAirport()->getId();
223 dep = flight->getDepartureTime();
224 arr = flight->getArrivalTime();
225 string depT = asctime(gmtime(&dep));
226 string arrT = asctime(gmtime(&arr));
228 depT = depT.substr(0,24);
229 arrT = arrT.substr(0,24);
230 SG_LOG(SG_GENERAL, SG_BULK, " " << flight->getCallSign() << ":"
231 << " " << flight->getDepartureAirport()->getId() << ":"
232 << " " << depT << ":"
233 << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
234 << " " << arrT << ":");
235 flights.push_back(flight);
237 } while ((currentDestination != homePort) && (flight != 0));
238 SG_LOG(SG_GENERAL, SG_BULK, cerr << " Done " << endl);
240 //cerr << " Done " << endl;
241 // No flights available for this aircraft
242 if (flights.size() == 0) {
245 // Sort all the scheduled flights according to scheduled departure time.
246 // Because this is done at every update, we only need to check the status
247 // of the first listed flight.
248 //sort(flights.begin(), flights.end(), compareScheduledFlights);
250 if (fgGetBool("/sim/traffic-manager/instantaneous-action") == true) {
251 deptime = now + rand() % 300; // Wait up to 5 minutes until traffic starts moving to prevent too many aircraft
252 // from cluttering the gate areas.
253 cerr << "Scheduling " << registration << " for instantaneous action flight " << endl;
258 deptime = (*flights.begin())->getDepartureTime();
259 FGScheduledFlightVecIterator i = flights.begin();
260 SG_LOG (SG_GENERAL, SG_DEBUG,"Traffic Manager: Processing registration " << registration << " with callsign " << (*i)->getCallSign());
263 // Check if this aircraft has been released.
264 FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("Traffic Manager");
265 if (tmgr->isReleased(AIManagerRef))
271 userLatitude = fgGetDouble("/position/latitude-deg");
272 userLongitude = fgGetDouble("/position/longitude-deg");
274 //cerr << "Estimated minimum distance to user: " << distanceToUser << endl;
275 // This flight entry is entirely in the past, do we need to
276 // push it forward in time to the next scheduled departure.
277 if (((*i)->getDepartureTime() < now) && ((*i)->getArrivalTime() < now))
279 SG_LOG (SG_GENERAL, SG_DEBUG, "Traffic Manager: Flight is in the Past");
280 //cerr << modelPath << " " << registration << ": Flights from the past belong to the past :-)" << endl;
282 // Don't just update: check whether we need to load a new leg. etc.
283 // This update occurs for distant aircraft, so we can update the current leg
284 // and detach it from the current list of aircraft.
286 i = flights.erase(i);
290 // Departure time in the past and arrival time in the future.
291 // This flight is in progress, so we need to calculate it's
292 // approximate position and -if in range- create an AIAircraft
294 //if ((i->getDepartureTime() < now) && (i->getArrivalTime() > now))
296 // Part of this flight is in the future.
297 if ((*i)->getArrivalTime() > now)
300 dep = (*i)->getDepartureAirport();
301 arr = (*i)->getArrivalAirport ();
305 SGVec3d a = SGVec3d::fromGeoc(SGGeoc::fromDegM(dep->getLongitude(),
306 dep->getLatitude(), 1));
307 SGVec3d b = SGVec3d::fromGeoc(SGGeoc::fromDegM(arr->getLongitude(),
308 arr->getLatitude(), 1));
309 SGVec3d _cross = cross(b, a);
311 angle = sgACos(dot(a, b));
313 // Okay, at this point we have the angle between departure and
314 // arrival airport, in degrees. From here we can interpolate the
315 // position of the aircraft by calculating the ratio between
316 // total time enroute and elapsed time enroute.
318 totalTimeEnroute = (*i)->getArrivalTime() - (*i)->getDepartureTime();
319 if (now > (*i)->getDepartureTime())
321 //err << "Lat = " << lat << ", lon = " << lon << endl;
322 //cerr << "Time diff: " << now-i->getDepartureTime() << endl;
323 elapsedTimeEnroute = now - (*i)->getDepartureTime();
324 remainingTimeEnroute = (*i)->getArrivalTime() - now;
325 SG_LOG (SG_GENERAL, SG_DEBUG, "Traffic Manager: Flight is in progress.");
329 lat = dep->getLatitude();
330 lon = dep->getLongitude();
331 elapsedTimeEnroute = 0;
332 remainingTimeEnroute = totalTimeEnroute;
333 SG_LOG (SG_GENERAL, SG_DEBUG, "Traffic Manager: Flight is pending.");
336 angle *= ( (double) elapsedTimeEnroute/ (double) totalTimeEnroute);
339 //cout << "a = " << a[0] << " " << a[1] << " " << a[2]
340 // << "b = " << b[0] << " " << b[1] << " " << b[2] << endl;
342 sgdMakeRotMat4(matrix, angle, _cross.data());
343 SGVec3d newPos(0, 0, 0);
344 for(int j = 0; j < 3; j++)
346 for (int k = 0; k<3; k++)
348 newPos[j] += matrix[j][k]*a[k];
353 if (now > (*i)->getDepartureTime())
355 current = SGGeod::fromCart(newPos);
359 current = dep->geod();
362 SGGeod user = SGGeod::fromDegM(userLongitude, userLatitude, (*i)->getCruiseAlt());
363 speed = SGGeodesy::distanceNm(current, arr->geod()) /
364 ((double) remainingTimeEnroute/3600.0);
366 distanceToUser = SGGeodesy::distanceNm(current, user);
368 // If distance between user and simulated aircaft is less
369 // then 500nm, create this flight. At jet speeds 500 nm is roughly
370 // one hour flight time, so that would be a good approximate point
371 // to start a more detailed simulation of this aircraft.
372 SG_LOG (SG_GENERAL, SG_DEBUG, "Traffic manager: " << registration << " is scheduled for a flight from "
373 << dep->getId() << " to " << arr->getId() << ". Current distance to user: "
375 if (distanceToUser < TRAFFICTOAIDISTTOSTART)
377 string flightPlanName = dep->getId() + string("-") + arr->getId() +
379 SG_LOG (SG_GENERAL, SG_DEBUG, "Traffic manager: Creating AIModel");
381 //if ((i->getDepartureTime() < now))
383 // alt = i->getCruiseAlt() *100;
387 // alt = dep->_elevation+19;
390 // Only allow traffic to be created when the model path (or the AI version of mp) exists
391 SGPath mp(globals->get_fg_root());
394 mp.append(modelPath);
396 mp_ai.append(modelPath);
398 if (mp.exists() || mp_ai.exists())
400 FGAIAircraft *aircraft = new FGAIAircraft(this);
401 aircraft->setPerformance(m_class); //"jet_transport";
402 aircraft->setCompany(airline); //i->getAirline();
403 aircraft->setAcType(acType); //i->getAcType();
404 aircraft->setPath(modelPath.c_str());
405 //aircraft->setFlightPlan(flightPlanName);
406 aircraft->setLatitude(lat);
407 aircraft->setLongitude(lon);
408 aircraft->setAltitude((*i)->getCruiseAlt()*100); // convert from FL to feet
409 aircraft->setSpeed(speed);
410 aircraft->setBank(0);
412 courseToDest = SGGeodesy::courseDeg(current, arr->geod());
413 aircraft->SetFlightPlan(new FGAIFlightPlan(aircraft, flightPlanName, courseToDest, deptime,
414 dep, arr,true, radius,
415 (*i)->getCruiseAlt()*100,
416 lat, lon, speed, flightType, acType,
418 aimgr->attach(aircraft);
421 AIManagerRef = aircraft->getID();
422 //cerr << "Class: " << m_class << ". acType: " << acType << ". Airline: " << airline << ". Speed = " << speed << ". From " << dep->getId() << " to " << arr->getId() << ". Time Fraction = " << (remainingTimeEnroute/(double) totalTimeEnroute) << endl;
423 //cerr << "Latitude : " << lat << ". Longitude : " << lon << endl;
424 //cerr << "Dep : " << dep->getLatitude()<< ", "<< dep->getLongitude() << endl;
425 //cerr << "Arr : " << arr->getLatitude()<< ", "<< arr->getLongitude() << endl;
426 //cerr << "Time remaining = " << (remainingTimeEnroute/3600.0) << endl;
427 //cerr << "Total time = " << (totalTimeEnroute/3600.0) << endl;
428 //cerr << "Distance remaining = " << distanceToDest*SG_METER_TO_NM << endl;
432 SG_LOG(SG_INPUT, SG_WARN, "TrafficManager: Could not load model " << mp.str());
438 // Both departure and arrival time are in the future, so this
439 // the aircraft is parked at the departure airport.
440 // Currently this status is mostly ignored, but in future
441 // versions, code should go here that -if within user range-
442 // positions these aircraft at parking locations at the airport.
443 if (((*i)->getDepartureTime() > now) && ((*i)->getArrivalTime() > now))
445 dep = (*i)->getDepartureAirport();
449 //cerr << "Traffic schedule got to beyond last clause" << endl;
450 // EMH: prevent a warning, should this be 'true' instead?
451 // DT: YES. Originally, this code couldn't be reached, but
452 // when the "if(!(AIManagerManager))" clause is false we
453 // fall through right to the end. This is a valid flow.
454 // the actual value is pretty innocent, only it triggers
455 // warning in TrafficManager::update().
456 // (which was added as a sanity check for myself in the first place. :-)
461 bool FGAISchedule::next()
463 FGScheduledFlightVecIterator i = flights.begin();
465 //FIXME: remove first entry,
466 // load new flights until back at home airport
467 // Lock loaded flights
468 //sort(flights.begin(), flights.end(), compareScheduledFlights);
470 i = flights.erase(i);
471 //cerr << "Next: scheduling for : " << modelPath << " " << registration << endl;
472 FGScheduledFlight *flight = findAvailableFlight(currentDestination, flightIdentifier);
474 currentDestination = flight->getArrivalAirport()->getId();
476 dep = flight->getDepartureTime();
477 arr = flight->getArrivalTime();
478 string depT = asctime(gmtime(&dep));
479 string arrT = asctime(gmtime(&arr));
481 depT = depT.substr(0,24);
482 arrT = arrT.substr(0,24);
483 //cerr << " " << flight->getCallSign() << ":"
484 // << " " << flight->getDepartureAirport()->getId() << ":"
485 // << " " << depT << ":"
486 // << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
487 // << " " << arrT << ":" << endl;
489 flights.push_back(flight);
494 //cerr << "FGAISchedule :: next needs updating" << endl;
498 FGScheduledFlight* FGAISchedule::findAvailableFlight (const string ¤tDestination,
501 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
503 FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("Traffic Manager");
504 FGScheduledFlightVecIterator fltBegin, fltEnd;
505 fltBegin = tmgr->getFirstFlight(req);
506 fltEnd = tmgr->getLastFlight(req);
509 //cerr << "Finding available flight " << endl;
511 // Traverse every registered flight
512 if (fltBegin == fltEnd) {
513 //cerr << "No Flights Scheduled for " << req << endl;
516 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
517 (*i)->adjustTime(now);
518 //sort(fltBegin, fltEnd, compareScheduledFlights);
519 //cerr << counter++ << endl;
521 sort(fltBegin, fltEnd, compareScheduledFlights);
522 for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
525 if (!(*i)->isAvailable()) {
526 //cerr << (*i)->getCallSign() << "is no longer available" << endl;
529 if (!((*i)->getRequirement() == req)) {
532 if (!(((*i)->getArrivalAirport()) && ((*i)->getDepartureAirport()))) {
535 if (!(currentDestination.empty())) {
536 if (currentDestination != (*i)->getDepartureAirport()->getId()) {
537 //cerr << (*i)->getCallSign() << "Doesn't match destination" << endl;
538 //cerr << "Current Destination " << currentDestination << "Doesnt match flight's " <<
539 // (*i)->getArrivalAirport()->getId() << endl;
544 // So, if we actually get here, we have a winner
545 //cerr << "found flight: " << req << " : " << currentDestination << " : " <<
546 // (*i)->getArrivalAirport()->getId() << endl;
551 // if currentDestination has a value, does it match departure of next flight?
552 // is departure time later than planned arrival?
553 // is departure port valid?
554 // is arrival port valid?
555 //cerr << "Ack no flight found: " << endl;
559 double FGAISchedule::getSpeed()
561 FGScheduledFlightVecIterator i = flights.begin();
563 FGAirport* dep = (*i)->getDepartureAirport(),
564 *arr = (*i)->getArrivalAirport();
565 double dist = SGGeodesy::distanceNm(dep->geod(), arr->geod());
566 double remainingTimeEnroute = (*i)->getArrivalTime() - (*i)->getDepartureTime();
568 double speed = dist / (remainingTimeEnroute/3600.0);
569 SG_CLAMP_RANGE(speed, 300.0, 500.0);
573 bool compareSchedules(FGAISchedule*a, FGAISchedule*b)
575 //return (*a) < (*b);
579 // void FGAISchedule::setClosestDistanceToUser()
589 // elapsedTimeEnroute;
591 // double userLatitude = fgGetDouble("/position/latitude-deg");
592 // double userLongitude = fgGetDouble("/position/longitude-deg");
596 // #if defined( __CYGWIN__) || defined( __MINGW32__)
597 // #define HUGE HUGE_VAL
599 // distanceToUser = HUGE;
600 // FGScheduledFlightVecIterator i = flights.begin();
601 // while (i != flights.end())
603 // dep = i->getDepartureAirport();
607 // SGWayPoint user ( userLongitude,
609 // i->getCruiseAlt());
610 // SGWayPoint current (dep->getLongitude(),
611 // dep->getLatitude(),
613 // user.CourseAndDistance(current, &course, &dist);
614 // if (dist < distanceToUser)
616 // distanceToUser = dist;
617 // //cerr << "Found closest distance to user for " << registration << " to be " << distanceToUser << " at airport " << dep->getId() << endl;
621 // //return distToUser;