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