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