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