]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIFlightPlan.cxx
add MIL-STD-1787B Aiming Reticle (stadiametric; TODO: standby)
[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   SGPath path( globals->get_fg_root() );
53   path.append( ("/AI/FlightPlans/" + filename).c_str() );
54   SGPropertyNode root;
55   repeat = false;
56
57   try {
58       readProperties(path.str(), &root);
59   } catch (const sg_exception &e) {
60       SG_LOG(SG_GENERAL, SG_ALERT,
61        "Error reading AI flight plan: " << path.str());
62        // cout << path.str() << endl;
63      return;
64   }
65
66   SGPropertyNode * node = root.getNode("flightplan");
67   for (i = 0; i < node->nChildren(); i++) { 
68      //cout << "Reading waypoint " << i << endl;        
69      waypoint* wpt = new waypoint;
70      SGPropertyNode * wpt_node = node->getChild(i);
71      wpt->name      = wpt_node->getStringValue("name", "END");
72      wpt->latitude  = wpt_node->getDoubleValue("lat", 0);
73      wpt->longitude = wpt_node->getDoubleValue("lon", 0);
74      wpt->altitude  = wpt_node->getDoubleValue("alt", 0);
75      wpt->speed     = wpt_node->getDoubleValue("ktas", 0);
76      wpt->crossat   = wpt_node->getDoubleValue("crossat", -10000);
77      wpt->gear_down = wpt_node->getBoolValue("gear-down", false);
78      wpt->flaps_down= wpt_node->getBoolValue("flaps-down", false);
79      wpt->on_ground = wpt_node->getBoolValue("on-ground", false);
80
81      if (wpt->name == "END") wpt->finished = true;
82      else wpt->finished = false;
83
84      waypoints.push_back( wpt );
85    }
86
87   wpt_iterator = waypoints.begin();
88   //cout << waypoints.size() << " waypoints read." << endl;
89 }
90
91
92 // This is a modified version of the constructor,
93 // Which not only reads the waypoints from a 
94 // Flight plan file, but also adds the current
95 // Position computed by the traffic manager, as well
96 // as setting speeds and altitude computed by the
97 // traffic manager. 
98 FGAIFlightPlan::FGAIFlightPlan(const std::string& p,
99                                double course,
100                                time_t start,
101                                FGAirport *dep,
102                                FGAirport *arr,
103                                bool firstLeg,
104                                double radius,
105                                double alt,
106                                double lat,
107                                double lon,
108                                double speed,
109                                const string& fltType,
110                                const string& acType,
111                                const string& airline)
112 {
113   leg = 10;
114   gateId=0;
115   start_time = start;
116   bool useInitialWayPoint = true;
117   bool useCurrentWayPoint = false;
118   SGPath path( globals->get_fg_root() );
119   path.append( "/AI/FlightPlans" );
120   path.append( p );
121   SGPropertyNode root;
122   
123   // This is a bit of a hack:
124   // Normally the value of course will be used to evaluate whether
125   // or not a waypoint will be used for midair initialization of 
126   // an AI aircraft. However, if a course value of 999 will be passed
127   // when an update request is received, which will by definition always be
128   // on the ground and should include all waypoints.
129   if (course == 999) 
130     {
131       useInitialWayPoint = false;
132       useCurrentWayPoint = true;
133     }
134
135   if (path.exists()) 
136     {
137       try 
138         {
139           readProperties(path.str(), &root);
140           
141           SGPropertyNode * node = root.getNode("flightplan");
142           
143           //waypoints.push_back( init_waypoint );
144           for (int i = 0; i < node->nChildren(); i++) { 
145             //cout << "Reading waypoint " << i << endl;
146             waypoint* wpt = new waypoint;
147             SGPropertyNode * wpt_node = node->getChild(i);
148             wpt->name      = wpt_node->getStringValue("name", "END");
149             wpt->latitude  = wpt_node->getDoubleValue("lat", 0);
150             wpt->longitude = wpt_node->getDoubleValue("lon", 0);
151             wpt->altitude  = wpt_node->getDoubleValue("alt", 0);
152             wpt->speed     = wpt_node->getDoubleValue("ktas", 0);
153             //wpt->speed     = speed;
154             wpt->crossat   = wpt_node->getDoubleValue("crossat", -10000);
155             wpt->gear_down = wpt_node->getBoolValue("gear-down", false);
156             wpt->flaps_down= wpt_node->getBoolValue("flaps-down", false);
157             
158             if (wpt->name == "END") wpt->finished = true;
159             else wpt->finished = false;
160             waypoints.push_back(wpt);
161           }
162         }
163       catch (const sg_exception &e) {
164         SG_LOG(SG_GENERAL, SG_WARN,
165                "Error reading AI flight plan: ");
166         cerr << "Errno = " << errno << endl;
167         if (errno == ENOENT)
168           {
169             cerr << "Reason: No such file or directory" << endl;
170           }
171       }
172     }
173   else
174     {
175       // cout << path.str() << endl;
176       // cout << "Trying to create this plan dynamically" << endl;
177       // cout << "Route from " << dep->id << " to " << arr->id << endl;
178       time_t now = time(NULL) + fgGetLong("/sim/time/warp");
179       time_t timeDiff = now-start; 
180       leg = 1;
181       if ((timeDiff > 300) && (timeDiff < 1200))
182         leg = 2;
183       else if ((timeDiff >= 1200) && (timeDiff < 1500))
184         leg = 3;
185       else if ((timeDiff >= 1500) && (timeDiff < 2000))
186         leg = 4;
187       else if (timeDiff >= 2000)
188         leg = 5;
189       
190       //cerr << "Set leg to : " << leg << endl;  
191       wpt_iterator = waypoints.begin();
192       create(dep,arr, leg, alt, speed, lat, lon,
193              firstLeg, radius, fltType, acType, airline);
194       wpt_iterator = waypoints.begin();
195       //cerr << "after create: " << (*wpt_iterator)->name << endl;
196       //leg++;
197       // Now that we have dynamically created a flight plan,
198       // we need to add some code that pops any waypoints already past.
199       //return;
200     }
201   /*
202     waypoint* init_waypoint   = new waypoint;
203     init_waypoint->name       = string("initial position");
204     init_waypoint->latitude   = entity->latitude;
205     init_waypoint->longitude  = entity->longitude;
206     init_waypoint->altitude   = entity->altitude;
207     init_waypoint->speed      = entity->speed;
208     init_waypoint->crossat    = - 10000;
209     init_waypoint->gear_down  = false;
210     init_waypoint->flaps_down = false;
211     init_waypoint->finished   = false;
212     
213     wpt_vector_iterator i = waypoints.begin();
214     while (i != waypoints.end())
215     {
216       //cerr << "Checking status of each waypoint: " << (*i)->name << endl;
217        SGWayPoint first(init_waypoint->longitude, 
218                        init_waypoint->latitude, 
219                        init_waypoint->altitude);
220       SGWayPoint curr ((*i)->longitude, 
221                        (*i)->latitude, 
222                        (*i)->altitude);
223       double crse, crsDiff;
224       double dist;
225       curr.CourseAndDistance(first, &crse, &dist);
226       
227       dist *= SG_METER_TO_NM;
228       
229       // We're only interested in the absolute value of crsDiff
230       // wich should fall in the 0-180 deg range.
231       crsDiff = fabs(crse-course);
232       if (crsDiff > 180)
233         crsDiff = 360-crsDiff;
234       // These are the three conditions that we consider including
235       // in our flight plan:
236       // 1) current waypoint is less then 100 miles away OR
237       // 2) curren waypoint is ahead of us, at any distance
238      
239       if ((dist > 20.0) && (crsDiff > 90.0) && ((*i)->name != string ("EOF")))
240         {
241           //useWpt = false;
242           // Once we start including waypoints, we have to continue, even though
243           // one of the following way point would suffice. 
244           // so once is the useWpt flag is set to true, we cannot reset it to false.
245           //cerr << "Discarding waypoint: " << (*i)->name 
246           //   << ": Course difference = " << crsDiff
247           //  << "Course = " << course
248           // << "crse   = " << crse << endl;
249         }
250       else
251         useCurrentWayPoint = true;
252       
253       if (useCurrentWayPoint)
254         {
255           if ((dist > 100.0) && (useInitialWayPoint))
256             {
257               //waypoints.push_back(init_waypoint);;
258               waypoints.insert(i, init_waypoint);
259               //cerr << "Using waypoint : " << init_waypoint->name <<  endl;
260             }
261           //if (useInitialWayPoint)
262           // {
263           //    (*i)->speed = dist; // A hack
264           //  }
265           //waypoints.push_back( wpt );
266           //cerr << "Using waypoint : " << (*i)->name 
267           //  << ": course diff : " << crsDiff 
268           //   << "Course = " << course
269           //   << "crse   = " << crse << endl
270           //    << "distance      : " << dist << endl;
271           useInitialWayPoint = false;
272           i++;
273         }
274       else 
275         {
276           //delete wpt;
277           delete *(i);
278           i = waypoints.erase(i);
279           }
280           
281         }
282   */
283   //for (i = waypoints.begin(); i != waypoints.end(); i++)
284   //  cerr << "Using waypoint : " << (*i)->name << endl;
285   //wpt_iterator = waypoints.begin();
286   //cout << waypoints.size() << " waypoints read." << endl;
287 }
288
289
290
291
292 FGAIFlightPlan::~FGAIFlightPlan()
293 {
294   deleteWaypoints();
295   //waypoints.clear();
296   //while (waypoints.begin() != waypoints.end())
297   //  {
298   //    delete *(waypoints.begin());
299   //    waypoints.erase (waypoints.begin());
300   //  }
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 }