]> git.mxchange.org Git - flightgear.git/blob - src/Traffic/Schedule.cxx
Performance optimization: empty() instead of size()>0
[flightgear.git] / src / Traffic / Schedule.cxx
1 /******************************************************************************
2  * Schedule.cxx
3  * Written by Durk Talsma, started May 5, 2004.
4  *
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.
9  *
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.
14  *
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.
18  *
19  *
20  ****************************************************************************
21  *
22  *****************************************************************************/
23
24 #ifdef HAVE_CONFIG_H
25 #  include "config.h"
26 #endif
27
28 #define BOGUS 0xFFFF
29
30 #include <stdlib.h>
31 #include <time.h>
32 #include <iostream>
33 #include <fstream>
34
35
36 #include <string>
37 #include <vector>
38 #include <algorithm>
39
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>
46
47 #include <AIModel/AIFlightPlan.hxx>
48 #include <AIModel/AIManager.hxx>
49 #include <AIModel/AIAircraft.hxx>
50 #include <Airports/airport.hxx>
51 #include <Main/fg_init.hxx>   // That's pretty ugly, but I need fgFindAirportID
52
53
54 #include "SchedFlight.hxx"
55 #include "TrafficMgr.hxx"
56
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()
62   : heavy(false),
63     radius(0),
64     groundOffset(0),
65     distanceToUser(0),
66     score(0),
67     runCount(0),
68     hits(0),
69     lastRun(0),
70     firstRun(false),
71     courseToDest(0),
72     initialized(false),
73     valid(false),
74     scheduleComplete(false)
75 {
76 }
77
78
79 FGAISchedule::FGAISchedule(const string& model,
80                            const string& lvry,
81                            const string& port,
82                            const string& reg,
83                            const string& flightId,
84                            bool   hvy, 
85                            const string& act,
86                            const string& arln,
87                            const string& mclass,
88                            const string& fltpe,
89                            double rad, 
90                            double grnd)
91     : heavy(hvy),
92       radius(rad),
93       groundOffset(grnd),
94       distanceToUser(0),
95       score(0),
96       runCount(0),
97       hits(0),
98       lastRun(0),
99       firstRun(true),
100       courseToDest(0),
101       initialized(false),
102       valid(true),
103       scheduleComplete(false)
104 {
105   modelPath        = model; 
106   livery           = lvry; 
107   homePort         = port;
108   registration     = reg;
109   flightIdentifier = flightId;
110   acType           = act;
111   airline          = arln;
112   m_class          = mclass;
113   flightType       = fltpe;
114   /*for (FGScheduledFlightVecIterator i = flt.begin();
115        i != flt.end();
116        i++)
117     flights.push_back(new FGScheduledFlight((*(*i))));*/
118 }
119
120 FGAISchedule::FGAISchedule(const FGAISchedule &other)
121 {
122   modelPath          = other.modelPath;
123   homePort           = other.homePort;
124   livery             = other.livery;
125   registration       = other.registration;
126   heavy              = other.heavy;
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;
137   score              = other.score;
138   distanceToUser     = other.distanceToUser;
139   currentDestination = other.currentDestination;
140   firstRun           = other.firstRun;
141   runCount           = other.runCount;
142   hits               = other.hits;
143   lastRun            = other.lastRun;
144   courseToDest       = other.courseToDest;
145   initialized        = other.initialized;
146   valid              = other.valid;
147   scheduleComplete   = other.scheduleComplete;
148 }
149
150
151
152 FGAISchedule::~FGAISchedule()
153 {
154     // remove related object from AI manager
155     if (aiAircraft)
156     {
157       aiAircraft->setDie(true);
158     }
159
160 /*  for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
161     {
162       delete (*flt);
163     }
164   flights.clear();*/
165
166
167 bool FGAISchedule::init()
168 {
169   //tm targetTimeDate;
170   //SGTime* currTimeDate = globals->get_time_params();
171
172   //tm *temp = currTimeDate->getGmt();
173   //char buffer[512];
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(); 
178        i != flights.end(); 
179        i++)
180     {
181       //i->adjustTime(now);
182       if (!((*i)->initializeAirports()))
183         return false;
184     } */
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();
190   return true;
191 }
192
193 /**
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).
197  */
198 bool FGAISchedule::update(time_t now, const SGVec3d& userCart)
199 {
200
201   time_t totalTimeEnroute,
202          elapsedTimeEnroute,
203          //remainingTimeEnroute,
204          deptime = 0;
205
206   if (!valid) {
207     return true; // processing complete
208   }
209
210   if (!scheduleComplete) {
211       scheduleComplete = scheduleFlights(now);
212   }
213
214   if (!scheduleComplete) {
215       return false; // not ready yet, continue processing in next iteration
216   }
217
218   if (flights.empty()) { // No flights available for this aircraft
219       valid = false;
220       return true; // processing complete
221   }
222
223
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);
228   
229   if (firstRun) {
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.
233      }
234      firstRun = false;
235   }
236   
237   FGScheduledFlight* flight = flights.front();
238   if (!deptime) {
239     deptime = flight->getDepartureTime();
240     //cerr << "Setting departure time " << deptime << endl;
241   }
242     
243   if (aiAircraft) {
244     if (aiAircraft->getDie()) {
245       aiAircraft = NULL;
246     } else {
247       return true; // in visual range, let the AIManager handle it
248     }
249   }
250   
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. 
258     flight->update();
259     flights.erase(flights.begin()); // pop_front(), effectively
260     return true; // processing complete
261   }
262   
263   FGAirport* dep = flight->getDepartureAirport();
264   FGAirport* arr = flight->getArrivalAirport();
265   if (!dep || !arr) {
266     return true; // processing complete
267   }
268     
269   double speed = 450.0;
270   if (dep != arr) {
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;
276       
277     // current pos is based on great-circle course between departure/arrival,
278     // with percentage of distance travelled, based upon percentage of time
279     // enroute elapsed.
280       double course, az2, distanceM;
281       SGGeodesy::inverse(dep->geod(), arr->geod(), course, az2, distanceM);
282       double coveredDistance = distanceM * x;
283       
284       SGGeodesy::direct(dep->geod(), course, coveredDistance, position, az2);
285       
286       SG_LOG (SG_AI, SG_BULK, "Traffic Manager:      Flight is in progress, %=" << x);
287       speed = ((distanceM - coveredDistance) * SG_METER_TO_NM) / 3600.0;
288     } else {
289     // not departed yet
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 ");
295     }
296   } else {
297     // departure / arrival coincident
298     //remainingTimeEnroute = totalTimeEnroute = 0.0;
299     elapsedTimeEnroute = 0;
300     position = dep->geod();
301   }
302     
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;
306
307
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: " 
314              << distanceToUser);
315   if (distanceToUser >= TRAFFICTOAIDISTTOSTART) {
316     return true; // out of visual range, for the moment.
317   }
318
319   if (!createAIAircraft(flight, speed, deptime)) {
320       valid = false;
321   }
322
323
324     return true; // processing complete
325 }
326
327 bool FGAISchedule::validModelPath(const std::string& modelPath)
328 {
329     SGPath mp(globals->get_fg_root());
330     SGPath mp_ai = mp;
331
332     mp.append(modelPath);
333     mp_ai.append("AI");
334     mp_ai.append(modelPath);
335
336     return mp.exists() || mp_ai.exists();
337 }
338
339 bool FGAISchedule::createAIAircraft(FGScheduledFlight* flight, double speedKnots, time_t deptime)
340 {
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);
345
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());
348   SGPath mp_ai = mp;
349
350   mp.append(modelPath);
351   mp_ai.append("AI");
352   mp_ai.append(modelPath);
353
354   if (!mp.exists() && !mp_ai.exists()) {
355     SG_LOG(SG_AI, SG_WARN, "TrafficManager: Could not load model " << mp_ai.str());
356     return true;
357   }
358
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);
370       
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, 
378                                             airline);
379   if (fp->isValidPlan()) {
380         aiAircraft->SetFlightPlan(fp);
381         FGAIManager* aimgr = (FGAIManager *) globals-> get_subsystem("ai-model");
382         aimgr->attach(aiAircraft);
383         return true;
384   } else {
385         aiAircraft = NULL;
386         delete fp;
387         //hand back the flights that had already been scheduled
388         while (!flights.empty()) {
389             flights.front()->release();
390             flights.erase(flights.begin());
391         }
392         return false;
393   }
394 }
395
396 // Create an initial heading for user controlled aircraft.
397 void FGAISchedule::setHeading()  
398
399     courseToDest = SGGeodesy::courseDeg((*flights.begin())->getDepartureAirport()->geod(), (*flights.begin())->getArrivalAirport()->geod());
400 }
401
402 bool FGAISchedule::scheduleFlights(time_t now)
403 {
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;
408   SGTimeStamp start;
409   start.stamp();
410
411   bool first = true;
412   if (currentDestination.empty())
413     flight = findAvailableFlight(userPort, flightIdentifier, now, (now+6400));
414
415   do {
416     if ((!flight)||(!first)) {
417         flight = findAvailableFlight(currentDestination, flightIdentifier);
418     }
419     if (!flight) {
420       break;
421     }
422
423     first = false;
424     currentDestination = flight->getArrivalAirport()->getId();
425     //cerr << "Current destination " <<  currentDestination << endl;
426     if (!initialized) {
427         const string& departurePort = flight->getDepartureAirport()->getId();
428         if (userPort == departurePort) {
429             lastRun = 1;
430             hits++;
431         } else {
432             lastRun = 0;
433         }
434         //runCount++;
435         initialized = true;
436     }
437   
438     if (sglog().would_log(SG_AI, SG_BULK))
439     {
440         time_t arr, dep;
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 << ":");
452     }
453   
454     flights.push_back(flight);
455
456     // continue processing until complete, or preempt after timeout
457   } while ((currentDestination != homePort)&&
458            (start.elapsedMSec()<3.0));
459
460   if (flight && (currentDestination != homePort))
461   {
462       // processing preempted, need to continue in next iteration
463       return false;
464   }
465
466   SG_LOG(SG_AI, SG_BULK, " Done ");
467   return true;
468 }
469
470 bool FGAISchedule::next()
471 {
472   if (!flights.empty()) {
473     flights.front()->release();
474     flights.erase(flights.begin());
475   }
476   
477   FGScheduledFlight *flight = findAvailableFlight(currentDestination, flightIdentifier);
478   if (!flight) {
479     return false;
480   }
481   
482   currentDestination = flight->getArrivalAirport()->getId();
483 /*
484   time_t arr, dep;
485   dep = flight->getDepartureTime();
486   arr = flight->getArrivalTime();
487   string depT = asctime(gmtime(&dep));
488   string arrT = asctime(gmtime(&arr));
489
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;
497 */
498    flights.push_back(flight);
499    return true;
500 }
501
502 FGScheduledFlight* FGAISchedule::findAvailableFlight (const string &currentDestination,
503                                                       const string &req,
504                                                      time_t min, time_t max)
505 {
506     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
507
508     FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("traffic-manager");
509     FGScheduledFlightVecIterator fltBegin, fltEnd;
510     fltBegin = tmgr->getFirstFlight(req);
511     fltEnd   = tmgr->getLastFlight(req);
512
513
514      //cerr << "Finding available flight " << endl;
515      // For Now:
516      // Traverse every registered flight
517      if (fltBegin == fltEnd) {
518           //cerr << "No Flights Scheduled for " << req << endl;
519      }
520      int counter = 0;
521      for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
522           (*i)->adjustTime(now);
523            //sort(fltBegin, fltEnd, compareScheduledFlights);
524            //cerr << counter++ << endl;
525      }
526      std::sort(fltBegin, fltEnd, compareScheduledFlights);
527      for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
528           //bool valid = true;
529           counter++;
530           if (!(*i)->isAvailable()) {
531                //cerr << (*i)->getCallSign() << "is no longer available" << endl;
532                continue;
533           }
534           if (!((*i)->getRequirement() == req)) {
535                continue;
536           }
537           if (!(((*i)->getArrivalAirport()) && ((*i)->getDepartureAirport()))) {
538               continue;
539           }
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;
545                    continue;
546               }
547           }
548           if (! flights.empty()) {
549             time_t arrival = flights.back()->getArrivalTime();
550             int groundTime = groundTimeFromRadius();
551             if ((*i)->getDepartureTime() < (arrival+(groundTime)))
552                 continue;
553           }
554           if (min != 0) {
555               time_t dep = (*i)->getDepartureTime();
556               if ((dep < min) || (dep > max))
557                   continue;
558           }
559
560           // So, if we actually get here, we have a winner
561           //cerr << "found flight: " << req << " : " << currentDestination << " : " <<       
562           //         (*i)->getArrivalAirport()->getId() << endl;
563           (*i)->lock();
564           return (*i);
565      }
566      // matches req?
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;
572      return NULL;
573 }
574
575 int FGAISchedule::groundTimeFromRadius()
576 {
577     if (radius < 10) 
578         return 15 * 60;
579     else if (radius < 15)
580         return 20 * 60;
581     else if (radius < 20)
582         return 30 * 60;
583     else if (radius < 25)
584         return 50 * 60;
585     else if (radius < 30)
586         return 90 * 60;
587     else 
588         return 120 * 60;
589 }
590
591
592 double FGAISchedule::getSpeed()
593 {
594   FGScheduledFlightVecIterator i = flights.begin();
595  
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();
600
601   double speed = dist / (remainingTimeEnroute/3600.0);
602   SG_CLAMP_RANGE(speed, 300.0, 500.0);
603   return speed;
604 }
605
606 void FGAISchedule::setScore   () 
607
608     if (runCount) {
609         score = ((double) hits / (double) runCount);
610     } else {
611         if (homePort == fgGetString("/sim/presets/airport-id")) {
612             score = 0.1;
613         } else {
614             score = 0.0;
615         }
616     }
617     runCount++;
618 }
619
620 bool compareSchedules(FGAISchedule*a, FGAISchedule*b)
621
622   return (*a) < (*b); 
623
624
625 bool FGAISchedule::operator< (const FGAISchedule &other) const
626
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;
631 }
632