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