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