1 // FGAIAircraft - FGAIBase-derived class creates an AI airplane
3 // Written by David Culp, started October 2003.
5 // Copyright (C) 2003 David P. Culp - davidculp2@comcast.net
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.
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.
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.
25 #include <Main/fg_props.hxx>
26 #include <Main/globals.hxx>
27 #include <Scenery/scenery.hxx>
28 #include <Scenery/tilemgr.hxx>
29 #include <Airports/dynamics.hxx>
30 #include <Airports/simple.hxx>
38 # define finite _finite
39 #elif defined(__sun) || defined(sgi)
45 #include "AIAircraft.hxx"
46 #include "performancedata.hxx"
47 #include "performancedb.hxx"
50 //#include <Airports/trafficcontroller.hxx>
52 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) :
53 /* HOT must be disabled for AI Aircraft,
54 * otherwise traffic detection isn't working as expected.*/
55 FGAIBase(otAircraft, false)
59 groundOffset = trafficRef->getGroundOffset();
60 setCallSign(trafficRef->getCallSign());
76 groundTargetSpeed = 0;
78 // set heading and altitude locks
82 headingChangeRate = 0.0;
88 needsTaxiClearance = false;
89 _needsGroundElevation = true;
91 _performance = 0; //TODO initialize to JET_TRANSPORT from PerformanceDB
97 FGAIAircraft::~FGAIAircraft() {
100 controller->signOff(getID());
104 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
108 FGAIBase::readFromScenario(scFileNode);
110 setPerformance("", scFileNode->getStringValue("class", "jet_transport"));
111 setFlightPlan(scFileNode->getStringValue("flightplan"),
112 scFileNode->getBoolValue("repeat", false));
113 setCallSign(scFileNode->getStringValue("callsign"));
117 void FGAIAircraft::bind() {
120 tie("controls/gear/gear-down",
121 SGRawValueMethods<FGAIAircraft,bool>(*this,
122 &FGAIAircraft::_getGearDown));
123 tie("transponder-id",
124 SGRawValueMethods<FGAIAircraft,const char*>(*this,
125 &FGAIAircraft::_getTransponderCode));
128 void FGAIAircraft::update(double dt) {
129 FGAIBase::update(dt);
134 void FGAIAircraft::setPerformance(const std::string& acType, const std::string& acclass)
136 static PerformanceDB perfdb; //TODO make it a global service
137 _performance = perfdb.getDataFor(acType, acclass);
141 void FGAIAircraft::setPerformance(PerformanceData *ps) {
146 void FGAIAircraft::Run(double dt) {
147 FGAIAircraft::dt = dt;
149 bool outOfSight = false,
150 flightplanActive = true;
151 updatePrimaryTargetValues(flightplanActive, outOfSight); // target hdg, alt, speed
156 if (!flightplanActive) {
157 groundTargetSpeed = 0;
160 handleATCRequests(); // ATC also has a word to say
161 updateSecondaryTargetValues(); // target roll, vertical speed, pitch
163 // We currently have one situation in which an AIAircraft object is used that is not attached to the
164 // AI manager. In this particular case, the AIAircraft is used to shadow the user's aircraft's behavior in the AI world.
165 // Since we perhaps don't want a radar entry of our own aircraft, the following conditional should probably be adequate
168 UpdateRadar(manager);
172 void FGAIAircraft::checkVisibility()
174 double visibility_meters = fgGetDouble("/environment/visibility-m");
175 invisible = (SGGeodesy::distanceM(globals->get_view_position(), pos) > visibility_meters);
180 void FGAIAircraft::AccelTo(double speed) {
182 //assertSpeed(speed);
184 _needsGroundElevation = true;
188 void FGAIAircraft::PitchTo(double angle) {
194 void FGAIAircraft::RollTo(double angle) {
200 void FGAIAircraft::YawTo(double angle) {
205 void FGAIAircraft::ClimbTo(double alt_ft ) {
206 tgt_altitude_ft = alt_ft;
211 void FGAIAircraft::TurnTo(double heading) {
212 tgt_heading = heading;
217 double FGAIAircraft::sign(double x) {
225 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
226 if (!flightplan.empty()) {
227 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
228 fp->setRepeat(repeat);
234 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
240 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
242 // the one behind you
243 FGAIWaypoint* prev = 0;
245 FGAIWaypoint* curr = 0;
247 FGAIWaypoint* next = 0;
249 prev = fp->getPreviousWaypoint();
250 curr = fp->getCurrentWaypoint();
251 next = fp->getNextWaypoint();
255 ///////////////////////////////////////////////////////////////////////////
256 // Initialize the flightplan
257 //////////////////////////////////////////////////////////////////////////
259 handleFirstWaypoint();
261 } // end of initialization
262 if (! fpExecutable(now))
266 double distanceToDescent;
267 if(reachedEndOfCruise(distanceToDescent)) {
268 if (!loadNextLeg(distanceToDescent)) {
272 prev = fp->getPreviousWaypoint();
273 curr = fp->getCurrentWaypoint();
274 next = fp->getNextWaypoint();
282 if (! leadPointReached(curr)) {
283 controlHeading(curr);
284 controlSpeed(curr, next);
288 cerr << getCallSign()
289 << ": verifying lead distance to waypoint : "
290 << fp->getCurrentWaypoint()->name << " "
291 << fp->getLeadDistance() << ". Distance to go "
292 << (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr))
293 << ". Target speed = "
295 << ". Current speed = "
297 << ". Minimum Bearing " << minBearing
301 if (curr->isFinished()) //end of the flight plan
311 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
312 tgt_heading = fp->getBearing(curr, next);
316 //TODO let the fp handle this (loading of next leg)
317 fp->IncrementWaypoint( trafficRef != 0 );
318 if ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
319 if (!loadNextLeg()) {
324 prev = fp->getPreviousWaypoint();
325 curr = fp->getCurrentWaypoint();
326 next = fp->getNextWaypoint();
328 // Now that we have incremented the waypoints, excute some traffic manager specific code
330 //TODO isn't this best executed right at the beginning?
331 if (! aiTrafficVisible()) {
336 if (! handleAirportEndPoints(prev, now)) {
341 announcePositionToController();
346 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
350 if (!(prev->getOn_ground())) // only update the tgt altitude from flightplan if not on the ground
352 tgt_altitude_ft = prev->getAltitude();
353 if (curr->getCrossat() > -1000.0) {
355 // Distance to go in meters
356 double vert_dist_ft = curr->getCrossat() - altitude_ft;
357 double err_dist = prev->getCrossat() - altitude_ft;
358 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
359 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
362 tgt_altitude_ft = curr->getCrossat();
367 AccelTo(prev->getSpeed());
368 hdg_lock = alt_lock = true;
369 no_roll = prev->getOn_ground();
373 double FGAIAircraft::calcVerticalSpeed(double vert_ft, double dist_m, double speed, double err)
375 // err is negative when we passed too high
376 double vert_m = vert_ft * SG_FEET_TO_METER;
377 //double err_m = err * SG_FEET_TO_METER;
378 //double angle = atan2(vert_m, dist_m);
379 double speedMs = (speed * SG_NM_TO_METER) / 3600;
380 //double vs = cos(angle) * speedMs; // Now in m/s
382 //cerr << "Error term = " << err_m << endl;
384 vs = ((vert_m) / dist_m) * speedMs;
386 // Convert to feet per minute
387 vs *= (SG_METER_TO_FEET * 60);
388 //if (getCallSign() == "LUFTHANSA2002")
389 //if (fabs(vs) > 100000) {
390 // if (getCallSign() == "LUFTHANSA2057") {
391 // cerr << getCallSign() << " " << fp->getPreviousWaypoint()->getName() << ". Alt = " << altitude_ft << " vertical dist = " << vert_m << " horiz dist = " << dist_m << " << angle = " << angle * SG_RADIANS_TO_DEGREES << " vs " << vs << " horizontal speed " << speed << "Previous crossAT " << fp->getPreviousWaypoint()->getCrossat() << endl;
392 // //= (curr->getCrossat() - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
393 // // / 6076.0 / speed*60.0);
399 void FGAIAircraft::assertSpeed(double speed)
401 if ((speed < -50) || (speed > 1000)) {
402 cerr << getCallSign() << " "
403 << "Previous waypoint " << fp->getPreviousWaypoint()->getName() << " "
404 << "Departure airport " << trafficRef->getDepartureAirport() << " "
405 << "Leg " << fp->getLeg() << " "
406 << "target_speed << " << tgt_speed << " "
407 << "speedFraction << " << speedFraction << " "
408 << "Currecnt speed << " << speed << " "
416 void FGAIAircraft::checkTcas(void)
418 if (props->getIntValue("tcas/threat-level",0)==3)
420 int RASense = props->getIntValue("tcas/ra-sense",0);
421 if ((RASense>0)&&(tgt_vs<4000))
427 // downward RA: descend!
428 if (altitude_ft < 1000)
430 // too low: level off
443 void FGAIAircraft::initializeFlightPlan() {
447 bool FGAIAircraft::_getGearDown() const {
448 return _performance->gearExtensible(this);
452 const char * FGAIAircraft::_getTransponderCode() const {
453 return transponderCode.c_str();
456 // NOTE: Check whether the new (delayed leg increment code has any effect on this code.
457 // Probably not, because it should only be executed after we have already passed the leg incrementing waypoint.
459 bool FGAIAircraft::loadNextLeg(double distance) {
462 if ((leg = fp->getLeg()) == 9) {
463 if (!trafficRef->next()) {
466 setCallSign(trafficRef->getCallSign());
471 FGAirport *dep = trafficRef->getDepartureAirport();
472 FGAirport *arr = trafficRef->getArrivalAirport();
477 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
484 trafficRef->getSpeed(),
488 trafficRef->getRadius(),
489 trafficRef->getFlightType(),
493 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
499 // Note: This code is copied from David Luff's AILocalTraffic
500 // Warning - ground elev determination is CPU intensive
501 // Either this function or the logic of how often it is called
502 // will almost certainly change.
504 void FGAIAircraft::getGroundElev(double dt) {
507 if (!needGroundElevation())
509 // Update minimally every three secs, but add some randomness
510 // to prevent all AI objects doing this in synchrony
511 if (dt_elev_count < (3.0) + (rand() % 10))
516 // Only do the proper hitlist stuff if we are within visible range of the viewer.
518 double visibility_meters = fgGetDouble("/environment/visibility-m");
519 if (SGGeodesy::distanceM(globals->get_view_position(), pos) > visibility_meters) {
523 double range = 500.0;
524 if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
527 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
529 tgt_altitude_ft = alt * SG_METER_TO_FEET;
532 // aircraft is stationary and we obtained altitude for this spot - we're done.
533 _needsGroundElevation = false;
541 void FGAIAircraft::doGroundAltitude() {
542 if ((fp->getLeg() == 7) && ((altitude_ft - tgt_altitude_ft) > 5)) {
545 if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
547 altitude_ft = (tgt_altitude_ft + groundOffset);
549 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
555 void FGAIAircraft::announcePositionToController() {
557 int leg = fp->getLeg();
559 // Note that leg has been incremented after creating the current leg, so we should use
560 // leg numbers here that are one higher than the number that is used to create the leg
561 // NOTE: As of July, 30, 2011, the post-creation leg updating is no longer happening.
562 // Leg numbers are updated only once the aircraft passes the last waypoint created for that legm so I should probably just use
563 // the original leg numbers here!
565 case 1: // Startup and Push back
566 if (trafficRef->getDepartureAirport()->getDynamics())
567 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
569 case 2: // Taxiing to runway
570 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
571 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
573 case 3: //Take off tower controller
574 if (trafficRef->getDepartureAirport()->getDynamics()) {
575 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
578 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
582 if (trafficRef->getDepartureAirport()->getDynamics()) {
583 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
586 case 8: // Taxiing for parking
587 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
588 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
595 if ((controller != prevController) && (prevController != 0)) {
596 prevController->signOff(getID());
598 prevController = controller;
600 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
601 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
602 trafficRef->getRadius(), leg, this);
607 void FGAIAircraft::scheduleForATCTowerDepartureControl(int state) {
608 if (!takeOffStatus) {
609 int leg = fp->getLeg();
611 if (trafficRef->getDepartureAirport()->getDynamics()) {
612 towerController = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
614 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
616 if (towerController) {
617 towerController->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
618 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
619 trafficRef->getRadius(), leg, this);
620 //cerr << "Scheduling " << trafficRef->getCallSign() << " for takeoff " << endl;
624 takeOffStatus = state;
627 // Process ATC instructions and report back
629 void FGAIAircraft::processATC(FGATCInstruction instruction) {
630 if (instruction.getCheckForCircularWait()) {
631 // This is not exactly an elegant solution,
632 // but at least it gives me a chance to check
633 // if circular waits are resolved.
634 // For now, just take the offending aircraft
637 // a more proper way should be - of course - to
638 // let an offending aircraft take an evasive action
639 // for instance taxi back a little bit.
641 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
642 if (instruction.getHoldPattern ()) {}
645 if (instruction.getHoldPosition ()) {
653 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
656 // Change speed Instruction. This can only be excecuted when there is no
657 // Hold position instruction.
658 if (instruction.getChangeSpeed ()) {
660 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
661 AccelTo(instruction.getSpeed());
663 if (fp) AccelTo(fp->getPreviousWaypoint()->getSpeed());
666 if (instruction.getChangeHeading ()) {
668 TurnTo(instruction.getHeading());
674 if (instruction.getChangeAltitude()) {}
679 void FGAIAircraft::handleFirstWaypoint() {
680 bool eraseWaypoints; //TODO YAGNI
683 eraseWaypoints = true;
685 eraseWaypoints = false;
688 FGAIWaypoint* prev = 0; // the one behind you
689 FGAIWaypoint* curr = 0; // the one ahead
690 FGAIWaypoint* next = 0;// the next plus 1
694 //TODO fp should handle this
695 fp->IncrementWaypoint(eraseWaypoints);
696 if (!(fp->getNextWaypoint()) && trafficRef)
697 if (!loadNextLeg()) {
702 prev = fp->getPreviousWaypoint(); //first waypoint
703 curr = fp->getCurrentWaypoint(); //second waypoint
704 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
706 setLatitude(prev->getLatitude());
707 setLongitude(prev->getLongitude());
708 setSpeed(prev->getSpeed());
709 setAltitude(prev->getAltitude());
711 if (prev->getSpeed() > 0.0)
712 setHeading(fp->getBearing(prev, curr));
714 setHeading(fp->getBearing(curr, prev));
716 // If next doesn't exist, as in incrementally created flightplans for
717 // AI/Trafficmanager created plans,
718 // Make sure lead distance is initialized otherwise
720 fp->setLeadDistance(speed, hdg, curr, next);
722 if (curr->getCrossat() > -1000.0) //use a calculated descent/climb rate
725 //tgt_vs = (curr->getCrossat() - prev->getAltitude())
726 // / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
727 // / 6076.0 / prev->getSpeed()*60.0);
728 double vert_dist_ft = curr->getCrossat() - altitude_ft;
729 double err_dist = prev->getCrossat() - altitude_ft;
730 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
731 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
733 tgt_altitude_ft = curr->getCrossat();
736 tgt_altitude_ft = prev->getAltitude();
738 alt_lock = hdg_lock = true;
739 no_roll = prev->getOn_ground();
741 Transform(); // make sure aip is initialized.
742 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
744 _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
746 // Make sure to announce the aircraft's position
747 announcePositionToController();
753 * Check Execution time (currently once every 100 ms)
754 * Add a bit of randomization to prevent the execution of all flight plans
755 * in synchrony, which can add significant periodic framerate flutter.
760 bool FGAIAircraft::fpExecutable(time_t now) {
761 double rand_exec_time = (rand() % 100) / 100;
762 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
767 * Check to see if we've reached the lead point for our next turn
772 bool FGAIAircraft::leadPointReached(FGAIWaypoint* curr) {
773 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
775 //cerr << "2" << endl;
776 double lead_dist = fp->getLeadDistance();
777 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
778 if ((dist_to_go < fabs(10.0* speed)) && (speed < 0) && (tgt_speed < 0) && fp->getCurrentWaypoint()->contains("PushBackPoint")) {
779 tgt_speed = -(dist_to_go / 10.0);
780 if (tgt_speed > -0.5) {
783 //assertSpeed(tgt_speed);
784 if (fp->getPreviousWaypoint()->getSpeed() < tgt_speed) {
785 fp->getPreviousWaypoint()->setSpeed(tgt_speed);
788 if (lead_dist < fabs(2*speed)) {
789 //don't skip over the waypoint
790 lead_dist = fabs(2*speed);
791 //cerr << "Extending lead distance to " << lead_dist << endl;
794 //prev_dist_to_go = dist_to_go;
795 //if (dist_to_go < lead_dist)
796 // cerr << trafficRef->getCallSign() << " Distance : "
797 // << dist_to_go << ": Lead distance "
798 // << lead_dist << " " << curr->name
799 // << " Ground target speed " << groundTargetSpeed << endl;
801 // don't do bearing calculations for ground traffic
802 bearing = getBearing(fp->getBearing(pos, curr));
803 if (bearing < minBearing) {
804 minBearing = bearing;
805 if (minBearing < 10) {
808 if ((minBearing < 360.0) && (minBearing > 10.0)) {
809 speedFraction = 0.5 + (cos(minBearing *SG_DEGREES_TO_RADIANS) * 0.5);
815 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
816 //if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
817 //cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
818 // << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->getName() << " " << vs << " " << //tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
821 if ((dist_to_go < lead_dist) ||
822 ((dist_to_go > prev_dist_to_go) && (bearing > (minBearing * 1.1))) ) {
825 prev_dist_to_go = HUGE_VAL;
828 prev_dist_to_go = dist_to_go;
834 bool FGAIAircraft::aiTrafficVisible()
836 SGVec3d cartPos = SGVec3d::fromGeod(pos);
837 const double d2 = (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER) *
838 (TRAFFICTOAIDISTTODIE * SG_NM_TO_METER);
839 return (distSqr(cartPos, globals->get_aircraft_position_cart()) < d2);
844 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
845 * in the case of an arrival.
851 //TODO the trafficRef is the right place for the method
852 bool FGAIAircraft::handleAirportEndPoints(FGAIWaypoint* prev, time_t now) {
853 // prepare routing from one airport to another
854 FGAirport * dep = trafficRef->getDepartureAirport();
855 FGAirport * arr = trafficRef->getArrivalAirport();
860 // This waypoint marks the fact that the aircraft has passed the initial taxi
861 // departure waypoint, so it can release the parking.
862 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
863 //cerr << "Passing waypoint : " << prev->getName() << endl;
864 if (prev->contains("PushBackPoint")) {
865 // clearing the parking assignment will release the gate
866 fp->setGate(ParkingAssignment());
868 //setTaxiClearanceRequest(true);
870 if (prev->contains("legend")) {
873 if (prev->contains(string("DepartureHold"))) {
874 //cerr << "Passing point DepartureHold" << endl;
875 scheduleForATCTowerDepartureControl(1);
877 if (prev->contains(string("Accel"))) {
880 //if (prev->contains(string("landing"))) {
881 // if (speed < _performance->vTaxi() * 2) {
882 // fp->shortenToFirst(2, "legend");
885 //if (prev->contains(string("final"))) {
887 // cerr << getCallSign() << " "
888 // << fp->getPreviousWaypoint()->getName()
889 // << ". Alt = " << altitude_ft
891 // << " horizontal speed " << speed
892 // << "Previous crossAT " << fp->getPreviousWaypoint()->getCrossat()
893 // << "Airport elevation" << getTrafficRef()->getArrivalAirport()->getElevation()
894 // << "Altitude difference " << (altitude_ft - fp->getPreviousWaypoint()->getCrossat()) << endl;
896 // This is the last taxi waypoint, and marks the the end of the flight plan
897 // so, the schedule should update and wait for the next departure time.
898 if (prev->contains("END")) {
899 time_t nextDeparture = trafficRef->getDepartureTime();
900 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
901 if (nextDeparture < (now+1200)) {
902 nextDeparture = now + 1200;
904 fp->setTime(nextDeparture);
912 * Check difference between target bearing and current heading and correct if necessary.
916 void FGAIAircraft::controlHeading(FGAIWaypoint* curr) {
917 double calc_bearing = fp->getBearing(pos, curr);
918 //cerr << "Bearing = " << calc_bearing << endl;
921 SG_NORMALIZE_RANGE(calc_bearing, 0.0, 360.0);
924 if (finite(calc_bearing)) {
925 double hdg_error = calc_bearing - tgt_heading;
926 if (fabs(hdg_error) > 0.01) {
927 TurnTo( calc_bearing );
931 cerr << "calc_bearing is not a finite number : "
933 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
934 << ", waypoint: " << curr->getLatitude() << ", " << curr->getLongitude() << endl;
935 cerr << "waypoint name: '" << curr->getName() << "'" << endl;
942 * Update the lead distance calculation if speed has changed sufficiently
943 * to prevent spinning (hopefully);
948 void FGAIAircraft::controlSpeed(FGAIWaypoint* curr, FGAIWaypoint* next) {
949 double speed_diff = speed - prevSpeed;
951 if (fabs(speed_diff) > 10) {
953 //assertSpeed(speed);
955 fp->setLeadDistance(speed, tgt_heading, curr, next);
962 * Update target values (heading, alt, speed) depending on flight plan or control properties
964 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
965 if (fp) // AI object has a flightplan
967 //TODO make this a function of AIBase
968 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
969 //cerr << "UpateTArgetValues() " << endl;
970 ProcessFlightPlan(dt, now);
972 // Do execute Ground elev for inactive aircraft, so they
973 // Are repositioned to the correct ground altitude when the user flies within visibility range.
974 // In addition, check whether we are out of user range, so this aircraft
977 Transform(); // make sure aip is initialized.
981 pos.setElevationFt(altitude_ft);
984 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
985 aiOutOfSight = !aiTrafficVisible();
988 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
993 timeElapsed = now - fp->getStartTime();
994 flightplanActive = fp->isActive(now);
996 // no flight plan, update target heading, speed, and altitude
997 // from control properties. These default to the initial
998 // settings in the config file, but can be changed "on the
1000 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
1001 if ( lat_mode == "roll" ) {
1003 = props->getDoubleValue("controls/flight/target-roll" );
1007 = props->getDoubleValue("controls/flight/target-hdg" );
1012 = props->getStringValue("controls/flight/longitude-mode");
1013 if ( lon_mode == "alt" ) {
1014 double alt = props->getDoubleValue("controls/flight/target-alt" );
1018 = props->getDoubleValue("controls/flight/target-pitch" );
1022 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
1026 void FGAIAircraft::updateHeading() {
1027 // adjust heading based on current bank angle
1032 // double turnConstant;
1034 // turnConstant = 0.0088362;
1036 // turnConstant = 0.088362;
1037 // If on ground, calculate heading change directly
1039 double headingDiff = fabs(hdg-tgt_heading);
1040 // double bank_sense = 0.0;
1042 double diff = fabs(hdg - tgt_heading);
1044 diff = fabs(diff - 360);
1046 double sum = hdg + diff;
1049 if (fabs(sum - tgt_heading) < 1.0) {
1050 bank_sense = 1.0; // right turn
1052 bank_sense = -1.0; // left turn
1054 if (headingDiff > 180)
1055 headingDiff = fabs(headingDiff - 360);
1056 double sum = hdg + headingDiff;
1059 if (fabs(sum - tgt_heading) > 0.0001) {
1060 // bank_sense = -1.0;
1062 // bank_sense = 1.0;
1065 // cerr << trafficRef->getCallSign() << " Heading "
1066 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
1067 //if (headingDiff > 60) {
1068 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
1069 //assertSpeed(groundTargetSpeed);
1070 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
1072 // groundTargetSpeed = tgt_speed;
1074 if (sign(groundTargetSpeed) != sign(tgt_speed))
1075 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
1076 //assertSpeed(groundTargetSpeed);
1077 // 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.
1079 if (headingDiff > 30.0) {
1080 // invert if pushed backward
1081 headingChangeRate += 10.0 * dt * sign(roll);
1083 // Clamp the maximum steering rate to 30 degrees per second,
1084 // But only do this when the heading error is decreasing.
1085 if ((headingDiff < headingError)) {
1086 if (headingChangeRate > 30)
1087 headingChangeRate = 30;
1088 else if (headingChangeRate < -30)
1089 headingChangeRate = -30;
1093 if (fabs(headingChangeRate) > headingDiff)
1094 headingChangeRate = headingDiff*sign(roll);
1096 headingChangeRate += dt * sign(roll);
1101 //cerr << trafficRef->getCallSign() << " Heading "
1102 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << "Heading change rate : " << headingChangeRate << " bacnk sence " << bank_sense << endl;
1103 hdg += headingChangeRate * dt * sqrt(fabs(speed) / 15);
1104 headingError = headingDiff;
1105 if (fabs(headingError) < 1.0) {
1109 if (fabs(speed) > 1.0) {
1110 turn_radius_ft = 0.088362 * speed * speed
1111 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
1113 // Check if turn_radius_ft == 0; this might lead to a division by 0.
1114 turn_radius_ft = 1.0;
1116 double turn_circum_ft = SGD_2PI * turn_radius_ft;
1117 double dist_covered_ft = speed * 1.686 * dt;
1118 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
1119 hdg += alpha * sign(roll);
1121 while ( hdg > 360.0 ) {
1125 while ( hdg < 0.0) {
1133 void FGAIAircraft::updateBankAngleTarget() {
1134 // adjust target bank angle if heading lock engaged
1136 double bank_sense = 0.0;
1137 double diff = fabs(hdg - tgt_heading);
1139 diff = fabs(diff - 360);
1141 double sum = hdg + diff;
1144 if (fabs(sum - tgt_heading) < 1.0) {
1145 bank_sense = 1.0; // right turn
1147 bank_sense = -1.0; // left turn
1149 if (diff < _performance->maximumBankAngle()) {
1150 tgt_roll = diff * bank_sense;
1152 tgt_roll = _performance->maximumBankAngle() * bank_sense;
1154 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
1155 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
1156 // The only way to resolve this is to make them slow down.
1162 void FGAIAircraft::updateVerticalSpeedTarget() {
1163 // adjust target Altitude, based on ground elevation when on ground
1167 } else if (alt_lock) {
1168 // find target vertical speed
1170 if (altitude_ft < tgt_altitude_ft) {
1171 tgt_vs = std::min(tgt_altitude_ft - altitude_ft, _performance->climbRate());
1173 tgt_vs = std::max(tgt_altitude_ft - altitude_ft, -_performance->descentRate());
1176 double vert_dist_ft = fp->getCurrentWaypoint()->getCrossat() - altitude_ft;
1177 double err_dist = 0; //prev->getCrossat() - altitude_ft;
1178 double dist_m = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), fp->getCurrentWaypoint());
1179 tgt_vs = calcVerticalSpeed(vert_dist_ft, dist_m, speed, err_dist);
1180 //cerr << "Target vs before : " << tgt_vs;
1181 /* double max_vs = 10*(tgt_altitude_ft - altitude_ft);
1182 double min_vs = 100;
1183 if (tgt_altitude_ft < altitude_ft)
1185 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1186 && (fabs(max_vs) < fabs(tgt_vs)))
1189 if (fabs(tgt_vs) < fabs(min_vs))
1191 //cerr << "target vs : after " << tgt_vs << endl;
1198 void FGAIAircraft::updatePitchAngleTarget() {
1199 // if on ground and above vRotate -> initial rotation
1200 if (onGround() && (speed > _performance->vRotate()))
1201 tgt_pitch = 8.0; // some rough B737 value
1203 //TODO pitch angle on approach and landing
1205 // match pitch angle to vertical speed
1206 else if (tgt_vs > 0) {
1207 tgt_pitch = tgt_vs * 0.005;
1209 tgt_pitch = tgt_vs * 0.002;
1213 string FGAIAircraft::atGate()
1215 if ((fp->getLeg() < 3) && trafficRef) {
1216 if (fp->getParkingGate()) {
1217 return fp->getParkingGate()->ident();
1224 void FGAIAircraft::handleATCRequests() {
1225 //TODO implement NullController for having no ATC to save the conditionals
1227 controller->updateAircraftInformation(getID(),
1228 pos.getLatitudeDeg(),
1229 pos.getLongitudeDeg(),
1233 processATC(controller->getInstruction(getID()));
1235 if (towerController) {
1236 towerController->updateAircraftInformation(getID(),
1237 pos.getLatitudeDeg(),
1238 pos.getLongitudeDeg(),
1245 void FGAIAircraft::updateActualState() {
1246 //update current state
1247 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1248 double distance = speed * SG_KT_TO_MPS * dt;
1249 pos = SGGeodesy::direct(pos, hdg, distance);
1253 speed = _performance->actualSpeed(this, groundTargetSpeed, dt, holdPos);
1255 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt, false);
1256 //assertSpeed(speed);
1258 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1260 // adjust altitude (meters) based on current vertical speed (fpm)
1261 altitude_ft += vs / 60.0 * dt;
1262 pos.setElevationFt(altitude_ft);
1264 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1265 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1268 void FGAIAircraft::updateSecondaryTargetValues() {
1269 // derived target state values
1270 updateBankAngleTarget();
1271 updateVerticalSpeedTarget();
1272 updatePitchAngleTarget();
1274 //TODO calculate wind correction angle (tgt_yaw)
1278 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1279 FGAIWaypoint* curr = fp->getCurrentWaypoint();
1280 if (curr->getName() == string("BOD")) {
1281 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1282 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1283 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1285 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1286 double descentTimeNeeded = verticalDistance / descentRate;
1287 double distanceCovered = descentSpeed * descentTimeNeeded;
1289 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1290 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1291 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1292 cerr << "Descent rate : " << descentRate << endl;
1293 cerr << "Descent speed : " << descentSpeed << endl;
1294 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1295 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1296 cerr << "DistanceCovered : " << distanceCovered << endl;
1298 //cerr << "Distance = " << distance << endl;
1299 distance = distanceCovered;
1300 if (dist < distanceCovered) {
1301 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1313 void FGAIAircraft::resetPositionFromFlightPlan()
1315 // the one behind you
1316 FGAIWaypoint* prev = 0;
1318 FGAIWaypoint* curr = 0;
1320 FGAIWaypoint* next = 0;
1322 prev = fp->getPreviousWaypoint();
1323 curr = fp->getCurrentWaypoint();
1324 next = fp->getNextWaypoint();
1326 setLatitude(prev->getLatitude());
1327 setLongitude(prev->getLongitude());
1328 double tgt_heading = fp->getBearing(curr, next);
1329 setHeading(tgt_heading);
1330 setAltitude(prev->getAltitude());
1331 setSpeed(prev->getSpeed());
1334 double FGAIAircraft::getBearing(double crse)
1336 double hdgDiff = fabs(hdg-crse);
1338 hdgDiff = fabs(hdgDiff - 360);
1342 time_t FGAIAircraft::checkForArrivalTime(string wptName) {
1343 FGAIWaypoint* curr = 0;
1344 curr = fp->getCurrentWaypoint();
1346 double tracklength = fp->checkTrackLength(wptName);
1347 if (tracklength > 0.1) {
1348 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1352 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1353 time_t arrivalTime = fp->getArrivalTime();
1355 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1356 time_t secondsToGo = arrivalTime - now;
1357 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1358 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1360 return (ete - secondsToGo); // Positive when we're too slow...