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