]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIFlightPlan.cxx
Merge branch 'next' into durk-atc
[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       else if ((timeDiff >= 1500) && (timeDiff < 2000))
232         leg = 4;
233       else if (timeDiff >= 2000)
234         leg = 5;
235       /*
236       if (timeDiff >= 2000)
237           leg = 5;
238       */
239       SG_LOG(SG_GENERAL, SG_INFO, "Route from " << dep->getId() << " to " << arr->getId() << ". Set leg to : " << leg << " " << ac->getTrafficRef()->getCallSign());
240       wpt_iterator = waypoints.begin();
241       bool dist = 0;
242       isValid = create(ac, dep,arr, leg, alt, speed, lat, lon,
243              firstLeg, radius, fltType, acType, airline, dist);
244       wpt_iterator = waypoints.begin();
245       //cerr << "after create: " << (*wpt_iterator)->name << endl;
246       //leg++;
247       // Now that we have dynamically created a flight plan,
248       // we need to add some code that pops any waypoints already past.
249       //return;
250     }
251   /*
252     waypoint* init_waypoint   = new waypoint;
253     init_waypoint->name       = string("initial position");
254     init_waypoint->latitude   = entity->latitude;
255     init_waypoint->longitude  = entity->longitude;
256     init_waypoint->altitude   = entity->altitude;
257     init_waypoint->speed      = entity->speed;
258     init_waypoint->crossat    = - 10000;
259     init_waypoint->gear_down  = false;
260     init_waypoint->flaps_down = false;
261     init_waypoint->finished   = false;
262     
263     wpt_vector_iterator i = waypoints.begin();
264     while (i != waypoints.end())
265     {
266       //cerr << "Checking status of each waypoint: " << (*i)->name << endl;
267        SGWayPoint first(init_waypoint->longitude, 
268                        init_waypoint->latitude, 
269                        init_waypoint->altitude);
270       SGWayPoint curr ((*i)->longitude, 
271                        (*i)->latitude, 
272                        (*i)->altitude);
273       double crse, crsDiff;
274       double dist;
275       curr.CourseAndDistance(first, &crse, &dist);
276       
277       dist *= SG_METER_TO_NM;
278       
279       // We're only interested in the absolute value of crsDiff
280       // wich should fall in the 0-180 deg range.
281       crsDiff = fabs(crse-course);
282       if (crsDiff > 180)
283         crsDiff = 360-crsDiff;
284       // These are the three conditions that we consider including
285       // in our flight plan:
286       // 1) current waypoint is less then 100 miles away OR
287       // 2) curren waypoint is ahead of us, at any distance
288      
289       if ((dist > 20.0) && (crsDiff > 90.0) && ((*i)->name != string ("EOF")))
290         {
291           //useWpt = false;
292           // Once we start including waypoints, we have to continue, even though
293           // one of the following way point would suffice. 
294           // so once is the useWpt flag is set to true, we cannot reset it to false.
295           //cerr << "Discarding waypoint: " << (*i)->name 
296           //   << ": Course difference = " << crsDiff
297           //  << "Course = " << course
298           // << "crse   = " << crse << endl;
299         }
300       else
301         useCurrentWayPoint = true;
302       
303       if (useCurrentWayPoint)
304         {
305           if ((dist > 100.0) && (useInitialWayPoint))
306             {
307               //waypoints.push_back(init_waypoint);;
308               waypoints.insert(i, init_waypoint);
309               //cerr << "Using waypoint : " << init_waypoint->name <<  endl;
310             }
311           //if (useInitialWayPoint)
312           // {
313           //    (*i)->speed = dist; // A hack
314           //  }
315           //waypoints.push_back( wpt );
316           //cerr << "Using waypoint : " << (*i)->name 
317           //  << ": course diff : " << crsDiff 
318           //   << "Course = " << course
319           //   << "crse   = " << crse << endl
320           //    << "distance      : " << dist << endl;
321           useInitialWayPoint = false;
322           i++;
323         }
324       else 
325         {
326           //delete wpt;
327           delete *(i);
328           i = waypoints.erase(i);
329           }
330           
331         }
332   */
333   //for (i = waypoints.begin(); i != waypoints.end(); i++)
334   //  cerr << "Using waypoint : " << (*i)->name << endl;
335   //wpt_iterator = waypoints.begin();
336   //cout << waypoints.size() << " waypoints read." << endl;
337 }
338
339
340
341
342 FGAIFlightPlan::~FGAIFlightPlan()
343 {
344   deleteWaypoints();
345   delete taxiRoute;
346 }
347
348
349 FGAIWaypoint* const FGAIFlightPlan::getPreviousWaypoint( void ) const
350 {
351   if (wpt_iterator == waypoints.begin()) {
352     return 0;
353   } else {
354     wpt_vector_iterator prev = wpt_iterator;
355     return *(--prev);
356   }
357 }
358
359 FGAIWaypoint* const FGAIFlightPlan::getCurrentWaypoint( void ) const
360 {
361   return *wpt_iterator;
362 }
363
364 FGAIWaypoint* const FGAIFlightPlan::getNextWaypoint( void ) const
365 {
366   wpt_vector_iterator i = waypoints.end();
367   i--;  // end() points to one element after the last one. 
368   if (wpt_iterator == i) {
369     return 0;
370   } else {
371     wpt_vector_iterator next = wpt_iterator;
372     return *(++next);
373   }
374 }
375
376 void FGAIFlightPlan::IncrementWaypoint(bool eraseWaypoints )
377 {
378   if (eraseWaypoints)
379     {
380       if (wpt_iterator == waypoints.begin())
381         wpt_iterator++;
382       else
383         {
384           delete *(waypoints.begin());
385           waypoints.erase(waypoints.begin());
386           wpt_iterator = waypoints.begin();
387           wpt_iterator++;
388         }
389     }
390   else
391     wpt_iterator++;
392
393 }
394
395 void FGAIFlightPlan::DecrementWaypoint(bool eraseWaypoints )
396 {
397     if (eraseWaypoints)
398     {
399         if (wpt_iterator == waypoints.end())
400             wpt_iterator--;
401         else
402         {
403             delete *(waypoints.end());
404             waypoints.erase(waypoints.end());
405             wpt_iterator = waypoints.end();
406             wpt_iterator--;
407         }
408     }
409     else
410         wpt_iterator--;
411
412 }
413
414
415 // gives distance in feet from a position to a waypoint
416 double FGAIFlightPlan::getDistanceToGo(double lat, double lon, FGAIWaypoint* wp) const{
417   return SGGeodesy::distanceM(SGGeod::fromDeg(lon, lat), 
418       SGGeod::fromDeg(wp->getLongitude(), wp->getLatitude()));
419 }
420
421 // sets distance in feet from a lead point to the current waypoint
422 void FGAIFlightPlan::setLeadDistance(double speed, double bearing, 
423                                      FGAIWaypoint* current, FGAIWaypoint* next){
424   double turn_radius;
425   // Handle Ground steering
426   // At a turn rate of 30 degrees per second, it takes 12 seconds to do a full 360 degree turn
427   // So, to get an estimate of the turn radius, calculate the cicumference of the circle
428   // we travel on. Get the turn radius by dividing by PI (*2).
429   if (speed < 0.5) {
430         lead_distance = 0.5;
431         return;
432   }
433   if (speed < 25) {
434        turn_radius = ((360/30)*fabs(speed)) / (2*M_PI);
435   } else 
436       turn_radius = 0.1911 * speed * speed; // an estimate for 25 degrees bank
437
438   double inbound = bearing;
439   double outbound = getBearing(current, next);
440   leadInAngle = fabs(inbound - outbound);
441   if (leadInAngle > 180.0) 
442     leadInAngle = 360.0 - leadInAngle;
443   //if (leadInAngle < 30.0) // To prevent lead_dist from getting so small it is skipped 
444   //  leadInAngle = 30.0;
445   
446   //lead_distance = turn_radius * sin(leadInAngle * SG_DEGREES_TO_RADIANS); 
447   lead_distance = turn_radius * tan((leadInAngle * SG_DEGREES_TO_RADIANS)/2);
448   /*
449   if ((lead_distance > (3*turn_radius)) && (current->on_ground == false)) {
450       // cerr << "Warning: Lead-in distance is large. Inbound = " << inbound
451       //      << ". Outbound = " << outbound << ". Lead in angle = " << leadInAngle  << ". Turn radius = " << turn_radius << endl;
452        lead_distance = 3 * turn_radius;
453        return;
454   }
455   if ((leadInAngle > 90) && (current->on_ground == true)) {
456       lead_distance = turn_radius * tan((90 * SG_DEGREES_TO_RADIANS)/2);
457       return;
458   }*/
459 }
460
461 void FGAIFlightPlan::setLeadDistance(double distance_ft){
462   lead_distance = distance_ft;
463 }
464
465
466 double FGAIFlightPlan::getBearing(FGAIWaypoint* first, FGAIWaypoint* second) const{
467   return getBearing(first->getLatitude(), first->getLongitude(), second);
468 }
469
470
471 double FGAIFlightPlan::getBearing(double lat, double lon, FGAIWaypoint* wp) const{
472   return SGGeodesy::courseDeg(SGGeod::fromDeg(lon, lat), 
473       SGGeod::fromDeg(wp->getLongitude(), wp->getLatitude()));
474 }
475
476 void FGAIFlightPlan::deleteWaypoints()
477 {
478   for (wpt_vector_iterator i = waypoints.begin(); i != waypoints.end();i++)
479     delete (*i);
480   waypoints.clear();
481 }
482
483 // Delete all waypoints except the last, 
484 // which we will recycle as the first waypoint in the next leg;
485 void FGAIFlightPlan::resetWaypoints()
486 {
487   if (waypoints.begin() == waypoints.end())
488     return;
489   else
490     {
491       FGAIWaypoint *wpt = new FGAIWaypoint;
492       wpt_vector_iterator i = waypoints.end();
493       i--;
494       wpt->setName        ( (*i)->getName()       );
495       wpt->setLatitude    ( (*i)->getLatitude()   );
496       wpt->setLongitude   ( (*i)->getLongitude()  );
497       wpt->setAltitude    ( (*i)->getAltitude()   );
498       wpt->setSpeed       ( (*i)->getSpeed()      );
499       wpt->setCrossat     ( (*i)->getCrossat()    );
500       wpt->setGear_down   ( (*i)->getGear_down()  );
501       wpt->setFlaps_down  ( (*i)->getFlaps_down() );
502       wpt->setFinished    ( false                 );
503       wpt->setOn_ground   ( (*i)->getOn_ground()  );
504       //cerr << "Recycling waypoint " << wpt->name << endl;
505       deleteWaypoints();
506       waypoints.push_back(wpt);
507     }
508 }
509
510 // Start flightplan over from the beginning
511 void FGAIFlightPlan::restart()
512 {
513   wpt_iterator = waypoints.begin();
514 }
515
516
517 void FGAIFlightPlan::deleteTaxiRoute() 
518 {
519   delete taxiRoute;
520   taxiRoute = 0;
521 }
522
523
524 int FGAIFlightPlan::getRouteIndex(int i) {
525   if ((i > 0) && (i < (int)waypoints.size())) {
526     return waypoints[i]->getRouteIndex();
527   }
528   else
529     return 0;
530 }
531
532
533 double FGAIFlightPlan::checkTrackLength(string wptName) {
534     // skip the first two waypoints: first one is behind, second one is partially done;
535     double trackDistance = 0;
536     wpt_vector_iterator wptvec = waypoints.begin();
537     wptvec++;
538     wptvec++;
539     while ((wptvec != waypoints.end()) && (!((*wptvec)->contains(wptName)))) {
540            trackDistance += (*wptvec)->getTrackLength();
541            wptvec++;
542     }
543     if (wptvec == waypoints.end()) {
544         trackDistance = 0; // name not found
545     }
546     return trackDistance;
547 }