]> git.mxchange.org Git - flightgear.git/blob - src/Traffic/Schedule.cxx
AIFlihtPlan: Proper member initialization
[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/simple.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 {
75 }
76
77
78 FGAISchedule::FGAISchedule(const string& model,
79                            const string& lvry,
80                            const string& port,
81                            const string& reg,
82                            const string& flightId,
83                            bool   hvy, 
84                            const string& act,
85                            const string& arln,
86                            const string& mclass,
87                            const string& fltpe,
88                            double rad, 
89                            double grnd)
90     : heavy(hvy),
91       radius(rad),
92       groundOffset(grnd),
93       distanceToUser(0),
94       score(0),
95       runCount(0),
96       hits(0),
97       lastRun(0),
98       firstRun(true),
99       courseToDest(0),
100       initialized(false),
101       valid(true)
102 {
103   modelPath        = model; 
104   livery           = lvry; 
105   homePort         = port;
106   registration     = reg;
107   flightIdentifier = flightId;
108   acType           = act;
109   airline          = arln;
110   m_class          = mclass;
111   flightType       = fltpe;
112   /*for (FGScheduledFlightVecIterator i = flt.begin();
113        i != flt.end();
114        i++)
115     flights.push_back(new FGScheduledFlight((*(*i))));*/
116 }
117
118 FGAISchedule::FGAISchedule(const FGAISchedule &other)
119 {
120   modelPath          = other.modelPath;
121   homePort           = other.homePort;
122   livery             = other.livery;
123   registration       = other.registration;
124   heavy              = other.heavy;
125   flightIdentifier   = other.flightIdentifier;
126   flights            = other.flights;
127   aiAircraft         = other.aiAircraft;
128   acType             = other.acType;
129   airline            = other.airline;
130   m_class            = other.m_class;
131   firstRun           = other.firstRun;
132   radius             = other.radius;
133   groundOffset       = other.groundOffset;
134   flightType         = other.flightType;
135   score              = other.score;
136   distanceToUser     = other.distanceToUser;
137   currentDestination = other.currentDestination;
138   firstRun           = other.firstRun;
139   runCount           = other.runCount;
140   hits               = other.hits;
141   lastRun            = other.lastRun;
142   initialized        = other.initialized;
143   valid              = other.valid;
144 }
145
146
147
148 FGAISchedule::~FGAISchedule()
149 {
150     // remove related object from AI manager
151     if (aiAircraft)
152     {
153       aiAircraft->setDie(true);
154     }
155
156 /*  for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
157     {
158       delete (*flt);
159     }
160   flights.clear();*/
161
162
163 bool FGAISchedule::init()
164 {
165   //tm targetTimeDate;
166   //SGTime* currTimeDate = globals->get_time_params();
167
168   //tm *temp = currTimeDate->getGmt();
169   //char buffer[512];
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(); 
174        i != flights.end(); 
175        i++)
176     {
177       //i->adjustTime(now);
178       if (!((*i)->initializeAirports()))
179         return false;
180     } */
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();
186   return true;
187 }
188
189 bool FGAISchedule::update(time_t now, const SGVec3d& userCart)
190
191   time_t 
192     totalTimeEnroute, 
193     elapsedTimeEnroute,
194     //remainingTimeEnroute,
195     deptime = 0;
196   if (!valid) {
197     return false;
198   }
199   scheduleFlights(now);
200   if (flights.empty()) { // No flights available for this aircraft
201       valid = false;
202       return false;
203   }
204   
205   // Sort all the scheduled flights according to scheduled departure time.
206   // Because this is done at every update, we only need to check the status
207   // of the first listed flight. 
208   //sort(flights.begin(), flights.end(), compareScheduledFlights);
209   
210   if (firstRun) {
211      if (fgGetBool("/sim/traffic-manager/instantaneous-action") == true) {
212          deptime = now; // + rand() % 300; // Wait up to 5 minutes until traffic starts moving to prevent too many aircraft 
213                                    // from cluttering the gate areas.
214      }
215      firstRun = false;
216   }
217   
218   FGScheduledFlight* flight = flights.front();
219   if (!deptime) {
220     deptime = flight->getDepartureTime();
221     //cerr << "Setting departure time " << deptime << endl;
222   }
223     
224   if (aiAircraft) {
225     if (aiAircraft->getDie()) {
226       aiAircraft = NULL;
227     } else {
228       return true; // in visual range, let the AIManager handle it
229     }
230   }
231   
232   // This flight entry is entirely in the past, do we need to 
233   // push it forward in time to the next scheduled departure. 
234   if (flight->getArrivalTime() < now) {
235     SG_LOG (SG_AI, SG_BULK, "Traffic Manager:      Flight is in the Past");
236     // Don't just update: check whether we need to load a new leg. etc.
237     // This update occurs for distant aircraft, so we can update the current leg
238     // and detach it from the current list of aircraft. 
239     flight->update();
240     flights.erase(flights.begin()); // pop_front(), effectively
241     return true;
242   }
243   
244   FGAirport* dep = flight->getDepartureAirport();
245   FGAirport* arr = flight->getArrivalAirport();
246   if (!dep || !arr) {
247     return false;
248   }
249     
250   double speed = 450.0;
251   if (dep != arr) {
252     totalTimeEnroute = flight->getArrivalTime() - flight->getDepartureTime();
253     if (flight->getDepartureTime() < now) {
254       elapsedTimeEnroute   = now - flight->getDepartureTime();
255       //remainingTimeEnroute = totalTimeEnroute - elapsedTimeEnroute;
256       double x = elapsedTimeEnroute / (double) totalTimeEnroute;
257       
258     // current pos is based on great-circle course between departure/arrival,
259     // with percentage of distance travelled, based upon percentage of time
260     // enroute elapsed.
261       double course, az2, distanceM;
262       SGGeodesy::inverse(dep->geod(), arr->geod(), course, az2, distanceM);
263       double coveredDistance = distanceM * x;
264       
265       SGGeodesy::direct(dep->geod(), course, coveredDistance, position, az2);
266       
267       SG_LOG (SG_AI, SG_BULK, "Traffic Manager:      Flight is in progress, %=" << x);
268       speed = ((distanceM - coveredDistance) * SG_METER_TO_NM) / 3600.0;
269     } else {
270     // not departed yet
271       //remainingTimeEnroute = totalTimeEnroute;
272       elapsedTimeEnroute = 0;
273       position = dep->geod();
274       SG_LOG (SG_AI, SG_BULK, "Traffic Manager:      Flight is pending, departure in "
275         << flight->getDepartureTime() - now << " seconds ");
276     }
277   } else {
278     // departure / arrival coincident
279     //remainingTimeEnroute = totalTimeEnroute = 0.0;
280     elapsedTimeEnroute = 0;
281     position = dep->geod();
282   }
283     
284   // cartesian calculations are more numerically stable over the (potentially)
285   // large distances involved here: see bug #80
286   distanceToUser = dist(userCart, SGVec3d::fromGeod(position)) * SG_METER_TO_NM;
287
288   // If distance between user and simulated aircaft is less
289   // then 500nm, create this flight. At jet speeds 500 nm is roughly
290   // one hour flight time, so that would be a good approximate point
291   // to start a more detailed simulation of this aircraft.
292   SG_LOG (SG_AI, SG_BULK, "Traffic manager: " << registration << " is scheduled for a flight from "
293              << dep->getId() << " to " << arr->getId() << ". Current distance to user: " 
294              << distanceToUser);
295   if (distanceToUser >= TRAFFICTOAIDISTTOSTART) {
296     return true; // out of visual range, for the moment.
297   }
298   return createAIAircraft(flight, speed, deptime);
299 }
300
301 bool FGAISchedule::validModelPath(const std::string& modelPath)
302 {
303     SGPath mp(globals->get_fg_root());
304     SGPath mp_ai = mp;
305
306     mp.append(modelPath);
307     mp_ai.append("AI");
308     mp_ai.append(modelPath);
309
310     return mp.exists() || mp_ai.exists();
311 }
312
313 bool FGAISchedule::createAIAircraft(FGScheduledFlight* flight, double speedKnots, time_t deptime)
314 {
315   FGAirport* dep = flight->getDepartureAirport();
316   FGAirport* arr = flight->getArrivalAirport();
317   string flightPlanName = dep->getId() + "-" + arr->getId() + ".xml";
318   SG_LOG(SG_AI, SG_INFO, "Traffic manager: Creating AIModel from:" << flightPlanName);
319
320   // Only allow traffic to be created when the model path (or the AI version of mp) exists
321   SGPath mp(globals->get_fg_root());
322   SGPath mp_ai = mp;
323
324   mp.append(modelPath);
325   mp_ai.append("AI");
326   mp_ai.append(modelPath);
327
328   if (!mp.exists() && !mp_ai.exists()) {
329     SG_LOG(SG_AI, SG_WARN, "TrafficManager: Could not load model " << mp_ai.str());
330     return true;
331   }
332
333   aiAircraft = new FGAIAircraft(this);
334   aiAircraft->setPerformance(acType, m_class); //"jet_transport";
335   aiAircraft->setCompany(airline); //i->getAirline();
336   aiAircraft->setAcType(acType); //i->getAcType();
337   aiAircraft->setPath(modelPath.c_str());
338   //aircraft->setFlightPlan(flightPlanName);
339   aiAircraft->setLatitude(position.getLatitudeDeg());
340   aiAircraft->setLongitude(position.getLongitudeDeg());
341   aiAircraft->setAltitude(flight->getCruiseAlt()*100); // convert from FL to feet
342   aiAircraft->setSpeed(0);
343   aiAircraft->setBank(0);
344       
345   courseToDest = SGGeodesy::courseDeg(position, arr->geod());
346   FGAIFlightPlan *fp = new FGAIFlightPlan(aiAircraft, flightPlanName, courseToDest, deptime,
347                                             dep, arr, true, radius, 
348                                             flight->getCruiseAlt()*100, 
349                                             position.getLatitudeDeg(), 
350                                             position.getLongitudeDeg(), 
351                                             speedKnots, flightType, acType, 
352                                             airline);
353   if (fp->isValidPlan()) {
354         aiAircraft->SetFlightPlan(fp);
355         FGAIManager* aimgr = (FGAIManager *) globals-> get_subsystem("ai-model");
356         aimgr->attach(aiAircraft);
357         return true;
358   } else {
359         aiAircraft = NULL;
360         delete fp;
361         //hand back the flights that had already been scheduled
362         while (!flights.empty()) {
363             flights.front()->release();
364             flights.erase(flights.begin());
365         }
366         return false;
367   }
368 }
369
370 // Create an initial heading for user controlled aircraft.
371 void FGAISchedule::setHeading()  
372
373     courseToDest = SGGeodesy::courseDeg((*flights.begin())->getDepartureAirport()->geod(), (*flights.begin())->getArrivalAirport()->geod());
374 }
375
376 void FGAISchedule::scheduleFlights(time_t now)
377 {
378   if (!flights.empty()) {
379     return;
380   }
381   //string startingPort;
382   string userPort = fgGetString("/sim/presets/airport-id");
383   SG_LOG(SG_AI, SG_BULK, "Scheduling Flights for : " << modelPath << " " <<  registration << " " << homePort);
384   FGScheduledFlight *flight = NULL;
385   do {
386     if (currentDestination.empty()) {
387         flight = findAvailableFlight(userPort, flightIdentifier, now, (now+6400));
388         if (!flight)
389             flight = findAvailableFlight(currentDestination, flightIdentifier);
390     } else {
391         flight = findAvailableFlight(currentDestination, flightIdentifier);
392     }
393     if (!flight) {
394       break;
395     }
396     currentDestination = flight->getArrivalAirport()->getId();
397     //cerr << "Current destination " <<  currentDestination << endl;
398     if (!initialized) {
399         string departurePort = flight->getDepartureAirport()->getId();
400         if (userPort == departurePort) {
401             lastRun = 1;
402             hits++;
403         } else {
404             lastRun = 0;
405         }
406         //runCount++;
407         initialized = true;
408     }
409   
410     time_t arr, dep;
411     dep = flight->getDepartureTime();
412     arr = flight->getArrivalTime();
413     string depT = asctime(gmtime(&dep));
414     string arrT = asctime(gmtime(&arr));
415
416     depT = depT.substr(0,24);
417     arrT = arrT.substr(0,24);
418     SG_LOG(SG_AI, SG_BULK, "  Flight " << flight->getCallSign() << ":" 
419                              << "  "        << flight->getDepartureAirport()->getId() << ":"
420                              << "  "        << depT << ":"
421                              << " \""       << flight->getArrivalAirport()->getId() << "\"" << ":"
422                              << "  "        << arrT << ":");
423   
424     flights.push_back(flight);
425   } while (currentDestination != homePort);
426   SG_LOG(SG_AI, SG_BULK, " Done ");
427 }
428
429 bool FGAISchedule::next()
430 {
431   if (!flights.empty()) {
432     flights.front()->release();
433     flights.erase(flights.begin());
434   }
435   
436   FGScheduledFlight *flight = findAvailableFlight(currentDestination, flightIdentifier);
437   if (!flight) {
438     return false;
439   }
440   
441   currentDestination = flight->getArrivalAirport()->getId();
442 /*
443   time_t arr, dep;
444   dep = flight->getDepartureTime();
445   arr = flight->getArrivalTime();
446   string depT = asctime(gmtime(&dep));
447   string arrT = asctime(gmtime(&arr));
448
449   depT = depT.substr(0,24);
450   arrT = arrT.substr(0,24);
451   //cerr << "  " << flight->getCallSign() << ":" 
452   //     << "  " << flight->getDepartureAirport()->getId() << ":"
453   //     << "  " << depT << ":"
454   //     << " \"" << flight->getArrivalAirport()->getId() << "\"" << ":"
455   //     << "  " << arrT << ":" << endl;
456 */
457    flights.push_back(flight);
458    return true;
459 }
460
461 FGScheduledFlight* FGAISchedule::findAvailableFlight (const string &currentDestination,
462                                                       const string &req,
463                                                      time_t min, time_t max)
464 {
465     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
466
467     FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("traffic-manager");
468     FGScheduledFlightVecIterator fltBegin, fltEnd;
469     fltBegin = tmgr->getFirstFlight(req);
470     fltEnd   = tmgr->getLastFlight(req);
471
472
473      //cerr << "Finding available flight " << endl;
474      // For Now:
475      // Traverse every registered flight
476      if (fltBegin == fltEnd) {
477           //cerr << "No Flights Scheduled for " << req << endl;
478      }
479      int counter = 0;
480      for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
481           (*i)->adjustTime(now);
482            //sort(fltBegin, fltEnd, compareScheduledFlights);
483            //cerr << counter++ << endl;
484      }
485      std::sort(fltBegin, fltEnd, compareScheduledFlights);
486      for (FGScheduledFlightVecIterator i = fltBegin; i != fltEnd; i++) {
487           //bool valid = true;
488           counter++;
489           if (!(*i)->isAvailable()) {
490                //cerr << (*i)->getCallSign() << "is no longer available" << endl;
491                continue;
492           }
493           if (!((*i)->getRequirement() == req)) {
494                continue;
495           }
496           if (!(((*i)->getArrivalAirport()) && ((*i)->getDepartureAirport()))) {
497               continue;
498           }
499           if (!(currentDestination.empty())) {
500               if (currentDestination != (*i)->getDepartureAirport()->getId()) {
501                    //cerr << (*i)->getCallSign() << "Doesn't match destination" << endl;
502                    //cerr << "Current Destination " << currentDestination << "Doesnt match flight's " <<
503                    //          (*i)->getArrivalAirport()->getId() << endl;
504                    continue;
505               }
506           }
507           if (flights.size()) {
508             time_t arrival = flights.back()->getArrivalTime();
509             int groundTime = groundTimeFromRadius();
510             if ((*i)->getDepartureTime() < (arrival+(groundTime)))
511                 continue;
512           }
513           if (min != 0) {
514               time_t dep = (*i)->getDepartureTime();
515               if ((dep < min) || (dep > max))
516                   continue;
517           }
518
519           // So, if we actually get here, we have a winner
520           //cerr << "found flight: " << req << " : " << currentDestination << " : " <<       
521           //         (*i)->getArrivalAirport()->getId() << endl;
522           (*i)->lock();
523           return (*i);
524      }
525      // matches req?
526      // if currentDestination has a value, does it match departure of next flight?
527      // is departure time later than planned arrival?
528      // is departure port valid?
529      // is arrival port valid?
530      //cerr << "Ack no flight found: " << endl;
531      return NULL;
532 }
533
534 int FGAISchedule::groundTimeFromRadius()
535 {
536     if (radius < 10) 
537         return 15 * 60;
538     else if (radius < 15)
539         return 20 * 60;
540     else if (radius < 20)
541         return 30 * 60;
542     else if (radius < 25)
543         return 50 * 60;
544     else if (radius < 30)
545         return 90 * 60;
546     else 
547         return 120 * 60;
548 }
549
550
551 double FGAISchedule::getSpeed()
552 {
553   FGScheduledFlightVecIterator i = flights.begin();
554  
555   FGAirport* dep = (*i)->getDepartureAirport(),
556    *arr = (*i)->getArrivalAirport();
557   double dist = SGGeodesy::distanceNm(dep->geod(), arr->geod());
558   double remainingTimeEnroute = (*i)->getArrivalTime() - (*i)->getDepartureTime();
559
560   double speed = dist / (remainingTimeEnroute/3600.0);
561   SG_CLAMP_RANGE(speed, 300.0, 500.0);
562   return speed;
563 }
564
565 void FGAISchedule::setScore   () 
566
567     if (runCount) {
568         score = ((double) hits / (double) runCount);
569     } else {
570         if (homePort == fgGetString("/sim/presets/airport-id")) {
571             score = 0.1;
572         } else {
573             score = 0.0;
574         }
575     }
576     runCount++;
577 }
578
579 bool compareSchedules(FGAISchedule*a, FGAISchedule*b)
580
581   return (*a) < (*b); 
582
583
584 bool FGAISchedule::operator< (const FGAISchedule &other) const
585
586     //cerr << "Sorting " << registration << " and "  << other.registration << endl;
587     double currentScore = score       * (1.5 - lastRun);
588     double otherScore   = other.score * (1.5 - other.lastRun);
589     return currentScore > otherScore;
590 }
591