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