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