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