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