]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIFlightPlan.cxx
NavDisplay: fix update lag when switching range or centre.
[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 #include "AIAircraft.hxx"
46
47 using std::cerr;
48
49 FGAIWaypoint::FGAIWaypoint() {
50   latitude    = 0;
51   longitude   = 0;
52   altitude    = 0;
53   speed       = 0;
54   crossat     = 0;
55   finished    = 0;
56   gear_down   = 0;
57   flaps_down  = 0;
58   on_ground   = 0;
59   routeIndex  = 0;
60   time_sec    = 0;
61   trackLength = 0;
62 }
63
64 bool FGAIWaypoint::contains(string target) {
65     size_t found = name.find(target);
66     if (found == string::npos)
67         return false;
68     else
69         return true;
70 }
71
72 FGAIFlightPlan::FGAIFlightPlan() 
73 {
74     sid = 0;
75     repeat = false;
76     distance_to_go = 0;
77     lead_distance = 0;
78     start_time = 0;
79     arrivalTime = 0;
80     leg = 10;
81     gateId = 0;
82     lastNodeVisited = 0;
83     taxiRoute = 0;
84     wpt_iterator = waypoints.begin();
85     isValid = true;
86 }
87
88 FGAIFlightPlan::FGAIFlightPlan(const string& filename)
89 {
90   int i;
91   sid = 0;
92   start_time = 0;
93   leg = 10;
94   gateId = 0;
95   taxiRoute = 0;
96   SGPath path( globals->get_fg_root() );
97   path.append( ("/AI/FlightPlans/" + filename).c_str() );
98   SGPropertyNode root;
99   repeat = false;
100
101   try {
102       readProperties(path.str(), &root);
103   } catch (const sg_exception &) {
104       SG_LOG(SG_AI, SG_ALERT,
105        "Error reading AI flight plan: " << path.str());
106        // cout << path.str() << endl;
107      return;
108   }
109
110   SGPropertyNode * node = root.getNode("flightplan");
111   for (i = 0; i < node->nChildren(); i++) { 
112      //cout << "Reading waypoint " << i << endl;        
113      FGAIWaypoint* wpt = new FGAIWaypoint;
114      SGPropertyNode * wpt_node = node->getChild(i);
115      wpt->setName       (wpt_node->getStringValue("name", "END"     ));
116      wpt->setLatitude   (wpt_node->getDoubleValue("lat", 0          ));
117      wpt->setLongitude  (wpt_node->getDoubleValue("lon", 0          ));
118      wpt->setAltitude   (wpt_node->getDoubleValue("alt", 0          ));
119      wpt->setSpeed      (wpt_node->getDoubleValue("ktas", 0         ));
120      wpt->setCrossat    (wpt_node->getDoubleValue("crossat", -10000 ));
121      wpt->setGear_down  (wpt_node->getBoolValue("gear-down", false  ));
122      wpt->setFlaps_down (wpt_node->getBoolValue("flaps-down", false ));
123      wpt->setOn_ground  (wpt_node->getBoolValue("on-ground", false  ));
124      wpt->setTime_sec   (wpt_node->getDoubleValue("time-sec", 0     ));
125      wpt->setTime       (wpt_node->getStringValue("time", ""        ));
126
127      if (wpt->getName() == "END") wpt->setFinished(true);
128      else wpt->setFinished(false);
129
130      pushBackWaypoint( wpt );
131    }
132
133   wpt_iterator = waypoints.begin();
134   isValid = true;
135   //cout << waypoints.size() << " waypoints read." << endl;
136 }
137
138
139 // This is a modified version of the constructor,
140 // Which not only reads the waypoints from a 
141 // Flight plan file, but also adds the current
142 // Position computed by the traffic manager, as well
143 // as setting speeds and altitude computed by the
144 // traffic manager. 
145 FGAIFlightPlan::FGAIFlightPlan(FGAIAircraft *ac,
146                                const std::string& p,
147                                double course,
148                                time_t start,
149                                FGAirport *dep,
150                                FGAirport *arr,
151                                bool firstLeg,
152                                double radius,
153                                double alt,
154                                double lat,
155                                double lon,
156                                double speed,
157                                const string& fltType,
158                                const string& acType,
159                                const string& airline)
160 {
161   sid = 0;
162   repeat = false;
163   leg = 10;
164   gateId=0;
165   taxiRoute = 0;
166   start_time = start;
167   bool useInitialWayPoint = true;
168   bool useCurrentWayPoint = false;
169   SGPath path( globals->get_fg_root() );
170   path.append( "/AI/FlightPlans" );
171   path.append( p );
172   
173   SGPropertyNode root;
174   isValid = true;
175   // This is a bit of a hack:
176   // Normally the value of course will be used to evaluate whether
177   // or not a waypoint will be used for midair initialization of 
178   // an AI aircraft. However, if a course value of 999 will be passed
179   // when an update request is received, which will by definition always be
180   // on the ground and should include all waypoints.
181   if (course == 999) 
182     {
183       useInitialWayPoint = false;
184       useCurrentWayPoint = true;
185     }
186
187   if (path.exists()) 
188     {
189       try 
190         {
191           readProperties(path.str(), &root);
192           
193           SGPropertyNode * node = root.getNode("flightplan");
194           
195           //pushBackWaypoint( init_waypoint );
196           for (int i = 0; i < node->nChildren(); i++) { 
197             //cout << "Reading waypoint " << i << endl;
198             FGAIWaypoint* wpt = new FGAIWaypoint;
199             SGPropertyNode * wpt_node = node->getChild(i);
200             wpt->setName       (wpt_node->getStringValue("name", "END"     ));
201             wpt->setLatitude   (wpt_node->getDoubleValue("lat", 0          ));
202             wpt->setLongitude  (wpt_node->getDoubleValue("lon", 0          ));
203             wpt->setAltitude   (wpt_node->getDoubleValue("alt", 0          ));
204             wpt->setSpeed      (wpt_node->getDoubleValue("ktas", 0         ));
205             wpt->setCrossat    (wpt_node->getDoubleValue("crossat", -10000 ));
206             wpt->setGear_down  (wpt_node->getBoolValue("gear-down", false  ));
207             wpt->setFlaps_down (wpt_node->getBoolValue("flaps-down", false ));
208             
209             if (wpt->getName() == "END") wpt->setFinished(true);
210             else wpt->setFinished(false);
211             pushBackWaypoint(wpt);
212           } // of node loop
213           wpt_iterator = waypoints.begin();
214         } catch (const sg_exception &e) {
215       SG_LOG(SG_AI, SG_WARN, "Error reading AI flight plan: " <<
216         e.getMessage() << " from " << e.getOrigin());
217     }
218   } else {
219       // cout << path.str() << endl;
220       // cout << "Trying to create this plan dynamically" << endl;
221       // cout << "Route from " << dep->id << " to " << arr->id << endl;
222       time_t now = time(NULL) + fgGetLong("/sim/time/warp");
223       time_t timeDiff = now-start; 
224       leg = 1;
225       
226       if ((timeDiff > 60) && (timeDiff < 1500))
227         leg = 2;
228       //else if ((timeDiff >= 1200) && (timeDiff < 1500)) {
229         //leg = 3;
230         //ac->setTakeOffStatus(2);
231       //}
232       else if ((timeDiff >= 1500) && (timeDiff < 2000))
233         leg = 4;
234       else if (timeDiff >= 2000)
235         leg = 5;
236       /*
237       if (timeDiff >= 2000)
238           leg = 5;
239       */
240       SG_LOG(SG_AI, SG_INFO, "Route from " << dep->getId() << " to " << arr->getId() << ". Set leg to : " << leg << " " << ac->getTrafficRef()->getCallSign());
241       wpt_iterator = waypoints.begin();
242       bool dist = 0;
243       isValid = create(ac, dep,arr, leg, alt, speed, lat, lon,
244              firstLeg, radius, fltType, acType, airline, dist);
245       wpt_iterator = waypoints.begin();
246     }
247
248 }
249
250
251
252
253 FGAIFlightPlan::~FGAIFlightPlan()
254 {
255   deleteWaypoints();
256   delete taxiRoute;
257 }
258
259
260 FGAIWaypoint* const FGAIFlightPlan::getPreviousWaypoint( void ) const
261 {
262   if (wpt_iterator == waypoints.begin()) {
263     return 0;
264   } else {
265     wpt_vector_iterator prev = wpt_iterator;
266     return *(--prev);
267   }
268 }
269
270 FGAIWaypoint* const FGAIFlightPlan::getCurrentWaypoint( void ) const
271 {
272   return *wpt_iterator;
273 }
274
275 FGAIWaypoint* const FGAIFlightPlan::getNextWaypoint( void ) const
276 {
277   wpt_vector_iterator i = waypoints.end();
278   i--;  // end() points to one element after the last one. 
279   if (wpt_iterator == i) {
280     return 0;
281   } else {
282     wpt_vector_iterator next = wpt_iterator;
283     return *(++next);
284   }
285 }
286
287 void FGAIFlightPlan::IncrementWaypoint(bool eraseWaypoints )
288 {
289   if (eraseWaypoints)
290     {
291       if (wpt_iterator == waypoints.begin())
292         wpt_iterator++;
293       else
294         {
295           delete *(waypoints.begin());
296           waypoints.erase(waypoints.begin());
297           wpt_iterator = waypoints.begin();
298           wpt_iterator++;
299         }
300     }
301   else
302     wpt_iterator++;
303
304 }
305
306 void FGAIFlightPlan::DecrementWaypoint(bool eraseWaypoints )
307 {
308     if (eraseWaypoints)
309     {
310         if (wpt_iterator == waypoints.end())
311             wpt_iterator--;
312         else
313         {
314             delete *(waypoints.end());
315             waypoints.erase(waypoints.end());
316             wpt_iterator = waypoints.end();
317             wpt_iterator--;
318         }
319     }
320     else
321         wpt_iterator--;
322 }
323
324 void FGAIFlightPlan::eraseLastWaypoint()
325 {
326     delete (waypoints.back());
327     waypoints.pop_back();;
328     wpt_iterator = waypoints.begin();
329     wpt_iterator++;
330 }
331
332
333
334
335 // gives distance in feet from a position to a waypoint
336 double FGAIFlightPlan::getDistanceToGo(double lat, double lon, FGAIWaypoint* wp) const{
337   return SGGeodesy::distanceM(SGGeod::fromDeg(lon, lat), 
338       SGGeod::fromDeg(wp->getLongitude(), wp->getLatitude()));
339 }
340
341 // sets distance in feet from a lead point to the current waypoint
342 void FGAIFlightPlan::setLeadDistance(double speed, double bearing, 
343                                      FGAIWaypoint* current, FGAIWaypoint* next){
344   double turn_radius;
345   // Handle Ground steering
346   // At a turn rate of 30 degrees per second, it takes 12 seconds to do a full 360 degree turn
347   // So, to get an estimate of the turn radius, calculate the cicumference of the circle
348   // we travel on. Get the turn radius by dividing by PI (*2).
349   if (speed < 0.5) {
350         lead_distance = 0.5;
351         return;
352   }
353   if (speed < 25) {
354        turn_radius = ((360/30)*fabs(speed)) / (2*M_PI);
355   } else 
356       turn_radius = 0.1911 * speed * speed; // an estimate for 25 degrees bank
357
358   double inbound = bearing;
359   double outbound = getBearing(current, next);
360   leadInAngle = fabs(inbound - outbound);
361   if (leadInAngle > 180.0) 
362     leadInAngle = 360.0 - leadInAngle;
363   //if (leadInAngle < 30.0) // To prevent lead_dist from getting so small it is skipped 
364   //  leadInAngle = 30.0;
365   
366   //lead_distance = turn_radius * sin(leadInAngle * SG_DEGREES_TO_RADIANS); 
367   lead_distance = turn_radius * tan((leadInAngle * SG_DEGREES_TO_RADIANS)/2);
368   /*
369   if ((lead_distance > (3*turn_radius)) && (current->on_ground == false)) {
370       // cerr << "Warning: Lead-in distance is large. Inbound = " << inbound
371       //      << ". Outbound = " << outbound << ". Lead in angle = " << leadInAngle  << ". Turn radius = " << turn_radius << endl;
372        lead_distance = 3 * turn_radius;
373        return;
374   }
375   if ((leadInAngle > 90) && (current->on_ground == true)) {
376       lead_distance = turn_radius * tan((90 * SG_DEGREES_TO_RADIANS)/2);
377       return;
378   }*/
379 }
380
381 void FGAIFlightPlan::setLeadDistance(double distance_ft){
382   lead_distance = distance_ft;
383 }
384
385
386 double FGAIFlightPlan::getBearing(FGAIWaypoint* first, FGAIWaypoint* second) const{
387   return getBearing(first->getLatitude(), first->getLongitude(), second);
388 }
389
390
391 double FGAIFlightPlan::getBearing(double lat, double lon, FGAIWaypoint* wp) const{
392   return SGGeodesy::courseDeg(SGGeod::fromDeg(lon, lat), 
393       SGGeod::fromDeg(wp->getLongitude(), wp->getLatitude()));
394 }
395
396 void FGAIFlightPlan::deleteWaypoints()
397 {
398   for (wpt_vector_iterator i = waypoints.begin(); i != waypoints.end();i++)
399     delete (*i);
400   waypoints.clear();
401 }
402
403 // Delete all waypoints except the last, 
404 // which we will recycle as the first waypoint in the next leg;
405 void FGAIFlightPlan::resetWaypoints()
406 {
407   if (waypoints.begin() == waypoints.end())
408     return;
409   else
410     {
411       FGAIWaypoint *wpt = new FGAIWaypoint;
412       wpt_vector_iterator i = waypoints.end();
413       i--;
414       wpt->setName        ( (*i)->getName()       );
415       wpt->setLatitude    ( (*i)->getLatitude()   );
416       wpt->setLongitude   ( (*i)->getLongitude()  );
417       wpt->setAltitude    ( (*i)->getAltitude()   );
418       wpt->setSpeed       ( (*i)->getSpeed()      );
419       wpt->setCrossat     ( (*i)->getCrossat()    );
420       wpt->setGear_down   ( (*i)->getGear_down()  );
421       wpt->setFlaps_down  ( (*i)->getFlaps_down() );
422       wpt->setFinished    ( false                 );
423       wpt->setOn_ground   ( (*i)->getOn_ground()  );
424       //cerr << "Recycling waypoint " << wpt->name << endl;
425       deleteWaypoints();
426       pushBackWaypoint(wpt);
427     }
428 }
429
430 void FGAIFlightPlan::pushBackWaypoint(FGAIWaypoint *wpt)
431 {
432   // std::vector::push_back invalidates waypoints
433   //  so we should restore wpt_iterator after push_back
434   //  (or it could be an index in the vector)
435   size_t pos = wpt_iterator - waypoints.begin();
436   waypoints.push_back(wpt);
437   wpt_iterator = waypoints.begin() + pos;
438 }
439
440 // Start flightplan over from the beginning
441 void FGAIFlightPlan::restart()
442 {
443   wpt_iterator = waypoints.begin();
444 }
445
446
447 void FGAIFlightPlan::deleteTaxiRoute() 
448 {
449   delete taxiRoute;
450   taxiRoute = 0;
451 }
452
453
454 int FGAIFlightPlan::getRouteIndex(int i) {
455   if ((i > 0) && (i < (int)waypoints.size())) {
456     return waypoints[i]->getRouteIndex();
457   }
458   else
459     return 0;
460 }
461
462
463 double FGAIFlightPlan::checkTrackLength(string wptName) {
464     // skip the first two waypoints: first one is behind, second one is partially done;
465     double trackDistance = 0;
466     wpt_vector_iterator wptvec = waypoints.begin();
467     wptvec++;
468     wptvec++;
469     while ((wptvec != waypoints.end()) && (!((*wptvec)->contains(wptName)))) {
470            trackDistance += (*wptvec)->getTrackLength();
471            wptvec++;
472     }
473     if (wptvec == waypoints.end()) {
474         trackDistance = 0; // name not found
475     }
476     return trackDistance;
477 }
478
479 void FGAIFlightPlan::shortenToFirst(unsigned int number, string name)
480 {
481     while (waypoints.size() > number + 3) {
482         eraseLastWaypoint();
483     }
484     (waypoints.back())->setName((waypoints.back())->getName() + name);
485 }