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