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