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