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