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