]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIFlightPlan.cxx
AI/ATC enhancements:
[flightgear.git] / src / AIModel / AIFlightPlan.cxx
1 // // FGAIFlightPlan - class for loading and storing  AI flight plans
2 // Written by David Culp, started May 2004
3 // - davidculp2@comcast.net
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 #ifdef HAVE_CONFIG_H
20 #  include <config.h>
21 #endif
22
23 #include <iostream>
24
25 #include <simgear/misc/sg_path.hxx>
26 #include <simgear/debug/logstream.hxx>
27 #include <simgear/route/waypoint.hxx>
28 #include <simgear/math/sg_geodesy.hxx>
29 #include <simgear/structure/exception.hxx>
30 #include <simgear/constants.h>
31 #include <simgear/props/props.hxx>
32 #include <simgear/props/props_io.hxx>
33
34 #include <Main/globals.hxx>
35 #include <Main/fg_props.hxx>
36 #include <Main/fg_init.hxx>
37 #include <Airports/simple.hxx>
38 #include <Airports/runways.hxx>
39 #include <Airports/groundnetwork.hxx>
40
41 #include <Environment/environment_mgr.hxx>
42 #include <Environment/environment.hxx>
43
44 #include "AIFlightPlan.hxx"
45 #include "AIAircraft.hxx"
46
47 using std::cerr;
48
49 FGAIWaypoint::FGAIWaypoint() {
50   latitude    = 0;
51   longitude   = 0;
52   altitude    = 0;
53   speed       = 0;
54   crossat     = 0;
55   finished    = 0;
56   gear_down   = 0;
57   flaps_down  = 0;
58   on_ground   = 0;
59   routeIndex  = 0;
60   time_sec    = 0;
61   trackLength = 0;
62 }
63
64 bool FGAIWaypoint::contains(string target) {
65     size_t found = name.find(target);
66     if (found == string::npos)
67         return false;
68     else
69         return true;
70 }
71
72 FGAIFlightPlan::FGAIFlightPlan() 
73 {
74     rwy = 0;
75     sid = 0;
76     repeat = false;
77     distance_to_go = 0;
78     lead_distance = 0;
79     start_time = 0;
80     arrivalTime = 0;
81     leg = 10;
82     gateId = 0;
83     lastNodeVisited = 0;
84     taxiRoute = 0;
85     wpt_iterator = waypoints.begin();
86     isValid = true;
87 }
88
89 FGAIFlightPlan::FGAIFlightPlan(const string& filename)
90 {
91   int i;
92   sid = 0;
93   start_time = 0;
94   leg = 10;
95   gateId = 0;
96   taxiRoute = 0;
97   SGPath path( globals->get_fg_root() );
98   path.append( ("/AI/FlightPlans/" + filename).c_str() );
99   SGPropertyNode root;
100   repeat = false;
101
102   try {
103       readProperties(path.str(), &root);
104   } catch (const sg_exception &) {
105       SG_LOG(SG_GENERAL, SG_ALERT,
106        "Error reading AI flight plan: " << path.str());
107        // cout << path.str() << endl;
108      return;
109   }
110
111   SGPropertyNode * node = root.getNode("flightplan");
112   for (i = 0; i < node->nChildren(); i++) { 
113      //cout << "Reading waypoint " << i << endl;        
114      FGAIWaypoint* wpt = new FGAIWaypoint;
115      SGPropertyNode * wpt_node = node->getChild(i);
116      wpt->setName       (wpt_node->getStringValue("name", "END"     ));
117      wpt->setLatitude   (wpt_node->getDoubleValue("lat", 0          ));
118      wpt->setLongitude  (wpt_node->getDoubleValue("lon", 0          ));
119      wpt->setAltitude   (wpt_node->getDoubleValue("alt", 0          ));
120      wpt->setSpeed      (wpt_node->getDoubleValue("ktas", 0         ));
121      wpt->setCrossat    (wpt_node->getDoubleValue("crossat", -10000 ));
122      wpt->setGear_down  (wpt_node->getBoolValue("gear-down", false  ));
123      wpt->setFlaps_down (wpt_node->getBoolValue("flaps-down", false ));
124      wpt->setOn_ground  (wpt_node->getBoolValue("on-ground", false  ));
125      wpt->setTime_sec   (wpt_node->getDoubleValue("time-sec", 0     ));
126      wpt->setTime       (wpt_node->getStringValue("time", ""        ));
127
128      if (wpt->getName() == "END") wpt->setFinished(true);
129      else wpt->setFinished(false);
130
131      waypoints.push_back( wpt );
132    }
133
134   wpt_iterator = waypoints.begin();
135   isValid = true;
136   //cout << waypoints.size() << " waypoints read." << endl;
137 }
138
139
140 // This is a modified version of the constructor,
141 // Which not only reads the waypoints from a 
142 // Flight plan file, but also adds the current
143 // Position computed by the traffic manager, as well
144 // as setting speeds and altitude computed by the
145 // traffic manager. 
146 FGAIFlightPlan::FGAIFlightPlan(FGAIAircraft *ac,
147                                const std::string& p,
148                                double course,
149                                time_t start,
150                                FGAirport *dep,
151                                FGAirport *arr,
152                                bool firstLeg,
153                                double radius,
154                                double alt,
155                                double lat,
156                                double lon,
157                                double speed,
158                                const string& fltType,
159                                const string& acType,
160                                const string& airline)
161 {
162   sid = 0;
163   repeat = false;
164   leg = 10;
165   gateId=0;
166   taxiRoute = 0;
167   start_time = start;
168   bool useInitialWayPoint = true;
169   bool useCurrentWayPoint = false;
170   SGPath path( globals->get_fg_root() );
171   path.append( "/AI/FlightPlans" );
172   path.append( p );
173   
174   SGPropertyNode root;
175   isValid = true;
176   // This is a bit of a hack:
177   // Normally the value of course will be used to evaluate whether
178   // or not a waypoint will be used for midair initialization of 
179   // an AI aircraft. However, if a course value of 999 will be passed
180   // when an update request is received, which will by definition always be
181   // on the ground and should include all waypoints.
182   if (course == 999) 
183     {
184       useInitialWayPoint = false;
185       useCurrentWayPoint = true;
186     }
187
188   if (path.exists()) 
189     {
190       try 
191         {
192           readProperties(path.str(), &root);
193           
194           SGPropertyNode * node = root.getNode("flightplan");
195           
196           //waypoints.push_back( init_waypoint );
197           for (int i = 0; i < node->nChildren(); i++) { 
198             //cout << "Reading waypoint " << i << endl;
199             FGAIWaypoint* wpt = new FGAIWaypoint;
200             SGPropertyNode * wpt_node = node->getChild(i);
201             wpt->setName       (wpt_node->getStringValue("name", "END"     ));
202             wpt->setLatitude   (wpt_node->getDoubleValue("lat", 0          ));
203             wpt->setLongitude  (wpt_node->getDoubleValue("lon", 0          ));
204             wpt->setAltitude   (wpt_node->getDoubleValue("alt", 0          ));
205             wpt->setSpeed      (wpt_node->getDoubleValue("ktas", 0         ));
206             wpt->setCrossat    (wpt_node->getDoubleValue("crossat", -10000 ));
207             wpt->setGear_down  (wpt_node->getBoolValue("gear-down", false  ));
208             wpt->setFlaps_down (wpt_node->getBoolValue("flaps-down", false ));
209             
210             if (wpt->getName() == "END") wpt->setFinished(true);
211             else wpt->setFinished(false);
212             waypoints.push_back(wpt);
213           } // of node loop
214           wpt_iterator = waypoints.begin();
215         } catch (const sg_exception &e) {
216       SG_LOG(SG_GENERAL, SG_WARN, "Error reading AI flight plan: " << 
217         e.getMessage() << " from " << e.getOrigin());
218     }
219   } else {
220       // cout << path.str() << endl;
221       // cout << "Trying to create this plan dynamically" << endl;
222       // cout << "Route from " << dep->id << " to " << arr->id << endl;
223       time_t now = time(NULL) + fgGetLong("/sim/time/warp");
224       time_t timeDiff = now-start; 
225       leg = 1;
226       
227       if ((timeDiff > 60) && (timeDiff < 1200))
228         leg = 2;
229       else if ((timeDiff >= 1200) && (timeDiff < 1500)) {
230         leg = 3;
231         ac->setTakeOffStatus(2);
232       }
233       else if ((timeDiff >= 1500) && (timeDiff < 2000))
234         leg = 4;
235       else if (timeDiff >= 2000)
236         leg = 5;
237       /*
238       if (timeDiff >= 2000)
239           leg = 5;
240       */
241       SG_LOG(SG_GENERAL, SG_INFO, "Route from " << dep->getId() << " to " << arr->getId() << ". Set leg to : " << leg << " " << ac->getTrafficRef()->getCallSign());
242       wpt_iterator = waypoints.begin();
243       bool dist = 0;
244       isValid = create(ac, dep,arr, leg, alt, speed, lat, lon,
245              firstLeg, radius, fltType, acType, airline, dist);
246       wpt_iterator = waypoints.begin();
247       //cerr << "after create: " << (*wpt_iterator)->name << endl;
248       //leg++;
249       // Now that we have dynamically created a flight plan,
250       // we need to add some code that pops any waypoints already past.
251       //return;
252     }
253   /*
254     waypoint* init_waypoint   = new waypoint;
255     init_waypoint->name       = string("initial position");
256     init_waypoint->latitude   = entity->latitude;
257     init_waypoint->longitude  = entity->longitude;
258     init_waypoint->altitude   = entity->altitude;
259     init_waypoint->speed      = entity->speed;
260     init_waypoint->crossat    = - 10000;
261     init_waypoint->gear_down  = false;
262     init_waypoint->flaps_down = false;
263     init_waypoint->finished   = false;
264     
265     wpt_vector_iterator i = waypoints.begin();
266     while (i != waypoints.end())
267     {
268       //cerr << "Checking status of each waypoint: " << (*i)->name << endl;
269        SGWayPoint first(init_waypoint->longitude, 
270                        init_waypoint->latitude, 
271                        init_waypoint->altitude);
272       SGWayPoint curr ((*i)->longitude, 
273                        (*i)->latitude, 
274                        (*i)->altitude);
275       double crse, crsDiff;
276       double dist;
277       curr.CourseAndDistance(first, &crse, &dist);
278       
279       dist *= SG_METER_TO_NM;
280       
281       // We're only interested in the absolute value of crsDiff
282       // wich should fall in the 0-180 deg range.
283       crsDiff = fabs(crse-course);
284       if (crsDiff > 180)
285         crsDiff = 360-crsDiff;
286       // These are the three conditions that we consider including
287       // in our flight plan:
288       // 1) current waypoint is less then 100 miles away OR
289       // 2) curren waypoint is ahead of us, at any distance
290      
291       if ((dist > 20.0) && (crsDiff > 90.0) && ((*i)->name != string ("EOF")))
292         {
293           //useWpt = false;
294           // Once we start including waypoints, we have to continue, even though
295           // one of the following way point would suffice. 
296           // so once is the useWpt flag is set to true, we cannot reset it to false.
297           //cerr << "Discarding waypoint: " << (*i)->name 
298           //   << ": Course difference = " << crsDiff
299           //  << "Course = " << course
300           // << "crse   = " << crse << endl;
301         }
302       else
303         useCurrentWayPoint = true;
304       
305       if (useCurrentWayPoint)
306         {
307           if ((dist > 100.0) && (useInitialWayPoint))
308             {
309               //waypoints.push_back(init_waypoint);;
310               waypoints.insert(i, init_waypoint);
311               //cerr << "Using waypoint : " << init_waypoint->name <<  endl;
312             }
313           //if (useInitialWayPoint)
314           // {
315           //    (*i)->speed = dist; // A hack
316           //  }
317           //waypoints.push_back( wpt );
318           //cerr << "Using waypoint : " << (*i)->name 
319           //  << ": course diff : " << crsDiff 
320           //   << "Course = " << course
321           //   << "crse   = " << crse << endl
322           //    << "distance      : " << dist << endl;
323           useInitialWayPoint = false;
324           i++;
325         }
326       else 
327         {
328           //delete wpt;
329           delete *(i);
330           i = waypoints.erase(i);
331           }
332           
333         }
334   */
335   //for (i = waypoints.begin(); i != waypoints.end(); i++)
336   //  cerr << "Using waypoint : " << (*i)->name << endl;
337   //wpt_iterator = waypoints.begin();
338   //cout << waypoints.size() << " waypoints read." << endl;
339 }
340
341
342
343
344 FGAIFlightPlan::~FGAIFlightPlan()
345 {
346   deleteWaypoints();
347   delete taxiRoute;
348 }
349
350
351 FGAIWaypoint* const FGAIFlightPlan::getPreviousWaypoint( void ) const
352 {
353   if (wpt_iterator == waypoints.begin()) {
354     return 0;
355   } else {
356     wpt_vector_iterator prev = wpt_iterator;
357     return *(--prev);
358   }
359 }
360
361 FGAIWaypoint* const FGAIFlightPlan::getCurrentWaypoint( void ) const
362 {
363   return *wpt_iterator;
364 }
365
366 FGAIWaypoint* const FGAIFlightPlan::getNextWaypoint( void ) const
367 {
368   wpt_vector_iterator i = waypoints.end();
369   i--;  // end() points to one element after the last one. 
370   if (wpt_iterator == i) {
371     return 0;
372   } else {
373     wpt_vector_iterator next = wpt_iterator;
374     return *(++next);
375   }
376 }
377
378 void FGAIFlightPlan::IncrementWaypoint(bool eraseWaypoints )
379 {
380   if (eraseWaypoints)
381     {
382       if (wpt_iterator == waypoints.begin())
383         wpt_iterator++;
384       else
385         {
386           delete *(waypoints.begin());
387           waypoints.erase(waypoints.begin());
388           wpt_iterator = waypoints.begin();
389           wpt_iterator++;
390         }
391     }
392   else
393     wpt_iterator++;
394
395 }
396
397 void FGAIFlightPlan::DecrementWaypoint(bool eraseWaypoints )
398 {
399     if (eraseWaypoints)
400     {
401         if (wpt_iterator == waypoints.end())
402             wpt_iterator--;
403         else
404         {
405             delete *(waypoints.end());
406             waypoints.erase(waypoints.end());
407             wpt_iterator = waypoints.end();
408             wpt_iterator--;
409         }
410     }
411     else
412         wpt_iterator--;
413
414 }
415
416
417 // gives distance in feet from a position to a waypoint
418 double FGAIFlightPlan::getDistanceToGo(double lat, double lon, FGAIWaypoint* wp) const{
419   return SGGeodesy::distanceM(SGGeod::fromDeg(lon, lat), 
420       SGGeod::fromDeg(wp->getLongitude(), wp->getLatitude()));
421 }
422
423 // sets distance in feet from a lead point to the current waypoint
424 void FGAIFlightPlan::setLeadDistance(double speed, double bearing, 
425                                      FGAIWaypoint* current, FGAIWaypoint* next){
426   double turn_radius;
427   // Handle Ground steering
428   // At a turn rate of 30 degrees per second, it takes 12 seconds to do a full 360 degree turn
429   // So, to get an estimate of the turn radius, calculate the cicumference of the circle
430   // we travel on. Get the turn radius by dividing by PI (*2).
431   if (speed < 0.5) {
432         lead_distance = 0.5;
433         return;
434   }
435   if (speed < 25) {
436        turn_radius = ((360/30)*fabs(speed)) / (2*M_PI);
437   } else 
438       turn_radius = 0.1911 * speed * speed; // an estimate for 25 degrees bank
439
440   double inbound = bearing;
441   double outbound = getBearing(current, next);
442   leadInAngle = fabs(inbound - outbound);
443   if (leadInAngle > 180.0) 
444     leadInAngle = 360.0 - leadInAngle;
445   //if (leadInAngle < 30.0) // To prevent lead_dist from getting so small it is skipped 
446   //  leadInAngle = 30.0;
447   
448   //lead_distance = turn_radius * sin(leadInAngle * SG_DEGREES_TO_RADIANS); 
449   lead_distance = turn_radius * tan((leadInAngle * SG_DEGREES_TO_RADIANS)/2);
450   /*
451   if ((lead_distance > (3*turn_radius)) && (current->on_ground == false)) {
452       // cerr << "Warning: Lead-in distance is large. Inbound = " << inbound
453       //      << ". Outbound = " << outbound << ". Lead in angle = " << leadInAngle  << ". Turn radius = " << turn_radius << endl;
454        lead_distance = 3 * turn_radius;
455        return;
456   }
457   if ((leadInAngle > 90) && (current->on_ground == true)) {
458       lead_distance = turn_radius * tan((90 * SG_DEGREES_TO_RADIANS)/2);
459       return;
460   }*/
461 }
462
463 void FGAIFlightPlan::setLeadDistance(double distance_ft){
464   lead_distance = distance_ft;
465 }
466
467
468 double FGAIFlightPlan::getBearing(FGAIWaypoint* first, FGAIWaypoint* second) const{
469   return getBearing(first->getLatitude(), first->getLongitude(), second);
470 }
471
472
473 double FGAIFlightPlan::getBearing(double lat, double lon, FGAIWaypoint* wp) const{
474   return SGGeodesy::courseDeg(SGGeod::fromDeg(lon, lat), 
475       SGGeod::fromDeg(wp->getLongitude(), wp->getLatitude()));
476 }
477
478 void FGAIFlightPlan::deleteWaypoints()
479 {
480   for (wpt_vector_iterator i = waypoints.begin(); i != waypoints.end();i++)
481     delete (*i);
482   waypoints.clear();
483 }
484
485 // Delete all waypoints except the last, 
486 // which we will recycle as the first waypoint in the next leg;
487 void FGAIFlightPlan::resetWaypoints()
488 {
489   if (waypoints.begin() == waypoints.end())
490     return;
491   else
492     {
493       FGAIWaypoint *wpt = new FGAIWaypoint;
494       wpt_vector_iterator i = waypoints.end();
495       i--;
496       wpt->setName        ( (*i)->getName()       );
497       wpt->setLatitude    ( (*i)->getLatitude()   );
498       wpt->setLongitude   ( (*i)->getLongitude()  );
499       wpt->setAltitude    ( (*i)->getAltitude()   );
500       wpt->setSpeed       ( (*i)->getSpeed()      );
501       wpt->setCrossat     ( (*i)->getCrossat()    );
502       wpt->setGear_down   ( (*i)->getGear_down()  );
503       wpt->setFlaps_down  ( (*i)->getFlaps_down() );
504       wpt->setFinished    ( false                 );
505       wpt->setOn_ground   ( (*i)->getOn_ground()  );
506       //cerr << "Recycling waypoint " << wpt->name << endl;
507       deleteWaypoints();
508       waypoints.push_back(wpt);
509     }
510 }
511
512 // Start flightplan over from the beginning
513 void FGAIFlightPlan::restart()
514 {
515   wpt_iterator = waypoints.begin();
516 }
517
518
519 void FGAIFlightPlan::deleteTaxiRoute() 
520 {
521   delete taxiRoute;
522   taxiRoute = 0;
523 }
524
525
526 int FGAIFlightPlan::getRouteIndex(int i) {
527   if ((i > 0) && (i < (int)waypoints.size())) {
528     return waypoints[i]->getRouteIndex();
529   }
530   else
531     return 0;
532 }
533
534
535 double FGAIFlightPlan::checkTrackLength(string wptName) {
536     // skip the first two waypoints: first one is behind, second one is partially done;
537     double trackDistance = 0;
538     wpt_vector_iterator wptvec = waypoints.begin();
539     wptvec++;
540     wptvec++;
541     while ((wptvec != waypoints.end()) && (!((*wptvec)->contains(wptName)))) {
542            trackDistance += (*wptvec)->getTrackLength();
543            wptvec++;
544     }
545     if (wptvec == waypoints.end()) {
546         trackDistance = 0; // name not found
547     }
548     return trackDistance;
549 }