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