]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIAircraft.cxx
Mathias Froehlich:
[flightgear.git] / src / AIModel / AIAircraft.cxx
1 // FGAIAircraft - FGAIBase-derived class creates an AI airplane
2 //
3 // Written by David Culp, started October 2003.
4 //
5 // Copyright (C) 2003  David P. Culp - davidculp2@comcast.net
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24
25 #include <simgear/math/point3d.hxx>
26 #include <simgear/route/waypoint.hxx>
27 #include <Main/fg_props.hxx>
28 #include <Main/globals.hxx>
29 #include <Main/viewer.hxx>
30 #include <Scenery/scenery.hxx>
31 #include <Scenery/tilemgr.hxx>
32
33 #include <string>
34 #include <math.h>
35 #include <time.h>
36 #ifdef _MSC_VER
37 #  include <float.h>
38 #  define finite _finite
39 #elif defined(__sun) || defined(sgi)
40 #  include <ieeefp.h>
41 #endif
42
43 SG_USING_STD(string);
44
45 #include "AIAircraft.hxx"
46    static string tempReg;
47 //
48 // accel, decel, climb_rate, descent_rate, takeoff_speed, climb_speed,
49 // cruise_speed, descent_speed, land_speed
50 //
51 const FGAIAircraft::PERF_STRUCT FGAIAircraft::settings[] = {
52     // light aircraft
53     {2.0, 2.0,  450.0, 1000.0,  70.0,  80.0, 100.0,  80.0,  60.0},
54     // ww2_fighter
55     {4.0, 2.0, 3000.0, 1500.0, 110.0, 180.0, 250.0, 200.0, 100.0},
56     // jet_transport
57     {5.0, 2.0, 3000.0, 1500.0, 140.0, 300.0, 430.0, 300.0, 130.0},
58     // jet_fighter
59     {7.0, 3.0, 4000.0, 2000.0, 150.0, 350.0, 500.0, 350.0, 150.0},
60     // tanker
61     {5.0, 2.0, 3000.0, 1500.0, 140.0, 300.0, 430.0, 300.0, 130.0}
62 };
63
64
65 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
66   FGAIBase(otAircraft) {
67   trafficRef = ref;
68   if (trafficRef)
69     groundOffset = trafficRef->getGroundOffset();
70   else
71     groundOffset = 0;
72    fp = 0;
73    dt_count = 0;
74    dt_elev_count = 0;
75    use_perf_vs = true;
76    isTanker = false;
77
78    // set heading and altitude locks
79    hdg_lock = false;
80    alt_lock = false;
81    roll = 0;
82    headingChangeRate = 0.0;
83 }
84
85
86 FGAIAircraft::~FGAIAircraft() {
87   delete fp;
88 }
89
90 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
91   if (!scFileNode)
92     return;
93
94   FGAIBase::readFromScenario(scFileNode);
95
96   setPerformance(scFileNode->getStringValue("class", "jet_transport"));
97   setFlightPlan(scFileNode->getStringValue("flightplan"),
98                 scFileNode->getBoolValue("repeat", false));
99 }
100
101 bool FGAIAircraft::init() {
102    refuel_node = fgGetNode("systems/refuel/contact", true);
103    return FGAIBase::init();
104 }
105
106 void FGAIAircraft::bind() {
107     FGAIBase::bind();
108
109     props->tie("controls/gear/gear-down",
110                SGRawValueMethods<FGAIAircraft,bool>(*this,
111                                               &FGAIAircraft::_getGearDown));
112 }
113
114 void FGAIAircraft::unbind() {
115     FGAIBase::unbind();
116
117     props->untie("controls/gear/gear-down");
118 }
119
120
121 void FGAIAircraft::update(double dt) {
122
123    FGAIBase::update(dt);
124    Run(dt);
125    Transform();
126 }
127
128 void FGAIAircraft::setPerformance(const std::string& acclass)
129 {
130   if (acclass == "light") {
131     SetPerformance(&FGAIAircraft::settings[FGAIAircraft::LIGHT]);
132   } else if (acclass == "ww2_fighter") {
133     SetPerformance(&FGAIAircraft::settings[FGAIAircraft::WW2_FIGHTER]);
134   } else if (acclass ==  "jet_transport") {
135     SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
136   } else if (acclass == "jet_fighter") {
137     SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_FIGHTER]);
138   } else if (acclass ==  "tanker") {
139     SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
140     SetTanker(true);
141   } else {
142     SetPerformance(&FGAIAircraft::settings[FGAIAircraft::JET_TRANSPORT]);
143   }
144 }
145
146 void FGAIAircraft::SetPerformance(const PERF_STRUCT *ps) {
147    
148    performance = ps;
149
150
151
152 void FGAIAircraft::Run(double dt) {
153
154    FGAIAircraft::dt = dt;
155
156    if (fp) 
157      {
158        time_t now = time(NULL) + fgGetLong("/sim/time/warp");
159        ProcessFlightPlan(dt, now);
160        if (now < fp->getStartTime())
161          {
162            // Do execute Ground elev for inactive aircraft, so they
163            // Are repositioned to the correct ground altitude when the user flies within visibility range.
164            if (no_roll)
165              {
166                Transform();         // make sure aip is initialized.
167                getGroundElev(dt); // make sure it's exectuted first time around, so force a large dt value
168                //getGroundElev(dt); // Need to do this twice.
169                //cerr << trafficRef->getRegistration() << " Setting altitude to " << tgt_altitude;
170                doGroundAltitude();
171                //cerr << " Actual altitude " << altitude << endl;
172                // Transform(); 
173                pos.setelev(altitude * SG_FEET_TO_METER);
174              }
175            return;
176          }
177      }
178   
179    double turn_radius_ft;
180    double turn_circum_ft;
181    double speed_north_deg_sec;
182    double speed_east_deg_sec;
183    double dist_covered_ft;
184    double alpha;
185
186    // adjust speed
187    double speed_diff; //= tgt_speed - speed;
188    if (!no_roll)
189      {
190        speed_diff = tgt_speed - speed;
191      }
192    else
193      {
194        speed_diff = groundTargetSpeed - speed;
195      }
196    if (fabs(speed_diff) > 0.2) {
197      if (speed_diff > 0.0) speed += performance->accel * dt;
198      if (speed_diff < 0.0) {
199        if (no_roll) { // was (!no_roll) but seems more logical this way (ground brakes).
200            speed -= performance->decel * dt * 3;
201         } else {
202            speed -= performance->decel * dt;
203         }
204      }
205    } 
206    
207    // convert speed to degrees per second
208    speed_north_deg_sec = cos( hdg / SG_RADIANS_TO_DEGREES )
209                           * speed * 1.686 / ft_per_deg_lat;
210    speed_east_deg_sec  = sin( hdg / SG_RADIANS_TO_DEGREES )
211                           * speed * 1.686 / ft_per_deg_lon;
212
213    // set new position
214    pos.setlat( pos.lat() + speed_north_deg_sec * dt);
215    pos.setlon( pos.lon() + speed_east_deg_sec * dt); 
216    //if (!(finite(pos.lat()) && finite(pos.lon())))
217    //  {
218    //    cerr << "Position is not finite" << endl;
219    //    cerr << "speed = " << speed << endl;
220    //    cerr << "dt" << dt << endl;
221    //    cerr << "heading " << hdg << endl;
222    //    cerr << "speed east " << speed_east_deg_sec << endl;
223    //    cerr << "speed nrth " << speed_north_deg_sec << endl;
224    //    cerr << "deg_lat    " << ft_per_deg_lat << endl;
225    //    cerr << "deg_lon    " << ft_per_deg_lon << endl;
226    //  }
227
228    // adjust heading based on current bank angle
229    if (roll == 0.0) 
230      roll = 0.01;
231    if (roll != 0.0) {
232      // double turnConstant;
233      //if (no_roll)
234      //  turnConstant = 0.0088362;
235      //else 
236      //  turnConstant = 0.088362;
237      // If on ground, calculate heading change directly
238      if (no_roll) {
239        double headingDiff = fabs(hdg-tgt_heading);
240       
241        if (headingDiff > 180)
242          headingDiff = fabs(headingDiff - 360);
243        groundTargetSpeed = tgt_speed - (tgt_speed * (headingDiff/45));
244        if (sign(groundTargetSpeed) != sign(tgt_speed))
245          groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
246        if (headingDiff > 30.0)
247          {
248            
249            headingChangeRate += dt * sign(roll); // invert if pushed backward
250            // Print some debug statements to find out why aircraft may get stuck
251            // forever turning
252            //if (trafficRef->getDepartureAirport()->getId() == string("EHAM"))
253            //  {
254            //cerr << "Turning : " << trafficRef->getRegistration()
255            //cerr <<  " Speed = " << speed << " Heading " << hdg 
256            //<< " Target Heading " << tgt_heading 
257            //   << " Lead Distance " <<  fp->getLeadDistance()
258            //   << " Distance to go " 
259            //   << fp->getDistanceToGo(pos.lat(), pos.lon(), fp->getCurrentWaypoint())
260            //   << "waypoint name " << fp->getCurrentWaypoint()->name
261            //   << endl;
262            //}
263            if (headingChangeRate > 30) 
264              { 
265                headingChangeRate = 30;
266              }
267            else if (headingChangeRate < -30)
268              {
269                headingChangeRate = -30;
270              }
271          }
272        else
273          {
274            if (fabs(headingChangeRate) > headingDiff)
275              headingChangeRate = headingDiff*sign(roll);
276            else
277              headingChangeRate += dt * sign(roll);
278          }
279        hdg += headingChangeRate * dt;
280        //cerr << "On ground. Heading: " << hdg << ". Target Heading: " << tgt_heading << ". Target speed: " << groundTargetSpeed << ". heading change rate" << headingChangeRate << endl;
281      }
282      else {
283        if (fabs(speed) > 1.0) {
284          turn_radius_ft = 0.088362 * speed * speed
285            / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
286        }
287        else
288          {
289            turn_radius_ft = 1.0; // Check if turn_radius_ft == 0; this might lead to a division by 0.
290          }
291        turn_circum_ft = SGD_2PI * turn_radius_ft;
292        dist_covered_ft = speed * 1.686 * dt; 
293        alpha = dist_covered_ft / turn_circum_ft * 360.0;
294        hdg += alpha * sign(roll);
295      }
296      while ( hdg > 360.0 ) {
297        hdg -= 360.0;
298        spinCounter++;
299      }
300      while ( hdg < 0.0) 
301        {
302          hdg += 360.0;
303          spinCounter--;
304        }
305    }
306      
307    
308    // adjust target bank angle if heading lock engaged
309    if (hdg_lock) {
310      double bank_sense = 0.0;
311      double diff = fabs(hdg - tgt_heading);
312      if (diff > 180) diff = fabs(diff - 360);
313      double sum = hdg + diff;
314      if (sum > 360.0) sum -= 360.0;
315      if (fabs(sum - tgt_heading) < 1.0) {
316        bank_sense = 1.0;   // right turn
317      } else {
318        bank_sense = -1.0;  // left turn
319      } 
320      if (diff < 30) {
321          tgt_roll = diff * bank_sense; 
322      } else {
323          tgt_roll = 30.0 * bank_sense;
324      }
325      if ((fabs((double) spinCounter) > 1) && (diff > 30))
326        {
327          tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
328          // The only way to resolve this is to make them slow down. 
329          //if (tempReg.empty())
330          //  tempReg = trafficRef->getRegistration();
331          //if (trafficRef->getRegistration() == tempReg)
332          //  {
333          //    cerr << trafficRef->getRegistration() 
334          //       << " appears to be spinning: " << spinCounter << endl
335          //       << " speed          " << speed << endl
336          //       << " heading        " << hdg << endl
337          //       << " lead distance  " << fp->getLeadDistance() << endl
338          //       << " waypoint       " << fp->getCurrentWaypoint()->name
339          //       << " target heading " << tgt_heading << endl
340          //       << " lead in angle  " << fp->getLeadInAngle()<< endl
341          //       << " roll           " << roll << endl
342          //       << " target_roll    " << tgt_roll << endl;
343              
344          //  }
345        }
346    }
347
348    // adjust bank angle, use 9 degrees per second
349    double bank_diff = tgt_roll - roll;
350    if (fabs(bank_diff) > 0.2) {
351      if (bank_diff > 0.0) roll += 9.0 * dt;
352      if (bank_diff < 0.0) roll -= 9.0 * dt;
353      //while (roll > 180) roll -= 360;
354      //while (roll < 180) roll += 360;
355    }
356
357    // adjust altitude (meters) based on current vertical speed (fpm)
358    altitude += vs / 60.0 * dt;
359    pos.setelev(altitude * SG_FEET_TO_METER);  
360    double altitude_ft = altitude;
361
362    // adjust target Altitude, based on ground elevation when on ground
363    if (no_roll)
364      {
365        getGroundElev(dt);
366        doGroundAltitude();
367      }
368    else
369      {
370        // find target vertical speed if altitude lock engaged
371        if (alt_lock && use_perf_vs) {
372          if (altitude_ft < tgt_altitude) {
373            tgt_vs = tgt_altitude - altitude_ft;
374            if (tgt_vs > performance->climb_rate)
375              tgt_vs = performance->climb_rate;
376          } else {
377            tgt_vs = tgt_altitude - altitude_ft;
378            if (tgt_vs  < (-performance->descent_rate))
379              tgt_vs = -performance->descent_rate;
380          }
381        }
382        
383        if (alt_lock && !use_perf_vs) {
384          double max_vs = 4*(tgt_altitude - altitude);
385          double min_vs = 100;
386          if (tgt_altitude < altitude) min_vs = -100.0;
387          if ((fabs(tgt_altitude - altitude) < 1500.0) && 
388              (fabs(max_vs) < fabs(tgt_vs))) tgt_vs = max_vs;
389          if (fabs(tgt_vs) < fabs(min_vs)) tgt_vs = min_vs;
390        }   
391      }
392    // adjust vertical speed
393    double vs_diff = tgt_vs - vs;
394    if (fabs(vs_diff) > 10.0) {
395      if (vs_diff > 0.0) {
396        vs += 900.0 * dt;
397        if (vs > tgt_vs) vs = tgt_vs;
398      } else {
399        vs -= 400.0 * dt;
400        if (vs < tgt_vs) vs = tgt_vs;
401      }
402    }   
403    
404    // match pitch angle to vertical speed
405    if (vs > 0){
406      pitch = vs * 0.005;
407    } else {
408      pitch = vs * 0.002;
409    }
410
411    //###########################//
412    // do calculations for radar //
413    //###########################//
414    double range_ft2 = UpdateRadar(manager);
415
416    //************************************//
417    // Tanker code                        //
418    //************************************//
419
420    if ( isTanker) {
421      if ( (range_ft2 < 250.0 * 250.0) &&
422           (y_shift > 0.0)    &&
423           (elevation > 0.0) ) {
424        refuel_node->setBoolValue(true);
425      } else {
426        refuel_node->setBoolValue(false);
427      } 
428    }
429 }
430
431
432 void FGAIAircraft::AccelTo(double speed) {
433    tgt_speed = speed;
434 }
435
436
437 void FGAIAircraft::PitchTo(double angle) {
438    tgt_pitch = angle;
439    alt_lock = false;
440 }
441
442
443 void FGAIAircraft::RollTo(double angle) {
444    tgt_roll = angle;
445    hdg_lock = false; 
446 }
447
448
449 void FGAIAircraft::YawTo(double angle) {
450    tgt_yaw = angle;
451 }
452
453
454 void FGAIAircraft::ClimbTo(double altitude) {
455    tgt_altitude = altitude;
456    alt_lock = true;
457 }
458
459
460 void FGAIAircraft::TurnTo(double heading) {
461    tgt_heading = heading;
462    hdg_lock = true;
463 }
464
465
466 double FGAIAircraft::sign(double x) {
467   if ( x < 0.0 ) { return -1.0; }
468   else { return 1.0; }
469 }
470
471 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat)
472 {
473   if (!flightplan.empty()){
474     FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
475     fp->setRepeat(repeat);
476     SetFlightPlan(fp);
477   }
478 }
479
480 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
481   delete fp;
482   fp = f;
483 }
484
485 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) 
486 {
487   bool eraseWaypoints;
488   if (trafficRef)
489     {
490 //       FGAirport *arr;
491 //       FGAirport *dep;
492       eraseWaypoints = true;
493 //       cerr << trafficRef->getRegistration();
494 //       cerr << "Departure airport " << endl;
495 //       dep = trafficRef->getDepartureAirport();
496 //       if (dep)
497 //      cerr << dep->getId() << endl;
498 //       cerr << "Arrival   airport " << endl;
499 //       arr = trafficRef->getArrivalAirport();
500 //       if (arr)
501 //      cerr << arr->getId() <<endl << endl;;
502      }
503   else
504     eraseWaypoints = false;
505
506   //cerr << "Processing Flightplan" << endl;
507   FGAIFlightPlan::waypoint* prev = 0; // the one behind you
508   FGAIFlightPlan::waypoint* curr = 0; // the one ahead
509   FGAIFlightPlan::waypoint* next = 0; // the next plus 1
510   prev = fp->getPreviousWaypoint();
511   curr = fp->getCurrentWaypoint();
512   next = fp->getNextWaypoint();
513   dt_count += dt;
514   
515   if (!prev) {  //beginning of flightplan, do this initialization once
516     //setBank(0.0);
517     spinCounter = 0;
518     tempReg = "";
519     //prev_dist_to_go = HUGE;
520     //cerr << "Before increment " << curr-> name << endl;
521     fp->IncrementWaypoint(eraseWaypoints); 
522     //prev = fp->getPreviousWaypoint(); //first waypoint
523     //curr = fp->getCurrentWaypoint();  //second waypoint
524     //next = fp->getNextWaypoint();     //third waypoint (might not exist!) 
525     //cerr << "After increment " << prev-> name << endl;
526     if (!(fp->getNextWaypoint()) && trafficRef)
527       {
528         loadNextLeg();
529       }
530     //cerr << "After load " << prev-> name << endl;
531     prev = fp->getPreviousWaypoint(); //first waypoint
532     curr = fp->getCurrentWaypoint();  //second waypoint
533     next = fp->getNextWaypoint();     //third waypoint (might not exist!) 
534     //cerr << "After load " << prev-> name << endl;
535     setLatitude(prev->latitude);
536     setLongitude(prev->longitude);
537     setSpeed(prev->speed);
538     setAltitude(prev->altitude);
539     if (prev->speed > 0.0)
540       setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
541     else
542       {
543         setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
544       }
545     // If next doesn't exist, as in incrementally created flightplans for 
546     // AI/Trafficmanager created plans, 
547     // Make sure lead distance is initialized otherwise
548     if (next) 
549       fp->setLeadDistance(speed, hdg, curr, next);
550     
551     if (curr->crossat > -1000.0) { //use a calculated descent/climb rate
552       use_perf_vs = false;
553       tgt_vs = (curr->crossat - prev->altitude)/
554         (fp->getDistanceToGo(pos.lat(), pos.lon(), curr)/
555            6076.0/prev->speed*60.0);
556       tgt_altitude = curr->crossat;
557     } else {
558       use_perf_vs = true;
559       tgt_altitude = prev->altitude;
560     }
561     alt_lock = hdg_lock = true;
562     no_roll = prev->on_ground;
563     if (no_roll)
564       {
565         Transform();         // make sure aip is initialized.
566         getGroundElev(60.1); // make sure it's exectuted first time around, so force a large dt value
567         //getGroundElev(60.1); // Need to do this twice.
568         //cerr << trafficRef->getRegistration() << " Setting altitude to " << tgt_altitude << endl;
569         doGroundAltitude(); //(tgt_altitude);
570       }
571     prevSpeed = 0;
572     //cout << "First waypoint:  " << prev->name << endl;
573     //cout << "  Target speed:    " << tgt_speed << endl;
574     //cout << "  Target altitude: " << tgt_altitude << endl;
575     //cout << "  Target heading:  " << tgt_heading << endl << endl;       
576     //cerr << "Done Flightplan init" << endl;
577     return;  
578   } // end of initialization
579   
580   // let's only process the flight plan every 100 ms.
581   if ((dt_count < 0.1) || (now < fp->getStartTime()))
582     {
583       //cerr  << "done fp dt" << endl;
584       return;
585     } else {
586       dt_count = 0;
587     }
588   // check to see if we've reached the lead point for our next turn
589   double dist_to_go = fp->getDistanceToGo(pos.lat(), pos.lon(), curr);
590   
591   //cerr << "2" << endl;
592   double lead_dist = fp->getLeadDistance();
593   //cerr << " Distance : " << dist_to_go << ": Lead distance " << lead_dist << endl;
594   // experimental: Use fabs, because speed can be negative (I hope) during push_back.
595   if (lead_dist < fabs(2*speed)) 
596     {
597       lead_dist = fabs(2*speed);  //don't skip over the waypoint
598       //cerr << "Extending lead distance to " << lead_dist << endl;
599     } 
600 //   FGAirport * apt = trafficRef->getDepartureAirport();
601 //   if ((dist_to_go > prev_dist_to_go) && trafficRef && apt)
602 //     {
603 //       if (apt->getId() == string("EHAM"))
604 //      cerr << "Alert: " << trafficRef->getRegistration() << " is moving away from waypoint " << curr->name  << endl
605 //           << "Target heading : " << tgt_heading << "act heading " << hdg << " Tgt speed : " << tgt_speed << endl
606 //           << "Lead distance : " << lead_dist  << endl
607 //           << "Distance to go: " << dist_to_go << endl;
608       
609 //     }
610   prev_dist_to_go = dist_to_go;
611   //cerr << "2" << endl;
612   //if (no_roll)
613   //  lead_dist = 10.0;
614   //cout << "Leg : " << (fp->getLeg()-1) << ". dist_to_go: " << dist_to_go << ",  lead_dist: " << lead_dist << ", tgt_speed " << tgt_speed << ", tgt_heading " << tgt_heading << " speed " << speed << " hdg " << hdg << ". Altitude "  << altitude << " TAget alt :" << tgt_altitude << endl;
615   
616   if ( dist_to_go < lead_dist ) {
617     //prev_dist_to_go = HUGE;
618     // For traffic manager generated aircraft: 
619     // check if the aircraft flies of of user range. And adjust the
620     // Current waypoint's elevation according to Terrain Elevation
621     if (curr->finished) {  //end of the flight plan
622       {
623          if (fp->getRepeat()) {
624            fp->restart();
625          } else {   
626           setDie(true);
627          } 
628
629         //cerr << "Done die end of fp" << endl;
630       }
631       return;
632     }
633     
634     // we've reached the lead-point for the waypoint ahead 
635     //cerr << "4" << endl;
636     //cerr << "Situation after lead point" << endl;
637     //cerr << "Prviious: " << prev->name << endl;
638     //cerr << "Current : " << curr->name << endl;
639     //cerr << "Next    : " << next->name << endl;
640     if (next) 
641       {
642         tgt_heading = fp->getBearing(curr, next);  
643         spinCounter = 0;
644       }
645     fp->IncrementWaypoint(eraseWaypoints);
646     if (!(fp->getNextWaypoint()) && trafficRef)
647       {
648         loadNextLeg();
649       }
650     prev = fp->getPreviousWaypoint();
651     curr = fp->getCurrentWaypoint();
652     next = fp->getNextWaypoint();
653     // Now that we have incremented the waypoints, excute some traffic manager specific code
654     // based on the name of the waypoint we just passed.
655     if (trafficRef)
656       { 
657         double userLatitude  = fgGetDouble("/position/latitude-deg");
658         double userLongitude = fgGetDouble("/position/longitude-deg");
659         double course, distance;
660         SGWayPoint current  (pos.lon(),
661                              pos.lat(),
662                              0);
663         SGWayPoint user (   userLongitude,
664                             userLatitude,
665                             0);
666         user.CourseAndDistance(current, &course, &distance);
667         if ((distance * SG_METER_TO_NM) > TRAFFICTOAIDIST)
668           {
669             setDie(true);
670             //cerr << "done fp die out of range" << endl;
671             return;
672           }
673         
674         FGAirport * dep = trafficRef->getDepartureAirport();
675         FGAirport * arr = trafficRef->getArrivalAirport();
676         // At parking the beginning of the airport
677         if (!( dep && arr))
678           {
679             setDie(true);
680             return;
681           }
682         //if ((dep->getId() == string("EHAM") || (arr->getId() == string("EHAM"))))
683         //  {
684         //      cerr << trafficRef->getRegistration() 
685         //           << " Enroute from " << dep->getId() 
686         //           << " to "           << arr->getId()
687         //           << " just crossed " << prev->name
688         //           << " Assigned rwy     " << fp->getRunwayId()
689         //           << " " << fp->getRunway() << endl;
690         // }
691         //if ((dep->getId() == string("EHAM")) && (prev->name == "park2"))
692         //  {
693         //    cerr << "Schiphol ground " 
694         //       << trafficRef->getCallSign();
695         //    if (trafficRef->getHeavy())
696         //      cerr << "Heavy";
697         //    cerr << ", is type " 
698         //       << trafficRef->getAircraft()
699         //       << " ready to go. IFR to "
700         //       << arr->getId() <<endl;
701         //  }   
702         if (prev->name == "park2")
703           {
704             dep->getDynamics()->releaseParking(fp->getGate());
705           }
706         // Some debug messages, specific to TESTING THE Logical networks.
707         //if ((arr->getId() == string("EHAM")) && (prev->name  == "Center"))
708         //  {
709         //    
710         //    cerr << "Schiphol ground " 
711         //       << trafficRef->getCallSign();
712         //    if (trafficRef->getHeavy())
713         //      cerr << "Heavy";
714         //    cerr << " landed runway " 
715         //       << fp->getRunway()
716         //       << " request taxi to gate " 
717         //       << arr->getParkingName(fp->getGate()) 
718         //       << endl;
719         //  }
720         if (prev->name == "END")
721           fp->setTime(trafficRef->getDepartureTime());
722         //cerr << "5" << endl;
723       }
724     if (next) 
725       {
726         //cerr << "Current waypoint" << curr->name << endl;
727         //cerr << "Next waypoint" << next->name << endl;
728         fp->setLeadDistance(speed, tgt_heading, curr, next);
729       }
730     //cerr << "5.1" << endl;
731     if (!(prev->on_ground)) { // only update the tgt altitude from flightplan if not on the ground
732       tgt_altitude = prev->altitude;
733       if (curr->crossat > -1000.0) {
734         //cerr << "5.1a" << endl;
735         use_perf_vs = false;
736         tgt_vs = (curr->crossat - altitude)/
737           (fp->getDistanceToGo(pos.lat(), pos.lon(), curr)/6076.0/speed*60.0);
738         //cerr << "5.1b" << endl;
739         tgt_altitude = curr->crossat;
740       } else {
741         //cerr << "5.1c" << endl;
742         use_perf_vs = true;
743         //cerr << "5.1d" << endl;       
744         
745         //cerr << "Setting target altitude : " <<tgt_altitude << endl;
746       }
747     }
748     //cerr << "6" << endl;
749     tgt_speed = prev->speed;
750     hdg_lock = alt_lock = true;
751     no_roll = prev->on_ground;
752     //cout << "Crossing waypoint: " << prev->name << endl;
753     //cout << "  Target speed:    " << tgt_speed << endl;
754     //cout << "  Target altitude: " << tgt_altitude << endl;
755     //cout << "  Target heading:  " << tgt_heading << endl << endl;       
756   } else {
757     
758     double calc_bearing = fp->getBearing(pos.lat(), pos.lon(), curr);
759     //cerr << "Bearing = " << calc_bearing << endl;
760     if (speed < 0)
761       {
762         calc_bearing +=180;
763         if (calc_bearing > 360)
764           calc_bearing -= 360;
765       }
766     if (finite(calc_bearing))
767       {
768         double hdg_error = calc_bearing - tgt_heading;
769         if (fabs(hdg_error) > 1.0) {
770           TurnTo( calc_bearing ); 
771         }
772       }
773     else
774       {
775         cerr << "calc_bearing is not a finite number : "
776              << "Speed " << speed
777              << "pos : " << pos.lat() << ", " << pos.lon()
778              << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
779         cerr << "waypoint name " << curr->name;
780         exit(1);
781       }
782     double speed_diff = speed - prevSpeed;
783     // Update the lead distance calculation if speed has changed sufficiently
784     // to prevent spinning (hopefully);
785     if (fabs(speed_diff) > 10)
786       { 
787         prevSpeed = speed;
788         fp->setLeadDistance(speed, tgt_heading, curr, next);
789       }
790     
791     //cerr << "Done Processing FlightPlan"<< endl;
792   } // if (dt count) else
793 }
794
795   bool FGAIAircraft::_getGearDown() const {
796    return ((props->getFloatValue("position/altitude-agl-ft") < 900.0)
797             && (props->getFloatValue("velocities/airspeed-kt")
798                  < performance->land_speed*1.25));
799 }
800
801
802 void FGAIAircraft::loadNextLeg() 
803 {
804   //delete fp;
805   //time_t now = time(NULL) + fgGetLong("/sim/time/warp");
806   
807   
808   //FGAIModelEntity entity;
809   //entity.m_class = "jet_transport";
810   //entity.path = modelPath.c_str();
811   //entity.flightplan = "none";
812   //entity.latitude = _getLatitude();
813   //entity.longitude = _getLongitude();
814  //entity.altitude = trafficRef->getCruiseAlt() * 100; // convert from FL to feet
815   //entity.speed = 450; // HACK ALERT
816   //entity.fp = new FGAIFlightPlan(&entity, courseToDest, i->getDepartureTime(), dep, arr);
817   int leg;
818   if ((leg = fp->getLeg())  == 10)
819     {
820       trafficRef->next();
821       leg = 1;
822       fp->setLeg(leg);
823       
824       //cerr << "Resetting leg : " << leg << endl;
825     }
826   //{
827   //leg++;
828   //fp->setLeg(leg);
829   //cerr << "Creating leg number : " << leg << endl;
830   FGAirport *dep = trafficRef->getDepartureAirport();
831   FGAirport *arr = trafficRef->getArrivalAirport();
832   if (!(dep && arr))
833     {
834       setDie(true);
835       //cerr << "Failed to get airport in AIAircraft::ProcessFlightplan()" << endl;
836       //if (dep)
837       //  cerr << "Departure " << dep->getId() << endl;
838       //if (arr) 
839       //  cerr << "Arrival   " << arr->getId() << endl;
840     }
841   else
842     {
843       double cruiseAlt = trafficRef->getCruiseAlt() * 100;
844       //cerr << "Creating new leg using " << cruiseAlt << " as cruise altitude."<< endl;
845       
846       fp->create (dep,
847                   arr,
848                   leg,
849                   cruiseAlt, //(trafficRef->getCruiseAlt() * 100), // convert from FL to feet
850                   trafficRef->getSpeed(),
851                   _getLatitude(),
852                   _getLongitude(),
853                   false,
854                   trafficRef->getRadius(),
855                   trafficRef->getFlightType(), 
856                   acType,
857                   company);
858       //prev = fp->getPreviousWaypoint();
859       //curr = fp->getCurrentWaypoint();
860       //next = fp->getNextWaypoint();
861       //cerr << "25" << endl;
862       //if (next) 
863       //        {
864       //  //cerr << "Next waypoint" << next->name << endl;
865       //          fp->setLeadDistance(speed, tgt_heading, curr, next);
866       //        }
867       //cerr << "25.1" << endl;
868       //if (curr->crossat > -1000.0) {
869       //        //cerr << "25.1a" << endl;
870       //        use_perf_vs = false;
871       //        
872       //        tgt_vs = (curr->crossat - altitude)/
873       //          (fp->getDistanceToGo(pos.lat(), pos.lon(), curr)/6076.0/speed*60.0);
874       //        //cerr << "25.1b" << endl;
875       //        tgt_altitude = curr->crossat;
876       //} else {
877       //        //cerr << "25.1c" << endl;
878       //        use_perf_vs = true;
879       //        //cerr << "25.1d" << endl;      
880       //        tgt_altitude = prev->altitude;
881       //        //cerr << "Setting target altitude : " <<tgt_altitude << endl;
882       // }
883       //cerr << "26" << endl;
884       //tgt_speed = prev->speed;
885       //hdg_lock = alt_lock = true;
886       //no_roll = prev->on_ground;
887       
888     }
889   //}
890   //else
891   //{
892   //delete entity.fp;
893   //entity.fp = new FGAIFlightPlan(&entity, 
894   //                             999,  // A hack
895   //                             trafficRef->getDepartureTime(), 
896   //                             trafficRef->getDepartureAirport(), 
897   //                             trafficRef->getArrivalAirport(),
898   //                             false,
899   //                             acType,
900   //                             company);
901   //SetFlightPlan(entity.fp);
902 }
903
904
905
906 // Note: This code is copied from David Luff's AILocalTraffic 
907 // Warning - ground elev determination is CPU intensive
908 // Either this function or the logic of how often it is called
909 // will almost certainly change.
910
911 void FGAIAircraft::getGroundElev(double dt) {
912   dt_elev_count += dt;
913   //return;
914   if (dt_elev_count < (3.0) + (rand() % 10)) //Update minimally every three secs, but add some randomness to prevent all IA objects doing this in synchrony
915      {
916        return;
917      }
918    else
919      {
920        dt_elev_count = 0;
921      }
922   // It would be nice if we could set the correct tile center here in order to get a correct
923   // answer with one call to the function, but what I tried in the two commented-out lines
924   // below only intermittently worked, and I haven't quite groked why yet.
925   //SGBucket buck(pos.lon(), pos.lat());
926   //aip.getSGLocation()->set_tile_center(Point3D(buck.get_center_lon(), buck.get_center_lat(), 0.0));
927   
928   // Only do the proper hitlist stuff if we are within visible range of the viewer.
929   double visibility_meters = fgGetDouble("/environment/visibility-m");  
930  
931
932   FGViewer* vw = globals->get_current_view();
933   double 
934     course, 
935     distance;
936
937   //Point3D currView(vw->getLongitude_deg(), 
938   //               vw->getLatitude_deg(), 0.0);
939   SGWayPoint current  (pos.lon(),
940                        pos.lat(),
941                        0);
942   SGWayPoint view (   vw->getLongitude_deg(),
943                       vw->getLatitude_deg(),
944                       0);
945   view.CourseAndDistance(current, &course, &distance);
946   if(distance > visibility_meters) {
947     //aip.getSGLocation()->set_cur_elev_m(aptElev);
948     return;
949   }
950     
951   // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
952   double range = 500.0;
953   if (!globals->get_tile_mgr()->scenery_available(pos.lat(), pos.lon(), range))
954   {
955     // Try to shedule tiles for that position.
956     globals->get_tile_mgr()->update( aip.getSGLocation(), range );
957   }
958
959   // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
960   double alt;
961   if (globals->get_scenery()->get_elevation_m(pos.lat(), pos.lon(),
962                                               20000.0, alt))
963       tgt_altitude = alt * SG_METER_TO_FEET; 
964   //cerr << "Target altitude : " << tgt_altitude << endl;
965   // if (globals->get_scenery()->get_elevation_m(pos.lat(), pos.lon(),
966   //                                            20000.0, alt))
967   //    tgt_altitude = alt * SG_METER_TO_FEET;
968   //cerr << "Target altitude : " << tgt_altitude << endl;
969 }
970
971 void FGAIAircraft::doGroundAltitude()
972 {
973   if (fabs(altitude - (tgt_altitude+groundOffset)) > 1000.0)
974     altitude = (tgt_altitude + groundOffset);
975   else
976     altitude += 0.1 * ((tgt_altitude+groundOffset) - altitude);
977 }