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