]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIAircraft.cxx
Merge branch 'next' of gitorious.org:fg/flightgear into next
[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                 checkTcas();
336                 tgt_altitude_ft = curr->crossat;
337             } else {
338                 use_perf_vs = true;
339             }
340         }
341         AccelTo(prev->speed);
342         hdg_lock = alt_lock = true;
343         no_roll = prev->on_ground;
344     }
345 }
346
347 void FGAIAircraft::checkTcas(void)
348 {
349     if (props->getIntValue("tcas/threat-level",0)==3)
350     {
351         int RASense = props->getIntValue("tcas/ra-sense",0);
352         if ((RASense>0)&&(tgt_vs<4000))
353             // upward RA: climb!
354             tgt_vs = 4000;
355         else
356         if (RASense<0)
357         {
358             // downward RA: descend!
359             if (altitude_ft < 1000)
360             {
361                 // too low: level off
362                 if (tgt_vs>0)
363                     tgt_vs = 0;
364             }
365             else
366             {
367                 if (tgt_vs >- 4000)
368                     tgt_vs = -4000;
369             }
370         }
371     }
372 }
373
374 void FGAIAircraft::initializeFlightPlan() {
375 }
376
377
378 bool FGAIAircraft::_getGearDown() const {
379     return _performance->gearExtensible(this);
380 }
381
382
383 const char * FGAIAircraft::_getTransponderCode() const {
384   return transponderCode.c_str();
385 }
386
387
388 bool FGAIAircraft::loadNextLeg(double distance) {
389
390     int leg;
391     if ((leg = fp->getLeg())  == 10) {
392         if (!trafficRef->next()) {
393             return false;
394         }
395         setCallSign(trafficRef->getCallSign());
396         leg = 1;
397         fp->setLeg(leg);
398     }
399
400     FGAirport *dep = trafficRef->getDepartureAirport();
401     FGAirport *arr = trafficRef->getArrivalAirport();
402     if (!(dep && arr)) {
403         setDie(true);
404
405     } else {
406         double cruiseAlt = trafficRef->getCruiseAlt() * 100;
407
408         fp->create (this,
409                     dep,
410                     arr,
411                     leg,
412                     cruiseAlt,
413                     trafficRef->getSpeed(),
414                     _getLatitude(),
415                     _getLongitude(),
416                     false,
417                     trafficRef->getRadius(),
418                     trafficRef->getFlightType(),
419                     acType,
420                     company,
421                     distance);
422        //cerr << "created  leg " << leg << " for " << trafficRef->getCallSign() << endl;
423     }
424     return true;
425 }
426
427
428 // Note: This code is copied from David Luff's AILocalTraffic
429 // Warning - ground elev determination is CPU intensive
430 // Either this function or the logic of how often it is called
431 // will almost certainly change.
432
433 void FGAIAircraft::getGroundElev(double dt) {
434     dt_elev_count += dt;
435
436     if (!needGroundElevation())
437         return;
438     // Update minimally every three secs, but add some randomness
439     // to prevent all AI objects doing this in synchrony
440     if (dt_elev_count < (3.0) + (rand() % 10))
441         return;
442
443     dt_elev_count = 0;
444
445     // Only do the proper hitlist stuff if we are within visible range of the viewer.
446     if (!invisible) {
447         double visibility_meters = fgGetDouble("/environment/visibility-m");
448         FGViewer* vw = globals->get_current_view();
449         
450         if (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters) {
451             return;
452         }
453
454         double range = 500.0;
455         if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
456         {
457             double alt;
458             if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
459             {
460                 tgt_altitude_ft = alt * SG_METER_TO_FEET;
461                 if (isStationary())
462                 {
463                     // aircraft is stationary and we obtained altitude for this spot - we're done.
464                     _needsGroundElevation = false;
465                 }
466             }
467         }
468     }
469 }
470
471
472 void FGAIAircraft::doGroundAltitude() {
473     if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
474         (isStationary()))
475         altitude_ft = (tgt_altitude_ft + groundOffset);
476     else
477         altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
478     tgt_vs = 0;
479 }
480
481
482 void FGAIAircraft::announcePositionToController() {
483     if (trafficRef) {
484         int leg = fp->getLeg();
485
486         // Note that leg has been incremented after creating the current leg, so we should use
487         // leg numbers here that are one higher than the number that is used to create the leg
488         //
489         switch (leg) {
490           case 2:              // Startup and Push back
491             if (trafficRef->getDepartureAirport()->getDynamics())
492                 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
493             break;
494         case 3:              // Taxiing to runway
495             if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
496                 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
497             break;
498         case 4:              //Take off tower controller
499             if (trafficRef->getDepartureAirport()->getDynamics()) {
500                 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
501             } else {
502                 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
503             }
504             break;
505         case 7:
506              if (trafficRef->getDepartureAirport()->getDynamics()) {
507                  controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
508               }
509               break;
510         case 9:              // Taxiing for parking
511             if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
512                 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
513             break;
514         default:
515             controller = 0;
516             break;
517         }
518
519         if ((controller != prevController) && (prevController != 0)) {
520             prevController->signOff(getID());
521         }
522         prevController = controller;
523         if (controller) {
524             controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
525                                          _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
526                                          trafficRef->getRadius(), leg, this);
527         }
528     }
529 }
530
531 // Process ATC instructions and report back
532
533 void FGAIAircraft::processATC(FGATCInstruction instruction) {
534     if (instruction.getCheckForCircularWait()) {
535         // This is not exactly an elegant solution, 
536         // but at least it gives me a chance to check
537         // if circular waits are resolved.
538         // For now, just take the offending aircraft 
539         // out of the scene
540         setDie(true);
541         // a more proper way should be - of course - to
542         // let an offending aircraft take an evasive action
543         // for instance taxi back a little bit.
544     }
545     //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
546     if (instruction.getHoldPattern   ()) {}
547
548     // Hold Position
549     if (instruction.getHoldPosition  ()) {
550         if (!holdPos) {
551             holdPos = true;
552         }
553         AccelTo(0.0);
554     } else {
555         if (holdPos) {
556             //if (trafficRef)
557             //  cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
558             holdPos = false;
559         }
560         // Change speed Instruction. This can only be excecuted when there is no
561         // Hold position instruction.
562         if (instruction.getChangeSpeed   ()) {
563             //  if (trafficRef)
564             //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
565             AccelTo(instruction.getSpeed());
566         } else {
567             if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
568         }
569     }
570     if (instruction.getChangeHeading ()) {
571         hdg_lock = false;
572         TurnTo(instruction.getHeading());
573     } else {
574         if (fp) {
575             hdg_lock = true;
576         }
577     }
578     if (instruction.getChangeAltitude()) {}
579
580 }
581
582
583 void FGAIAircraft::handleFirstWaypoint() {
584     bool eraseWaypoints;         //TODO YAGNI
585     headingError = 0;
586     if (trafficRef) {
587         eraseWaypoints = true;
588     } else {
589         eraseWaypoints = false;
590     }
591
592     FGAIFlightPlan::waypoint* prev = 0; // the one behind you
593     FGAIFlightPlan::waypoint* curr = 0; // the one ahead
594     FGAIFlightPlan::waypoint* next = 0;// the next plus 1
595
596     spinCounter = 0;
597     tempReg = "";
598
599     //TODO fp should handle this
600     fp->IncrementWaypoint(eraseWaypoints);
601     if (!(fp->getNextWaypoint()) && trafficRef)
602         if (!loadNextLeg()) {
603             setDie(true);
604             return;
605         }
606
607     prev = fp->getPreviousWaypoint();   //first waypoint
608     curr = fp->getCurrentWaypoint();    //second waypoint
609     next = fp->getNextWaypoint();       //third waypoint (might not exist!)
610
611     setLatitude(prev->latitude);
612     setLongitude(prev->longitude);
613     setSpeed(prev->speed);
614     setAltitude(prev->altitude);
615
616     if (prev->speed > 0.0)
617         setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
618     else
619         setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
620
621     // If next doesn't exist, as in incrementally created flightplans for
622     // AI/Trafficmanager created plans,
623     // Make sure lead distance is initialized otherwise
624     if (next)
625         fp->setLeadDistance(speed, hdg, curr, next);
626
627     if (curr->crossat > -1000.0) //use a calculated descent/climb rate
628     {
629         use_perf_vs = false;
630         tgt_vs = (curr->crossat - prev->altitude)
631                  / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
632                     / 6076.0 / prev->speed*60.0);
633         checkTcas();
634         tgt_altitude_ft = curr->crossat;
635     } else {
636         use_perf_vs = true;
637         tgt_altitude_ft = prev->altitude;
638     }
639     alt_lock = hdg_lock = true;
640     no_roll = prev->on_ground;
641     if (no_roll) {
642         Transform();             // make sure aip is initialized.
643         getGroundElev(60.1);     // make sure it's executed first time around, so force a large dt value
644         doGroundAltitude();
645         _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
646     }
647     // Make sure to announce the aircraft's position
648     announcePositionToController();
649     prevSpeed = 0;
650 }
651
652
653 /**
654  * Check Execution time (currently once every 100 ms)
655  * Add a bit of randomization to prevent the execution of all flight plans
656  * in synchrony, which can add significant periodic framerate flutter.
657  *
658  * @param now
659  * @return
660  */
661 bool FGAIAircraft::fpExecutable(time_t now) {
662     double rand_exec_time = (rand() % 100) / 100;
663     return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
664 }
665
666
667 /**
668  * Check to see if we've reached the lead point for our next turn
669  *
670  * @param curr
671  * @return
672  */
673 bool FGAIAircraft::leadPointReached(FGAIFlightPlan::waypoint* curr) {
674     double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
675
676     //cerr << "2" << endl;
677     double lead_dist = fp->getLeadDistance();
678     // experimental: Use fabs, because speed can be negative (I hope) during push_back.
679
680     if (lead_dist < fabs(2*speed)) {
681       //don't skip over the waypoint
682       lead_dist = fabs(2*speed);
683       //cerr << "Extending lead distance to " << lead_dist << endl;
684     }
685
686     //prev_dist_to_go = dist_to_go;
687     //if (dist_to_go < lead_dist)
688     //     cerr << trafficRef->getCallSign() << " Distance : " 
689     //          << dist_to_go << ": Lead distance " 
690     //          << lead_dist << " " << curr->name 
691     //          << " Ground target speed " << groundTargetSpeed << endl;
692     double bearing = 0;
693     if (speed > 50) { // don't do bearing calculations for ground traffic
694        bearing = getBearing(fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr));
695        if (bearing < minBearing) {
696             minBearing = bearing;
697             if (minBearing < 10) {
698                  minBearing = 10;
699             }
700             if ((minBearing < 360.0) && (minBearing > 10.0)) {
701                 speedFraction = cos(minBearing *SG_DEGREES_TO_RADIANS);
702             } else {
703                 speedFraction = 1.0;
704             }
705        }
706     } 
707     if (trafficRef) {
708          //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
709 /*         if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
710               cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " " 
711                    << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->name << " " << vs << " " << tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl; 
712          }*/
713      }
714     if ((dist_to_go < lead_dist) || (bearing > (minBearing * 1.1))) {
715         minBearing = 360;
716         return true;
717     } else {
718         return false;
719     }
720 }
721
722
723 bool FGAIAircraft::aiTrafficVisible() {
724   SGGeod userPos(SGGeod::fromDeg(fgGetDouble("/position/longitude-deg"), 
725     fgGetDouble("/position/latitude-deg")));
726   
727   return (SGGeodesy::distanceNm(userPos, pos) <= TRAFFICTOAIDISTTODIE);
728 }
729
730
731 /**
732  * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
733  * in the case of an arrival.
734  *
735  * @param prev
736  * @return
737  */
738
739 //TODO the trafficRef is the right place for the method
740 bool FGAIAircraft::handleAirportEndPoints(FGAIFlightPlan::waypoint* prev, time_t now) {
741     // prepare routing from one airport to another
742     FGAirport * dep = trafficRef->getDepartureAirport();
743     FGAirport * arr = trafficRef->getArrivalAirport();
744
745     if (!( dep && arr))
746         return false;
747
748     // This waypoint marks the fact that the aircraft has passed the initial taxi
749     // departure waypoint, so it can release the parking.
750     //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
751     if (prev->name == "PushBackPoint") {
752         dep->getDynamics()->releaseParking(fp->getGate());
753         AccelTo(0.0);
754         setTaxiClearanceRequest(true);
755     }
756
757     // This is the last taxi waypoint, and marks the the end of the flight plan
758     // so, the schedule should update and wait for the next departure time.
759     if (prev->name == "END") {
760         time_t nextDeparture = trafficRef->getDepartureTime();
761         // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
762         if (nextDeparture < (now+1200)) {
763             nextDeparture = now + 1200;
764         }
765         fp->setTime(nextDeparture); // should be "next departure"
766     }
767
768     return true;
769 }
770
771
772 /**
773  * Check difference between target bearing and current heading and correct if necessary.
774  *
775  * @param curr
776  */
777 void FGAIAircraft::controlHeading(FGAIFlightPlan::waypoint* curr) {
778     double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
779     //cerr << "Bearing = " << calc_bearing << endl;
780     if (speed < 0) {
781         calc_bearing +=180;
782         if (calc_bearing > 360)
783             calc_bearing -= 360;
784     }
785
786     if (finite(calc_bearing)) {
787         double hdg_error = calc_bearing - tgt_heading;
788         if (fabs(hdg_error) > 0.01) {
789             TurnTo( calc_bearing );
790         }
791
792     } else {
793         cerr << "calc_bearing is not a finite number : "
794         << "Speed " << speed
795         << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
796         << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
797         cerr << "waypoint name " << curr->name;
798         exit(1);                 // FIXME
799     }
800 }
801
802
803 /**
804  * Update the lead distance calculation if speed has changed sufficiently
805  * to prevent spinning (hopefully);
806  *
807  * @param curr
808  * @param next
809  */
810 void FGAIAircraft::controlSpeed(FGAIFlightPlan::waypoint* curr, FGAIFlightPlan::waypoint* next) {
811     double speed_diff = speed - prevSpeed;
812
813     if (fabs(speed_diff) > 10) {
814         prevSpeed = speed;
815         if (next) {
816             fp->setLeadDistance(speed, tgt_heading, curr, next);
817         }
818     }
819 }
820
821
822 /**
823  * Update target values (heading, alt, speed) depending on flight plan or control properties
824  */
825 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
826     if (fp)                      // AI object has a flightplan
827     {
828         //TODO make this a function of AIBase
829         time_t now = time(NULL) + fgGetLong("/sim/time/warp");
830         //cerr << "UpateTArgetValues() " << endl;
831         ProcessFlightPlan(dt, now);
832
833         // Do execute Ground elev for inactive aircraft, so they
834         // Are repositioned to the correct ground altitude when the user flies within visibility range.
835         // In addition, check whether we are out of user range, so this aircraft
836         // can be deleted.
837         if (onGround()) {
838                 Transform();     // make sure aip is initialized.
839                 getGroundElev(dt);
840                 doGroundAltitude();
841                 // Transform();
842                 pos.setElevationFt(altitude_ft);
843         }
844         if (trafficRef) {
845            //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
846             aiOutOfSight = !aiTrafficVisible();
847             if (aiOutOfSight) {
848                 setDie(true);
849                 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
850                 aiOutOfSight = true;
851                 return;
852             }
853         }
854         timeElapsed = now - fp->getStartTime();
855         flightplanActive = fp->isActive(now);
856     } else {
857         // no flight plan, update target heading, speed, and altitude
858         // from control properties.  These default to the initial
859         // settings in the config file, but can be changed "on the
860         // fly".
861         string lat_mode = props->getStringValue("controls/flight/lateral-mode");
862         if ( lat_mode == "roll" ) {
863             double angle
864             = props->getDoubleValue("controls/flight/target-roll" );
865             RollTo( angle );
866         } else {
867             double angle
868             = props->getDoubleValue("controls/flight/target-hdg" );
869             TurnTo( angle );
870         }
871
872         string lon_mode
873         = props->getStringValue("controls/flight/longitude-mode");
874         if ( lon_mode == "alt" ) {
875             double alt = props->getDoubleValue("controls/flight/target-alt" );
876             ClimbTo( alt );
877         } else {
878             double angle
879             = props->getDoubleValue("controls/flight/target-pitch" );
880             PitchTo( angle );
881         }
882
883         AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
884     }
885 }
886
887 void FGAIAircraft::updatePosition() {
888     // convert speed to degrees per second
889     double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
890                                  * speed * 1.686 / ft_per_deg_lat;
891     double speed_east_deg_sec  = sin( hdg * SGD_DEGREES_TO_RADIANS )
892                                  * speed * 1.686 / ft_per_deg_lon;
893
894     // set new position
895     pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
896     pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
897 }
898
899
900 void FGAIAircraft::updateHeading() {
901     // adjust heading based on current bank angle
902     if (roll == 0.0)
903         roll = 0.01;
904
905     if (roll != 0.0) {
906         // double turnConstant;
907         //if (no_roll)
908         //  turnConstant = 0.0088362;
909         //else
910         //  turnConstant = 0.088362;
911         // If on ground, calculate heading change directly
912         if (onGround()) {
913             double headingDiff = fabs(hdg-tgt_heading);
914             double bank_sense = 0.0;
915         /*
916         double diff = fabs(hdg - tgt_heading);
917         if (diff > 180)
918             diff = fabs(diff - 360);
919
920         double sum = hdg + diff;
921         if (sum > 360.0)
922             sum -= 360.0;
923         if (fabs(sum - tgt_heading) < 1.0) {
924             bank_sense = 1.0;    // right turn
925         } else {
926             bank_sense = -1.0;   // left turn
927         }*/
928             if (headingDiff > 180)
929                 headingDiff = fabs(headingDiff - 360);
930             double sum = hdg + headingDiff;
931             if (sum > 360.0) 
932                 sum -= 360.0;
933             if (fabs(sum - tgt_heading) > 0.0001) {
934                 bank_sense = -1.0;
935             } else {
936                 bank_sense = 1.0;
937             }
938             //if (trafficRef)
939                 //cerr << trafficRef->getCallSign() << " Heading " 
940                 //     << hdg << ". Target " << tgt_heading <<  ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
941             //if (headingDiff > 60) {
942             groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
943                 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
944             //} else {
945             //    groundTargetSpeed = tgt_speed;
946             //}
947             if (sign(groundTargetSpeed) != sign(tgt_speed))
948                 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
949
950             if (headingDiff > 30.0) {
951                 // invert if pushed backward
952                 headingChangeRate += 10.0 * dt * sign(roll);
953
954                 // Clamp the maximum steering rate to 30 degrees per second,
955                 // But only do this when the heading error is decreasing.
956                 if ((headingDiff < headingError)) {
957                     if (headingChangeRate > 30)
958                         headingChangeRate = 30;
959                     else if (headingChangeRate < -30)
960                         headingChangeRate = -30;
961                 }
962             } else {
963                    if (fabs(headingChangeRate) > headingDiff)
964                        headingChangeRate = headingDiff*sign(roll);
965                    else
966                        headingChangeRate += dt * sign(roll);
967             }
968
969             hdg += headingChangeRate * dt * (fabs(speed) / 15);
970             headingError = headingDiff;
971         } else {
972             if (fabs(speed) > 1.0) {
973                 turn_radius_ft = 0.088362 * speed * speed
974                                  / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
975             } else {
976                 // Check if turn_radius_ft == 0; this might lead to a division by 0.
977                 turn_radius_ft = 1.0;
978             }
979             double turn_circum_ft = SGD_2PI * turn_radius_ft;
980             double dist_covered_ft = speed * 1.686 * dt;
981             double alpha = dist_covered_ft / turn_circum_ft * 360.0;
982             hdg += alpha * sign(roll);
983         }
984         while ( hdg > 360.0 ) {
985             hdg -= 360.0;
986             spinCounter++;
987         }
988         while ( hdg < 0.0) {
989             hdg += 360.0;
990             spinCounter--;
991         }
992     }
993 }
994
995
996 void FGAIAircraft::updateBankAngleTarget() {
997     // adjust target bank angle if heading lock engaged
998     if (hdg_lock) {
999         double bank_sense = 0.0;
1000         double diff = fabs(hdg - tgt_heading);
1001         if (diff > 180)
1002             diff = fabs(diff - 360);
1003
1004         double sum = hdg + diff;
1005         if (sum > 360.0)
1006             sum -= 360.0;
1007         if (fabs(sum - tgt_heading) < 1.0) {
1008             bank_sense = 1.0;    // right turn
1009         } else {
1010             bank_sense = -1.0;   // left turn
1011         }
1012         if (diff < _performance->maximumBankAngle()) {
1013             tgt_roll = diff * bank_sense;
1014         } else {
1015             tgt_roll = _performance->maximumBankAngle() * bank_sense;
1016         }
1017         if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
1018             tgt_speed *= 0.999;  // Ugly hack: If aircraft get stuck, they will continually spin around.
1019             // The only way to resolve this is to make them slow down.
1020         }
1021     }
1022 }
1023
1024
1025 void FGAIAircraft::updateVerticalSpeedTarget() {
1026     // adjust target Altitude, based on ground elevation when on ground
1027     if (onGround()) {
1028         getGroundElev(dt);
1029         doGroundAltitude();
1030     } else if (alt_lock) {
1031         // find target vertical speed
1032         if (use_perf_vs) {
1033             if (altitude_ft < tgt_altitude_ft) {
1034                 tgt_vs = tgt_altitude_ft - altitude_ft;
1035                 if (tgt_vs > _performance->climbRate())
1036                     tgt_vs = _performance->climbRate();
1037             } else {
1038                 tgt_vs = tgt_altitude_ft - altitude_ft;
1039                 if (tgt_vs  < (-_performance->descentRate()))
1040                     tgt_vs = -_performance->descentRate();
1041             }
1042         } else {
1043             double max_vs = 4*(tgt_altitude_ft - altitude_ft);
1044             double min_vs = 100;
1045             if (tgt_altitude_ft < altitude_ft)
1046                 min_vs = -100.0;
1047             if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1048                     && (fabs(max_vs) < fabs(tgt_vs)))
1049                 tgt_vs = max_vs;
1050
1051             if (fabs(tgt_vs) < fabs(min_vs))
1052                 tgt_vs = min_vs;
1053         }
1054     } //else 
1055     //    tgt_vs = 0.0;
1056     checkTcas();
1057 }
1058
1059 void FGAIAircraft::updatePitchAngleTarget() {
1060     // if on ground and above vRotate -> initial rotation
1061     if (onGround() && (speed > _performance->vRotate()))
1062         tgt_pitch = 8.0; // some rough B737 value 
1063
1064     //TODO pitch angle on approach and landing
1065     
1066     // match pitch angle to vertical speed
1067     else if (tgt_vs > 0) {
1068         tgt_pitch = tgt_vs * 0.005;
1069     } else {
1070         tgt_pitch = tgt_vs * 0.002;
1071     }
1072 }
1073
1074 string FGAIAircraft::atGate() {
1075      string tmp("");
1076      if (fp->getLeg() < 3) {
1077          if (trafficRef) {
1078              if (fp->getGate() > 0) {
1079                  FGParking *park =
1080                      trafficRef->getDepartureAirport()->getDynamics()->getParking(fp->getGate());
1081                  tmp = park->getName();
1082              }
1083          }
1084      }
1085      return tmp;
1086 }
1087
1088 void FGAIAircraft::handleATCRequests() {
1089     //TODO implement NullController for having no ATC to save the conditionals
1090     if (controller) {
1091         controller->update(getID(),
1092                            pos.getLatitudeDeg(),
1093                            pos.getLongitudeDeg(),
1094                            hdg,
1095                            speed,
1096                            altitude_ft, dt);
1097         processATC(controller->getInstruction(getID()));
1098     }
1099 }
1100
1101 void FGAIAircraft::updateActualState() {
1102     //update current state
1103     //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1104     updatePosition();
1105
1106     if (onGround())
1107         speed = _performance->actualSpeed(this, groundTargetSpeed, dt);
1108     else
1109         speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt);
1110
1111     updateHeading();
1112     roll = _performance->actualBankAngle(this, tgt_roll, dt);
1113
1114     // adjust altitude (meters) based on current vertical speed (fpm)
1115     altitude_ft += vs / 60.0 * dt;
1116     pos.setElevationFt(altitude_ft);
1117
1118     vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1119     pitch = _performance->actualPitch(this, tgt_pitch, dt);
1120 }
1121
1122 void FGAIAircraft::updateSecondaryTargetValues() {
1123     // derived target state values
1124     updateBankAngleTarget();
1125     updateVerticalSpeedTarget();
1126     updatePitchAngleTarget();
1127
1128     //TODO calculate wind correction angle (tgt_yaw)
1129 }
1130
1131
1132 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1133     FGAIFlightPlan::waypoint* curr = fp->getCurrentWaypoint();
1134     if (curr->name == "BOD") {
1135         double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1136         double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0;     // convert from kts to meter/s
1137         double descentRate  = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0;  // convert from feet/min to meter/s
1138
1139         double verticalDistance  = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1140         double descentTimeNeeded = verticalDistance / descentRate;
1141         double distanceCovered   = descentSpeed * descentTimeNeeded; 
1142
1143         //cerr << "Tracking  : " << fgGetString("/ai/track-callsign");
1144         if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1145             cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1146             cerr << "Descent rate      : " << descentRate << endl;
1147             cerr << "Descent speed     : " << descentSpeed << endl;
1148             cerr << "VerticalDistance  : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1149             cerr << "DecentTimeNeeded  : " << descentTimeNeeded << endl;
1150             cerr << "DistanceCovered   : " << distanceCovered   << endl;
1151         }
1152         //cerr << "Distance = " << distance << endl;
1153         distance = distanceCovered;
1154         if (dist < distanceCovered) {
1155               if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1156                    //exit(1);
1157               }
1158               return true;
1159         } else {
1160               return false;
1161         }
1162     } else {
1163          return false;
1164     }
1165 }
1166
1167 void FGAIAircraft::resetPositionFromFlightPlan()
1168 {
1169     // the one behind you
1170     FGAIFlightPlan::waypoint* prev = 0;
1171     // the one ahead
1172     FGAIFlightPlan::waypoint* curr = 0;
1173     // the next plus 1
1174     FGAIFlightPlan::waypoint* next = 0;
1175
1176     prev = fp->getPreviousWaypoint();
1177     curr = fp->getCurrentWaypoint();
1178     next = fp->getNextWaypoint();
1179
1180     setLatitude(prev->latitude);
1181     setLongitude(prev->longitude);
1182     double tgt_heading = fp->getBearing(curr, next);
1183     setHeading(tgt_heading);
1184     setAltitude(prev->altitude);
1185     setSpeed(prev->speed);
1186 }
1187
1188 double FGAIAircraft::getBearing(double crse) 
1189 {
1190   double hdgDiff = fabs(hdg-crse);
1191   if (hdgDiff > 180)
1192       hdgDiff = fabs(hdgDiff - 360);
1193   return hdgDiff;
1194 }
1195
1196 time_t FGAIAircraft::checkForArrivalTime(string wptName) {
1197      FGAIFlightPlan::waypoint* curr = 0;
1198      curr = fp->getCurrentWaypoint();
1199
1200      double tracklength = fp->checkTrackLength(wptName);
1201      if (tracklength > 0.1) {
1202           tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1203      } else {
1204          return 0;
1205      }
1206      time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1207      time_t arrivalTime = fp->getArrivalTime();
1208      
1209      time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0); 
1210      time_t secondsToGo = arrivalTime - now;
1211      if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {    
1212           cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1213      }
1214      return (ete - secondsToGo); // Positive when we're too slow...
1215 }