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