]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIAircraft.cxx
Pull Sound-manager out of FGGlobals
[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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24
25 #include <Main/fg_props.hxx>
26 #include <Main/globals.hxx>
27 #include <Scenery/scenery.hxx>
28 #include <Scenery/tilemgr.hxx>
29 #include <Airports/dynamics.hxx>
30 #include <Airports/airport.hxx>
31 #include <Main/util.hxx>
32 #include <Traffic/Schedule.hxx>
33
34 #include <simgear/structure/exception.hxx>
35
36 #include <string>
37 #include <cmath>
38 #include <ctime>
39
40 // defined in AIShip.cxx
41 extern double fgIsFinite(double x);
42
43 #include "AIManager.hxx"
44 #include "AIAircraft.hxx"
45 #include "AIFlightPlan.hxx"
46 #include "performancedata.hxx"
47 #include "performancedb.hxx"
48 #include <signal.h>
49
50 using std::string;
51 using std::cerr;
52 using std::endl;
53
54 //#include <Airports/trafficcontroller.hxx>
55
56 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
57      /* HOT must be disabled for AI Aircraft,
58       * otherwise traffic detection isn't working as expected.*/
59     FGAIBase(otAircraft, false),
60     _performance(0)
61 {
62     trafficRef = ref;
63     if (trafficRef) {
64         groundOffset = trafficRef->getGroundOffset();
65         setCallSign(trafficRef->getCallSign());
66     }
67     else
68         groundOffset = 0;
69
70     fp              = 0;
71     controller      = 0;
72     prevController  = 0;
73     towerController = 0;
74     dt_count = 0;
75     dt_elev_count = 0;
76     use_perf_vs = true;
77
78     no_roll = false;
79     tgt_speed = 0;
80     speed = 0;
81     groundTargetSpeed = 0;
82
83     // set heading and altitude locks
84     hdg_lock = false;
85     alt_lock = false;
86     roll = 0;
87     headingChangeRate = 0.0;
88     headingError = 0;
89     minBearing = 360;
90     speedFraction =1.0;
91     prev_dist_to_go = 0.0;
92
93     holdPos = false;
94     needsTaxiClearance = false;
95     _needsGroundElevation = true;
96
97     PerformanceDB* perfDB = globals->get_subsystem<PerformanceDB>();
98     if (perfDB) {
99         _performance = perfDB->getDefaultPerformance();
100     } else {
101         SG_LOG(SG_AI, SG_ALERT, "no performance DB found");
102     }
103
104     dt = 0;
105     takeOffStatus = 0;
106
107     trackCache.remainingLength = 0;
108     trackCache.startWptName = "-";
109 }
110
111
112 FGAIAircraft::~FGAIAircraft() {
113     //delete fp;
114     if (controller)
115         controller->signOff(getID());
116 }
117
118
119 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
120     if (!scFileNode)
121         return;
122
123     FGAIBase::readFromScenario(scFileNode);
124
125     setPerformance("", scFileNode->getStringValue("class", "jet_transport"));
126     setFlightPlan(scFileNode->getStringValue("flightplan"),
127                   scFileNode->getBoolValue("repeat", false));
128     setCallSign(scFileNode->getStringValue("callsign"));
129 }
130
131
132 void FGAIAircraft::bind() {
133     FGAIBase::bind();
134
135     tie("transponder-id",
136         SGRawValueMethods<FGAIAircraft,const char*>(*this,
137                 &FGAIAircraft::_getTransponderCode));
138 }
139
140 void FGAIAircraft::update(double dt) {
141     FGAIBase::update(dt);
142     Run(dt);
143     Transform();
144 }
145
146 void FGAIAircraft::unbind()
147 {
148     FGAIBase::unbind();
149     clearATCController();
150 }
151
152 void FGAIAircraft::setPerformance(const std::string& acType, const std::string& acclass)
153 {
154     PerformanceDB* perfDB = globals->get_subsystem<PerformanceDB>();
155     if (perfDB) {
156         _performance = perfDB->getDataFor(acType, acclass);
157     }
158 }
159
160 #if 0
161  void FGAIAircraft::setPerformance(PerformanceData *ps) {
162      _performance = ps;
163   }
164 #endif
165
166  void FGAIAircraft::Run(double dt) {
167       FGAIAircraft::dt = dt;
168     
169      bool outOfSight = false, 
170         flightplanActive = true;
171      updatePrimaryTargetValues(flightplanActive, outOfSight); // target hdg, alt, speed
172      if (outOfSight) {
173         return;
174      }
175
176      if (!flightplanActive) {
177         groundTargetSpeed = 0;
178      }
179
180      handleATCRequests(); // ATC also has a word to say
181      updateSecondaryTargetValues(); // target roll, vertical speed, pitch
182      updateActualState();
183 #if 0
184    // 25/11/12 - added but disabled, since setting properties isn't
185    // affecting the AI-model as expected.
186      updateModelProperties(dt);
187 #endif
188    
189     // We currently have one situation in which an AIAircraft object is used that is not attached to the
190     // AI manager. In this particular case, the AIAircraft is used to shadow the user's aircraft's behavior in the AI world.
191     // Since we perhaps don't want a radar entry of our own aircraft, the following conditional should probably be adequate
192     // enough
193      if (manager){
194         UpdateRadar(manager);
195         invisible = !manager->isVisible(pos);
196      }
197   }
198
199
200 void FGAIAircraft::AccelTo(double speed) {
201     tgt_speed = speed;
202     //assertSpeed(speed);
203     if (!isStationary())
204         _needsGroundElevation = true;
205 }
206
207
208 void FGAIAircraft::PitchTo(double angle) {
209     tgt_pitch = angle;
210     alt_lock = false;
211 }
212
213
214 void FGAIAircraft::RollTo(double angle) {
215     tgt_roll = angle;
216     hdg_lock = false;
217 }
218
219
220 void FGAIAircraft::YawTo(double angle) {
221     tgt_yaw = angle;
222 }
223
224
225 void FGAIAircraft::ClimbTo(double alt_ft ) {
226     tgt_altitude_ft = alt_ft;
227     alt_lock = true;
228 }
229
230
231 void FGAIAircraft::TurnTo(double heading) {
232     tgt_heading = heading;
233     hdg_lock = true;
234 }
235
236
237 double FGAIAircraft::sign(double x) {
238     if (x == 0.0)
239         return x;
240     else
241         return x/fabs(x);
242 }
243
244
245 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat)
246 {
247     if (flightplan.empty()) {
248         // this is the case for Nasal-scripted aircraft
249         return;
250     }
251     
252     FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
253     if (fp->isValidPlan()) {
254         fp->setRepeat(repeat);
255         SetFlightPlan(fp);
256     } else {
257         SG_LOG(SG_AI, SG_WARN, "setFlightPlan: invalid flightplan specified:" << flightplan);
258         delete fp;
259     }
260 }
261
262
263 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f)
264 {
265     delete fp;
266     fp = f;
267 }
268
269
270 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
271
272     // the one behind you
273     FGAIWaypoint* prev = 0;
274     // the one ahead
275     FGAIWaypoint* curr = 0;
276     // the next plus 1
277     FGAIWaypoint* next = 0;
278
279     prev = fp->getPreviousWaypoint();
280     curr = fp->getCurrentWaypoint();
281     next = fp->getNextWaypoint();
282
283     dt_count += dt;
284
285     ///////////////////////////////////////////////////////////////////////////
286     // Initialize the flightplan
287     //////////////////////////////////////////////////////////////////////////
288     if (!prev) {
289         handleFirstWaypoint();
290         return;
291     }                            // end of initialization
292     if (! fpExecutable(now))
293           return;
294     dt_count = 0;
295
296     double distanceToDescent;
297     if(reachedEndOfCruise(distanceToDescent)) {
298         if (!loadNextLeg(distanceToDescent)) {
299             setDie(true);
300             return;
301         }
302         prev = fp->getPreviousWaypoint();
303         curr = fp->getCurrentWaypoint();
304         next = fp->getNextWaypoint();
305     }
306     if (!curr)
307     {
308         // Oops! FIXME
309         return;
310     }
311
312     if (! leadPointReached(curr)) {
313         controlHeading(curr);
314         controlSpeed(curr, next);
315         
316             /*
317             if (speed < 0) { 
318                 cerr << getCallSign() 
319                      << ": verifying lead distance to waypoint : " 
320                      << fp->getCurrentWaypoint()->name << " "
321                      << fp->getLeadDistance() << ". Distance to go " 
322                      << (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)) 
323                      << ". Target speed = " 
324                      << tgt_speed
325                      << ". Current speed = "
326                      << speed
327                      << ". Minimum Bearing " << minBearing
328                      << endl;
329             } */
330     } else {
331         if (curr->isFinished())      //end of the flight plan
332         {
333             if (fp->getRepeat())
334                 fp->restart();
335             else
336                 setDie(true);
337             return;
338         }
339
340         if (next) {
341             //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
342             tgt_heading = fp->getBearing(curr, next);
343             spinCounter = 0;
344         }
345
346         //TODO let the fp handle this (loading of next leg)
347         fp->IncrementWaypoint( trafficRef != 0 );
348         if  ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
349             if (!loadNextLeg()) {
350                 setDie(true);
351                 return;
352             }
353
354         prev = fp->getPreviousWaypoint();
355         curr = fp->getCurrentWaypoint();
356         next = fp->getNextWaypoint();
357
358         // Now that we have incremented the waypoints, excute some traffic manager specific code
359         if (trafficRef) {
360             //TODO isn't this best executed right at the beginning?
361             if (! aiTrafficVisible()) {
362                 setDie(true);
363                 return;
364             }
365
366             if (! handleAirportEndPoints(prev, now)) {
367                 setDie(true);
368                 return;
369             }
370
371             announcePositionToController();
372
373         }
374
375         if (next) {
376             fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
377         }
378
379
380         if (!(prev->getOn_ground()))  // only update the tgt altitude from flightplan if not on the ground
381         {
382             tgt_altitude_ft = prev->getAltitude();
383             if (curr->getCrossat() > -1000.0) {
384                 use_perf_vs = false;
385                 // Distance to go in meters
386                 double vert_dist_ft = curr->getCrossat() - altitude_ft;
387                 double err_dist     = prev->getCrossat() - altitude_ft;
388                 double dist_m       = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
389                 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
390                 
391                 checkTcas();
392                 tgt_altitude_ft = curr->getCrossat();
393             } else {
394                 use_perf_vs = true;
395             }
396         }
397         AccelTo(prev->getSpeed());
398         hdg_lock = alt_lock = true;
399         no_roll = prev->getOn_ground();
400     }
401 }
402
403 double FGAIAircraft::calcVerticalSpeed(double vert_ft, double dist_m, double speed, double err)
404 {
405     // err is negative when we passed too high
406     double vert_m = vert_ft * SG_FEET_TO_METER;
407     //double err_m  = err     * SG_FEET_TO_METER;
408     //double angle = atan2(vert_m, dist_m);
409     double speedMs = (speed * SG_NM_TO_METER) / 3600;
410     //double vs = cos(angle) * speedMs; // Now in m/s
411     double vs = 0;
412     //cerr << "Error term = " << err_m << endl;
413     if (dist_m) {
414         vs = ((vert_m) / dist_m) * speedMs;
415     }
416     // Convert to feet per minute
417     vs *= (SG_METER_TO_FEET * 60);
418     //if (getCallSign() == "LUFTHANSA2002")
419     //if (fabs(vs) > 100000) {
420 //     if (getCallSign() == "LUFTHANSA2057") {
421 //         cerr << getCallSign() << " " << fp->getPreviousWaypoint()->getName() << ". Alt = " << altitude_ft <<  " vertical dist = " << vert_m << " horiz dist = " << dist_m << " << angle  = " << angle * SG_RADIANS_TO_DEGREES << " vs " << vs << " horizontal speed " << speed << "Previous crossAT " << fp->getPreviousWaypoint()->getCrossat() << endl;
422 //     //= (curr->getCrossat() - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
423 //     //                     / 6076.0 / speed*60.0);
424 //         //raise(SIGSEGV);
425 //     }
426     return vs;
427 }
428
429 void FGAIAircraft::clearATCController()
430 {
431     controller = 0;
432     prevController = 0;
433     towerController = 0;
434 }
435
436 void FGAIAircraft::assertSpeed(double speed)
437 {
438     if ((speed < -50) || (speed > 1000)) {
439         cerr << getCallSign() << " " 
440             << "Previous waypoint " << fp->getPreviousWaypoint()->getName() << " "
441             << "Departure airport " << trafficRef->getDepartureAirport() << " "
442             << "Leg " << fp->getLeg() <<  " "
443             << "target_speed << " << tgt_speed <<  " "
444             << "speedFraction << " << speedFraction << " "
445             << "Currecnt speed << " << speed << " "
446             << endl;
447        //raise(SIGSEGV);
448     }
449 }
450
451
452
453 void FGAIAircraft::checkTcas(void)
454 {
455     if (props->getIntValue("tcas/threat-level",0)==3)
456     {
457         int RASense = props->getIntValue("tcas/ra-sense",0);
458         if ((RASense>0)&&(tgt_vs<4000))
459             // upward RA: climb!
460             tgt_vs = 4000;
461         else
462         if (RASense<0)
463         {
464             // downward RA: descend!
465             if (altitude_ft < 1000)
466             {
467                 // too low: level off
468                 if (tgt_vs>0)
469                     tgt_vs = 0;
470             }
471             else
472             {
473                 if (tgt_vs >- 4000)
474                     tgt_vs = -4000;
475             }
476         }
477     }
478 }
479
480 void FGAIAircraft::initializeFlightPlan() {
481 }
482
483 const char * FGAIAircraft::_getTransponderCode() const {
484   return transponderCode.c_str();
485 }
486
487 // NOTE: Check whether the new (delayed leg increment code has any effect on this code.
488 // Probably not, because it should only be executed after we have already passed the leg incrementing waypoint. 
489
490 bool FGAIAircraft::loadNextLeg(double distance) {
491
492     int leg;
493     if ((leg = fp->getLeg())  == 9) {
494         if (!trafficRef->next()) {
495             return false;
496         }
497         setCallSign(trafficRef->getCallSign());
498         leg = 0;
499         fp->setLeg(leg);
500     }
501
502     FGAirport *dep = trafficRef->getDepartureAirport();
503     FGAirport *arr = trafficRef->getArrivalAirport();
504     if (!(dep && arr)) {
505         setDie(true);
506
507     } else {
508         double cruiseAlt = trafficRef->getCruiseAlt() * 100;
509
510         fp->create (this,
511                     dep,
512                     arr,
513                     leg+1,
514                     cruiseAlt,
515                     trafficRef->getSpeed(),
516                     _getLatitude(),
517                     _getLongitude(),
518                     false,
519                     trafficRef->getRadius(),
520                     trafficRef->getFlightType(),
521                     acType,
522                     company,
523                     distance);
524        //cerr << "created  leg " << leg << " for " << trafficRef->getCallSign() << endl;
525     }
526     return true;
527 }
528
529
530 // Note: This code is copied from David Luff's AILocalTraffic
531 // Warning - ground elev determination is CPU intensive
532 // Either this function or the logic of how often it is called
533 // will almost certainly change.
534
535 void FGAIAircraft::getGroundElev(double dt) {
536     dt_elev_count += dt;
537
538     if (!needGroundElevation())
539         return;
540     // Update minimally every three secs, but add some randomness
541     // to prevent all AI objects doing this in synchrony
542     if (dt_elev_count < (3.0) + (rand() % 10))
543         return;
544
545     dt_elev_count = 0;
546
547     // Only do the proper hitlist stuff if we are within visible range of the viewer.
548     if (!invisible) {
549         double visibility_meters = fgGetDouble("/environment/visibility-m");        
550         if (SGGeodesy::distanceM(globals->get_view_position(), pos) > visibility_meters) {
551             return;
552         }
553
554         double range = 500.0;
555         if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
556         {
557             double alt;
558             if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
559             {
560                 tgt_altitude_ft = alt * SG_METER_TO_FEET;
561                 if (isStationary())
562                 {
563                     // aircraft is stationary and we obtained altitude for this spot - we're done.
564                     _needsGroundElevation = false;
565                 }
566             }
567         }
568     }
569 }
570
571
572 void FGAIAircraft::doGroundAltitude() {
573     if ((fp->getLeg() == 7) && ((altitude_ft -  tgt_altitude_ft) > 5)) {
574         tgt_vs = -500;
575     } else {
576         if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
577             (isStationary()))
578             altitude_ft = (tgt_altitude_ft + groundOffset);
579         else
580             altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
581         tgt_vs = 0;
582     }
583 }
584
585
586 void FGAIAircraft::announcePositionToController() {
587     if (!trafficRef) {
588         return;
589     }
590     
591     int leg = fp->getLeg();
592     if (!fp->getCurrentWaypoint()) {
593         // http://code.google.com/p/flightgear-bugs/issues/detail?id=1153
594         // throw an exception so this aircraft gets killed by the AIManager.
595         throw sg_exception("bad AI flight plan");
596     }
597     
598     // Note that leg has been incremented after creating the current leg, so we should use
599     // leg numbers here that are one higher than the number that is used to create the leg
600     // NOTE: As of July, 30, 2011, the post-creation leg updating is no longer happening. 
601     // Leg numbers are updated only once the aircraft passes the last waypoint created for that legm so I should probably just use
602     // the original leg numbers here!
603     switch (leg) {
604       case 1:              // Startup and Push back
605         if (trafficRef->getDepartureAirport()->getDynamics())
606             controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
607         break;
608     case 2:              // Taxiing to runway
609         if (trafficRef->getDepartureAirport()->getDynamics()->getGroundController()->exists())
610             controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundController();
611         break;
612     case 3:              //Take off tower controller
613         if (trafficRef->getDepartureAirport()->getDynamics()) {
614             controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
615             towerController = 0;
616         } else {
617             cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
618         }
619         break;
620     case 6:
621          if (trafficRef->getArrivalAirport()->getDynamics()) {
622              controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
623           }
624           break;
625     case 8:              // Taxiing for parking
626         if (trafficRef->getArrivalAirport()->getDynamics()->getGroundController()->exists())
627             controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundController();
628         break;
629     default:
630         controller = 0;
631         break;
632     }
633
634     if ((controller != prevController) && (prevController != 0)) {
635         prevController->signOff(getID());
636     }
637     prevController = controller;
638     if (controller) {
639         controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
640                                      _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
641                                      trafficRef->getRadius(), leg, this);
642     }
643 }
644
645 void FGAIAircraft::scheduleForATCTowerDepartureControl(int state) {
646     if (!takeOffStatus) {
647         int leg = fp->getLeg();
648         if (trafficRef) {
649             if (trafficRef->getDepartureAirport()->getDynamics()) {
650                 towerController = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
651             } else {
652                 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
653             }
654             if (towerController) {
655                 towerController->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
656                                                    _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
657                                                     trafficRef->getRadius(), leg, this);
658                 //cerr << "Scheduling " << trafficRef->getCallSign() << " for takeoff " << endl;
659             }
660         }
661     }
662     takeOffStatus = state;
663 }
664
665 // Process ATC instructions and report back
666
667 void FGAIAircraft::processATC(const FGATCInstruction& instruction) {
668     if (instruction.getCheckForCircularWait()) {
669         // This is not exactly an elegant solution, 
670         // but at least it gives me a chance to check
671         // if circular waits are resolved.
672         // For now, just take the offending aircraft 
673         // out of the scene
674         setDie(true);
675         // a more proper way should be - of course - to
676         // let an offending aircraft take an evasive action
677         // for instance taxi back a little bit.
678     }
679     //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
680     if (instruction.getHoldPattern   ()) {}
681
682     // Hold Position
683     if (instruction.getHoldPosition  ()) {
684         if (!holdPos) {
685             holdPos = true;
686         }
687         AccelTo(0.0);
688     } else {
689         if (holdPos) {
690             //if (trafficRef)
691             //  cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
692             holdPos = false;
693         }
694         // Change speed Instruction. This can only be excecuted when there is no
695         // Hold position instruction.
696         if (instruction.getChangeSpeed   ()) {
697             //  if (trafficRef)
698             //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
699             AccelTo(instruction.getSpeed());
700         } else {
701             if (fp) AccelTo(fp->getPreviousWaypoint()->getSpeed());
702         }
703     }
704     if (instruction.getChangeHeading ()) {
705         hdg_lock = false;
706         TurnTo(instruction.getHeading());
707     } else {
708         if (fp) {
709             hdg_lock = true;
710         }
711     }
712     if (instruction.getChangeAltitude()) {}
713
714 }
715
716
717 void FGAIAircraft::handleFirstWaypoint() {
718     bool eraseWaypoints;         //TODO YAGNI
719     headingError = 0;
720     if (trafficRef) {
721         eraseWaypoints = true;
722     } else {
723         eraseWaypoints = false;
724     }
725
726     FGAIWaypoint* prev = 0; // the one behind you
727     FGAIWaypoint* curr = 0; // the one ahead
728     FGAIWaypoint* next = 0;// the next plus 1
729
730     spinCounter = 0;
731
732     //TODO fp should handle this
733     fp->IncrementWaypoint(eraseWaypoints);
734     if (!(fp->getNextWaypoint()) && trafficRef)
735         if (!loadNextLeg()) {
736             setDie(true);
737             return;
738         }
739
740     prev = fp->getPreviousWaypoint();   //first waypoint
741     curr = fp->getCurrentWaypoint();    //second waypoint
742     next = fp->getNextWaypoint();       //third waypoint (might not exist!)
743
744     setLatitude(prev->getLatitude());
745     setLongitude(prev->getLongitude());
746     setSpeed(prev->getSpeed());
747     setAltitude(prev->getAltitude());
748
749     if (prev->getSpeed() > 0.0)
750         setHeading(fp->getBearing(prev, curr));
751     else
752         setHeading(fp->getBearing(curr, prev));
753
754     // If next doesn't exist, as in incrementally created flightplans for
755     // AI/Trafficmanager created plans,
756     // Make sure lead distance is initialized otherwise
757     if (next)
758         fp->setLeadDistance(speed, hdg, curr, next);
759
760     if (curr->getCrossat() > -1000.0) //use a calculated descent/climb rate
761     {
762         use_perf_vs = false;
763         //tgt_vs = (curr->getCrossat() - prev->getAltitude())
764         //         / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
765         //            / 6076.0 / prev->getSpeed()*60.0);
766         double vert_dist_ft = curr->getCrossat() - altitude_ft;
767         double err_dist     = prev->getCrossat() - altitude_ft;
768         double dist_m       = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
769         tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
770         checkTcas();
771         tgt_altitude_ft = curr->getCrossat();
772     } else {
773         use_perf_vs = true;
774         tgt_altitude_ft = prev->getAltitude();
775     }
776     alt_lock = hdg_lock = true;
777     no_roll = prev->getOn_ground();
778     if (no_roll) {
779         Transform();             // make sure aip is initialized.
780         getGroundElev(60.1);     // make sure it's executed first time around, so force a large dt value
781         doGroundAltitude();
782         _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
783     }
784     // Make sure to announce the aircraft's position
785     announcePositionToController();
786     prevSpeed = 0;
787 }
788
789
790 /**
791  * Check Execution time (currently once every 100 ms)
792  * Add a bit of randomization to prevent the execution of all flight plans
793  * in synchrony, which can add significant periodic framerate flutter.
794  *
795  * @param now
796  * @return
797  */
798 bool FGAIAircraft::fpExecutable(time_t now) {
799     double rand_exec_time = (rand() % 100) / 100;
800     return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
801 }
802
803
804 /**
805  * Check to see if we've reached the lead point for our next turn
806  *
807  * @param curr
808  * @return
809  */
810 bool FGAIAircraft::leadPointReached(FGAIWaypoint* curr) {
811     double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
812
813     //cerr << "2" << endl;
814     double lead_dist = fp->getLeadDistance();
815     // experimental: Use fabs, because speed can be negative (I hope) during push_back.
816     if ((dist_to_go < fabs(10.0* speed)) && (speed < 0) && (tgt_speed < 0) && fp->getCurrentWaypoint()->contains("PushBackPoint")) {
817           tgt_speed = -(dist_to_go / 10.0);
818           if (tgt_speed > -0.5) {
819                 tgt_speed = -0.5;
820           }
821           //assertSpeed(tgt_speed);
822           if (fp->getPreviousWaypoint()->getSpeed() < tgt_speed) {
823               fp->getPreviousWaypoint()->setSpeed(tgt_speed);
824           }
825     }
826     if (lead_dist < fabs(2*speed)) {
827       //don't skip over the waypoint
828       lead_dist = fabs(2*speed);
829       //cerr << "Extending lead distance to " << lead_dist << endl;
830     }
831
832     //prev_dist_to_go = dist_to_go;
833     //if (dist_to_go < lead_dist)
834     //     cerr << trafficRef->getCallSign() << " Distance : " 
835     //          << dist_to_go << ": Lead distance " 
836     //          << lead_dist << " " << curr->name 
837     //          << " Ground target speed " << groundTargetSpeed << endl;
838     double bearing = 0;
839      // don't do bearing calculations for ground traffic
840        bearing = getBearing(fp->getBearing(pos, curr));
841        if (bearing < minBearing) {
842             minBearing = bearing;
843             if (minBearing < 10) {
844                  minBearing = 10;
845             }
846             if ((minBearing < 360.0) && (minBearing > 10.0)) {
847                 speedFraction = 0.5 + (cos(minBearing *SG_DEGREES_TO_RADIANS) * 0.5);
848             } else {
849                 speedFraction = 1.0;
850             }
851        } 
852     if (trafficRef) {
853          //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
854          //if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
855               //cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " " 
856               //     << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->getName() << " " << vs << " " << //tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl; 
857          //}
858      }
859     if ((dist_to_go < lead_dist) ||
860         ((dist_to_go > prev_dist_to_go) && (bearing > (minBearing * 1.1))) ) {
861         minBearing = 360;
862         speedFraction = 1.0;
863         prev_dist_to_go = HUGE_VAL;
864         return true;
865     } else {
866         prev_dist_to_go = dist_to_go;
867         return false;
868     }
869 }
870
871
872 bool FGAIAircraft::aiTrafficVisible()
873 {
874     SGVec3d cartPos = SGVec3d::fromGeod(pos);
875     const double d2 = (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER) *
876         (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER);
877     return (distSqr(cartPos, globals->get_aircraft_position_cart()) < d2);
878 }
879
880
881 /**
882  * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
883  * in the case of an arrival.
884  *
885  * @param prev
886  * @return
887  */
888
889 //TODO the trafficRef is the right place for the method
890 bool FGAIAircraft::handleAirportEndPoints(FGAIWaypoint* prev, time_t now) {
891     // prepare routing from one airport to another
892     FGAirport * dep = trafficRef->getDepartureAirport();
893     FGAirport * arr = trafficRef->getArrivalAirport();
894
895     if (!( dep && arr))
896         return false;
897
898     // This waypoint marks the fact that the aircraft has passed the initial taxi
899     // departure waypoint, so it can release the parking.
900     //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
901     //cerr << "Passing waypoint : " << prev->getName() << endl;
902     if (prev->contains("PushBackPoint")) {
903       // clearing the parking assignment will release the gate
904         fp->setGate(ParkingAssignment());
905         AccelTo(0.0);
906         //setTaxiClearanceRequest(true);
907     }
908     if (prev->contains("legend")) {
909         fp->incrementLeg();
910     }
911     if (prev->contains(string("DepartureHold"))) {
912         //cerr << "Passing point DepartureHold" << endl;
913         scheduleForATCTowerDepartureControl(1);
914     }
915     if (prev->contains(string("Accel"))) {
916         takeOffStatus = 3;
917     }
918     //if (prev->contains(string("landing"))) {
919     //    if (speed < _performance->vTaxi() * 2) {
920     //        fp->shortenToFirst(2, "legend");
921     //    }
922     //}
923     //if (prev->contains(string("final"))) {
924     //    
925     //     cerr << getCallSign() << " " 
926     //        << fp->getPreviousWaypoint()->getName() 
927     //        << ". Alt = " << altitude_ft 
928     //        << " vs " << vs 
929     //        << " horizontal speed " << speed 
930     //        << "Previous crossAT " << fp->getPreviousWaypoint()->getCrossat()
931     //        << "Airport elevation" << getTrafficRef()->getArrivalAirport()->getElevation() 
932     //        << "Altitude difference " << (altitude_ft -  fp->getPreviousWaypoint()->getCrossat()) << endl;
933     //q}
934     // This is the last taxi waypoint, and marks the the end of the flight plan
935     // so, the schedule should update and wait for the next departure time.
936     if (prev->contains("END")) {
937         time_t nextDeparture = trafficRef->getDepartureTime();
938         // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
939         if (nextDeparture < (now+1200)) {
940             nextDeparture = now + 1200;
941         }
942         fp->setTime(nextDeparture);
943     }
944
945     return true;
946 }
947
948
949 /**
950  * Check difference between target bearing and current heading and correct if necessary.
951  *
952  * @param curr
953  */
954 void FGAIAircraft::controlHeading(FGAIWaypoint* curr) {
955     double calc_bearing = fp->getBearing(pos, curr);
956     //cerr << "Bearing = " << calc_bearing << endl;
957     if (speed < 0) {
958         calc_bearing +=180;
959         SG_NORMALIZE_RANGE(calc_bearing, 0.0, 360.0);
960     }
961
962     if (fgIsFinite(calc_bearing)) {
963         double hdg_error = calc_bearing - tgt_heading;
964         if (fabs(hdg_error) > 0.01) {
965             TurnTo( calc_bearing );
966         }
967
968     } else {
969         cerr << "calc_bearing is not a finite number : "
970         << "Speed " << speed
971         << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
972         << ", waypoint: " << curr->getLatitude() << ", " << curr->getLongitude() << endl;
973         cerr << "waypoint name: '" << curr->getName() << "'" << endl;
974         //exit(1);                 // FIXME
975     }
976 }
977
978
979 /**
980  * Update the lead distance calculation if speed has changed sufficiently
981  * to prevent spinning (hopefully);
982  *
983  * @param curr
984  * @param next
985  */
986 void FGAIAircraft::controlSpeed(FGAIWaypoint* curr, FGAIWaypoint* next) {
987     double speed_diff = speed - prevSpeed;
988
989     if (fabs(speed_diff) > 10) {
990         prevSpeed = speed;
991         //assertSpeed(speed);
992         if (next) {
993             fp->setLeadDistance(speed, tgt_heading, curr, next);
994         }
995     }
996 }
997
998
999 /**
1000  * Update target values (heading, alt, speed) depending on flight plan or control properties
1001  */
1002 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
1003     if (fp)                      // AI object has a flightplan
1004     {
1005         //TODO make this a function of AIBase
1006         time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1007         //cerr << "UpateTArgetValues() " << endl;
1008         ProcessFlightPlan(dt, now);
1009
1010         // Do execute Ground elev for inactive aircraft, so they
1011         // Are repositioned to the correct ground altitude when the user flies within visibility range.
1012         // In addition, check whether we are out of user range, so this aircraft
1013         // can be deleted.
1014         if (onGround()) {
1015                 Transform();     // make sure aip is initialized.
1016                 getGroundElev(dt);
1017                 doGroundAltitude();
1018                 // Transform();
1019                 pos.setElevationFt(altitude_ft);
1020         }
1021         if (trafficRef) {
1022            //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
1023             aiOutOfSight = !aiTrafficVisible();
1024             if (aiOutOfSight) {
1025                 setDie(true);
1026                 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
1027                 aiOutOfSight = true;
1028                 return;
1029             }
1030         }
1031         timeElapsed = now - fp->getStartTime();
1032         flightplanActive = fp->isActive(now);
1033     } else {
1034         // no flight plan, update target heading, speed, and altitude
1035         // from control properties.  These default to the initial
1036         // settings in the config file, but can be changed "on the
1037         // fly".
1038         const string& lat_mode = props->getStringValue("controls/flight/lateral-mode");
1039         if ( lat_mode == "roll" ) {
1040             double angle
1041             = props->getDoubleValue("controls/flight/target-roll" );
1042             RollTo( angle );
1043         } else {
1044             double angle
1045             = props->getDoubleValue("controls/flight/target-hdg" );
1046             TurnTo( angle );
1047         }
1048
1049         string lon_mode
1050         = props->getStringValue("controls/flight/longitude-mode");
1051         if ( lon_mode == "alt" ) {
1052             double alt = props->getDoubleValue("controls/flight/target-alt" );
1053             ClimbTo( alt );
1054         } else {
1055             double angle
1056             = props->getDoubleValue("controls/flight/target-pitch" );
1057             PitchTo( angle );
1058         }
1059
1060         AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
1061     }
1062 }
1063
1064 void FGAIAircraft::updateHeading() {
1065     // adjust heading based on current bank angle
1066     if (roll == 0.0)
1067         roll = 0.01;
1068
1069     if (roll != 0.0) {
1070         // double turnConstant;
1071         //if (no_roll)
1072         //  turnConstant = 0.0088362;
1073         //else
1074         //  turnConstant = 0.088362;
1075         // If on ground, calculate heading change directly
1076         if (onGround()) {
1077             double headingDiff = fabs(hdg-tgt_heading);
1078 //            double bank_sense = 0.0;
1079         /*
1080         double diff = fabs(hdg - tgt_heading);
1081         if (diff > 180)
1082             diff = fabs(diff - 360);
1083
1084         double sum = hdg + diff;
1085         if (sum > 360.0)
1086             sum -= 360.0;
1087         if (fabs(sum - tgt_heading) < 1.0) {
1088             bank_sense = 1.0;    // right turn
1089         } else {
1090             bank_sense = -1.0;   // left turn
1091         }*/
1092             if (headingDiff > 180)
1093                 headingDiff = fabs(headingDiff - 360);
1094             double sum = hdg + headingDiff;
1095             if (sum > 360.0) 
1096                 sum -= 360.0;
1097             if (fabs(sum - tgt_heading) > 0.0001) {
1098 //                bank_sense = -1.0;
1099             } else {
1100 //                bank_sense = 1.0;
1101             }
1102             //if (trafficRef)
1103             //  cerr << trafficRef->getCallSign() << " Heading " 
1104             //         << hdg << ". Target " << tgt_heading <<  ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
1105             //if (headingDiff > 60) {
1106             groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
1107             //assertSpeed(groundTargetSpeed);
1108                 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
1109             //} else {
1110             //    groundTargetSpeed = tgt_speed;
1111             //}
1112             if (sign(groundTargetSpeed) != sign(tgt_speed))
1113                 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
1114             //assertSpeed(groundTargetSpeed);
1115             // Only update the target values when we're not moving because otherwise we might introduce an enormous target change rate while waiting a the gate, or holding.
1116             if (speed != 0) {
1117                 if (headingDiff > 30.0) {
1118                     // invert if pushed backward
1119                     headingChangeRate += 10.0 * dt * sign(roll);
1120
1121                     // Clamp the maximum steering rate to 30 degrees per second,
1122                     // But only do this when the heading error is decreasing.
1123                     if ((headingDiff < headingError)) {
1124                         if (headingChangeRate > 30)
1125                             headingChangeRate = 30;
1126                         else if (headingChangeRate < -30)
1127                             headingChangeRate = -30;
1128                     }
1129                 } else {
1130                     if (speed != 0) {
1131                         if (fabs(headingChangeRate) > headingDiff)
1132                             headingChangeRate = headingDiff*sign(roll);
1133                         else
1134                             headingChangeRate += dt * sign(roll);
1135                     }
1136                 }
1137             }
1138
1139             hdg += headingChangeRate * dt * sqrt(fabs(speed) / 15);
1140             headingError = headingDiff;
1141             if (fabs(headingError) < 1.0) {
1142                 hdg = tgt_heading;
1143             }
1144         } else {
1145             if (fabs(speed) > 1.0) {
1146                 turn_radius_ft = 0.088362 * speed * speed
1147                                  / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
1148             } else {
1149                 // Check if turn_radius_ft == 0; this might lead to a division by 0.
1150                 turn_radius_ft = 1.0;
1151             }
1152             double turn_circum_ft = SGD_2PI * turn_radius_ft;
1153             double dist_covered_ft = speed * 1.686 * dt;
1154             double alpha = dist_covered_ft / turn_circum_ft * 360.0;
1155             hdg += alpha * sign(roll);
1156         }
1157         while ( hdg > 360.0 ) {
1158             hdg -= 360.0;
1159             spinCounter++;
1160         }
1161         while ( hdg < 0.0) {
1162             hdg += 360.0;
1163             spinCounter--;
1164         }
1165     }
1166 }
1167
1168
1169 void FGAIAircraft::updateBankAngleTarget() {
1170     // adjust target bank angle if heading lock engaged
1171     if (hdg_lock) {
1172         double bank_sense = 0.0;
1173         double diff = fabs(hdg - tgt_heading);
1174         if (diff > 180)
1175             diff = fabs(diff - 360);
1176
1177         double sum = hdg + diff;
1178         if (sum > 360.0)
1179             sum -= 360.0;
1180         if (fabs(sum - tgt_heading) < 1.0) {
1181             bank_sense = 1.0;    // right turn
1182         } else {
1183             bank_sense = -1.0;   // left turn
1184         }
1185         if (diff < _performance->maximumBankAngle()) {
1186             tgt_roll = diff * bank_sense;
1187         } else {
1188             tgt_roll = _performance->maximumBankAngle() * bank_sense;
1189         }
1190         if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
1191             tgt_speed *= 0.999;  // Ugly hack: If aircraft get stuck, they will continually spin around.
1192             // The only way to resolve this is to make them slow down.
1193         }
1194     }
1195 }
1196
1197
1198 void FGAIAircraft::updateVerticalSpeedTarget() {
1199     // adjust target Altitude, based on ground elevation when on ground
1200     if (onGround()) {
1201         getGroundElev(dt);
1202         doGroundAltitude();
1203     } else if (alt_lock) {
1204         // find target vertical speed
1205         if (use_perf_vs) {
1206             if (altitude_ft < tgt_altitude_ft) {
1207                 tgt_vs = std::min(tgt_altitude_ft - altitude_ft, _performance->climbRate());
1208             } else {
1209                 tgt_vs = std::max(tgt_altitude_ft - altitude_ft, -_performance->descentRate());
1210             }
1211         } else {
1212             double vert_dist_ft = fp->getCurrentWaypoint()->getCrossat() - altitude_ft;
1213             double err_dist     = 0; //prev->getCrossat() - altitude_ft;
1214             double dist_m       = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), fp->getCurrentWaypoint());
1215             tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
1216             //cerr << "Target vs before : " << tgt_vs;
1217 /*            double max_vs = 10*(tgt_altitude_ft - altitude_ft);
1218             double min_vs = 100;
1219             if (tgt_altitude_ft < altitude_ft)
1220                 min_vs = -100.0;
1221             if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1222                     && (fabs(max_vs) < fabs(tgt_vs)))
1223                 tgt_vs = max_vs;
1224
1225             if (fabs(tgt_vs) < fabs(min_vs))
1226                 tgt_vs = min_vs;*/
1227             //cerr << "target vs : after " << tgt_vs << endl;
1228         }
1229     } //else 
1230     //    tgt_vs = 0.0;
1231     checkTcas();
1232 }
1233
1234 void FGAIAircraft::updatePitchAngleTarget() {
1235     // if on ground and above vRotate -> initial rotation
1236     if (onGround() && (speed > _performance->vRotate()))
1237         tgt_pitch = 8.0; // some rough B737 value 
1238
1239     //TODO pitch angle on approach and landing
1240     
1241     // match pitch angle to vertical speed
1242     else if (tgt_vs > 0) {
1243         tgt_pitch = tgt_vs * 0.005;
1244     } else {
1245         tgt_pitch = tgt_vs * 0.002;
1246     }
1247 }
1248
1249 const string& FGAIAircraft::atGate()
1250 {
1251      if ((fp->getLeg() < 3) && trafficRef) {
1252        if (fp->getParkingGate()) {
1253          return fp->getParkingGate()->ident();
1254        }
1255      }
1256        
1257      static const string empty;
1258      return empty;
1259 }
1260
1261 void FGAIAircraft::handleATCRequests() {
1262     //TODO implement NullController for having no ATC to save the conditionals
1263     if (controller) {
1264         controller->updateAircraftInformation(getID(),
1265                                               pos.getLatitudeDeg(),
1266                                               pos.getLongitudeDeg(),
1267                                               hdg,
1268                                               speed,
1269                                               altitude_ft, dt);
1270         processATC(controller->getInstruction(getID()));
1271     }
1272     if (towerController) {
1273         towerController->updateAircraftInformation(getID(),
1274                                               pos.getLatitudeDeg(),
1275                                               pos.getLongitudeDeg(),
1276                                               hdg,
1277                                               speed,
1278                                               altitude_ft, dt);
1279     }
1280 }
1281
1282 void FGAIAircraft::updateActualState() {
1283     //update current state
1284     //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1285     double distance = speed * SG_KT_TO_MPS * dt;
1286     pos = SGGeodesy::direct(pos, hdg, distance);
1287
1288
1289     if (onGround())
1290         speed = _performance->actualSpeed(this, groundTargetSpeed, dt, holdPos);
1291     else
1292         speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt, false);
1293     //assertSpeed(speed);
1294     updateHeading();
1295     roll = _performance->actualBankAngle(this, tgt_roll, dt);
1296
1297     // adjust altitude (meters) based on current vertical speed (fpm)
1298     altitude_ft += vs / 60.0 * dt;
1299     pos.setElevationFt(altitude_ft);
1300
1301     vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1302     pitch = _performance->actualPitch(this, tgt_pitch, dt);
1303 }
1304
1305 void FGAIAircraft::updateSecondaryTargetValues() {
1306     // derived target state values
1307     updateBankAngleTarget();
1308     updateVerticalSpeedTarget();
1309     updatePitchAngleTarget();
1310
1311     //TODO calculate wind correction angle (tgt_yaw)
1312 }
1313
1314
1315 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1316     FGAIWaypoint* curr = fp->getCurrentWaypoint();
1317     if (curr->getName() == string("BOD")) {
1318         double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1319         double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0;     // convert from kts to meter/s
1320         double descentRate  = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0;  // convert from feet/min to meter/s
1321
1322         double verticalDistance  = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1323         double descentTimeNeeded = verticalDistance / descentRate;
1324         double distanceCovered   = descentSpeed * descentTimeNeeded; 
1325
1326         //cerr << "Tracking  : " << fgGetString("/ai/track-callsign");
1327         if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1328             cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1329             cerr << "Descent rate      : " << descentRate << endl;
1330             cerr << "Descent speed     : " << descentSpeed << endl;
1331             cerr << "VerticalDistance  : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1332             cerr << "DecentTimeNeeded  : " << descentTimeNeeded << endl;
1333             cerr << "DistanceCovered   : " << distanceCovered   << endl;
1334         }
1335         //cerr << "Distance = " << distance << endl;
1336         distance = distanceCovered;
1337         if (dist < distanceCovered) {
1338               if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1339                    //exit(1);
1340               }
1341               return true;
1342         } else {
1343               return false;
1344         }
1345     } else {
1346          return false;
1347     }
1348 }
1349
1350 void FGAIAircraft::resetPositionFromFlightPlan()
1351 {
1352     // the one behind you
1353     FGAIWaypoint* prev = 0;
1354     // the one ahead
1355     FGAIWaypoint* curr = 0;
1356     // the next plus 1
1357     FGAIWaypoint* next = 0;
1358
1359     prev = fp->getPreviousWaypoint();
1360     curr = fp->getCurrentWaypoint();
1361     next = fp->getNextWaypoint();
1362
1363     setLatitude(prev->getLatitude());
1364     setLongitude(prev->getLongitude());
1365     double tgt_heading = fp->getBearing(curr, next);
1366     setHeading(tgt_heading);
1367     setAltitude(prev->getAltitude());
1368     setSpeed(prev->getSpeed());
1369 }
1370
1371 double FGAIAircraft::getBearing(double crse) 
1372 {
1373   double hdgDiff = fabs(hdg-crse);
1374   if (hdgDiff > 180)
1375       hdgDiff = fabs(hdgDiff - 360);
1376   return hdgDiff;
1377 }
1378
1379 time_t FGAIAircraft::checkForArrivalTime(const string& wptName) {
1380      FGAIWaypoint* curr = 0;
1381      curr = fp->getCurrentWaypoint();
1382
1383      // don't recalculate tracklength unless the start/stop waypoint has changed
1384      if (curr &&
1385          ((curr->getName() != trackCache.startWptName)||
1386           (wptName != trackCache.finalWptName)))
1387      {
1388          trackCache.remainingLength = fp->checkTrackLength(wptName);
1389          trackCache.startWptName = curr->getName();
1390          trackCache.finalWptName = wptName;
1391      }
1392      double tracklength = trackCache.remainingLength;
1393      if (tracklength > 0.1) {
1394           tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1395      } else {
1396          return 0;
1397      }
1398      time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1399      time_t arrivalTime = fp->getArrivalTime();
1400      
1401      time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0); 
1402      time_t secondsToGo = arrivalTime - now;
1403      if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {    
1404           cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1405      }
1406      return (ete - secondsToGo); // Positive when we're too slow...
1407 }
1408
1409 double limitRateOfChange(double cur, double target, double maxDeltaSec, double dt)
1410 {
1411   double delta = target - cur;
1412   double maxDelta = maxDeltaSec * dt;
1413   
1414 // if delta is > maxDelta, use maxDelta, but with the sign of delta.
1415   return (fabs(delta) < maxDelta) ? delta : copysign(maxDelta, delta);
1416 }
1417
1418 // drive various properties in a semi-realistic fashion.
1419 void FGAIAircraft::updateModelProperties(double dt)
1420 {
1421   if (!props) {
1422     return;
1423   }
1424   
1425   SGPropertyNode* gear = props->getChild("gear", 0, true);
1426   double targetGearPos = fp->getCurrentWaypoint()->getGear_down() ? 1.0 : 0.0;
1427   if (!gear->hasValue("gear/position-norm")) {
1428     gear->setDoubleValue("gear/position-norm", targetGearPos);
1429   }
1430   
1431   double gearPosNorm = gear->getDoubleValue("gear/position-norm");
1432   if (gearPosNorm != targetGearPos) {
1433     gearPosNorm += limitRateOfChange(gearPosNorm, targetGearPos, 0.1, dt);
1434     if (gearPosNorm < 0.001) {
1435       gearPosNorm = 0.0;
1436     } else if (gearPosNorm > 0.999) {
1437       gearPosNorm = 1.0;
1438     }
1439     
1440     for (int i=0; i<6; ++i) {
1441       SGPropertyNode* g = gear->getChild("gear", i, true);
1442       g->setDoubleValue("position-norm", gearPosNorm);
1443     } // of gear setting loop      
1444   } // of gear in-transit
1445   
1446 //  double flapPosNorm = props->getDoubleValue();
1447 }
1448