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