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