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