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