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 <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>
40 # define finite _finite
41 #elif defined(__sun) || defined(sgi)
47 #include "AIAircraft.hxx"
48 #include "performancedata.hxx"
49 #include "performancedb.hxx"
51 //#include <Airports/trafficcontroller.hxx>
53 static string tempReg;
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)
62 groundOffset = trafficRef->getGroundOffset();
63 setCallSign(trafficRef->getCallSign());
78 groundTargetSpeed = 0;
80 // set heading and altitude locks
84 headingChangeRate = 0.0;
90 needsTaxiClearance = false;
91 _needsGroundElevation = true;
93 _performance = 0; //TODO initialize to JET_TRANSPORT from PerformanceDB
98 FGAIAircraft::~FGAIAircraft() {
101 controller->signOff(getID());
105 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
109 FGAIBase::readFromScenario(scFileNode);
111 setPerformance(scFileNode->getStringValue("class", "jet_transport"));
112 setFlightPlan(scFileNode->getStringValue("flightplan"),
113 scFileNode->getBoolValue("repeat", false));
114 setCallSign(scFileNode->getStringValue("callsign"));
118 void FGAIAircraft::bind() {
121 props->tie("controls/gear/gear-down",
122 SGRawValueMethods<FGAIAircraft,bool>(*this,
123 &FGAIAircraft::_getGearDown));
124 props->tie("transponder-id",
125 SGRawValueMethods<FGAIAircraft,const char*>(*this,
126 &FGAIAircraft::_getTransponderCode));
130 void FGAIAircraft::unbind() {
133 props->untie("controls/gear/gear-down");
134 props->untie("transponder-id");
138 void FGAIAircraft::update(double dt) {
139 FGAIBase::update(dt);
144 void FGAIAircraft::setPerformance(const std::string& acclass) {
145 static PerformanceDB perfdb; //TODO make it a global service
146 setPerformance(perfdb.getDataFor(acclass));
150 void FGAIAircraft::setPerformance(PerformanceData *ps) {
155 void FGAIAircraft::Run(double dt) {
156 FGAIAircraft::dt = dt;
158 bool outOfSight = false,
159 flightplanActive = true;
160 updatePrimaryTargetValues(flightplanActive, outOfSight); // target hdg, alt, speed
165 if (!flightplanActive) {
166 groundTargetSpeed = 0;
169 handleATCRequests(); // ATC also has a word to say
170 updateSecondaryTargetValues(); // target roll, vertical speed, pitch
172 // We currently have one situation in which an AIAircraft object is used that is not attached to the
173 // AI manager. In this particular case, the AIAircraft is used to shadow the user's aircraft's behavior in the AI world.
174 // Since we perhaps don't want a radar entry of our own aircraft, the following conditional should probably be adequate
177 UpdateRadar(manager);
181 void FGAIAircraft::checkVisibility()
183 double visibility_meters = fgGetDouble("/environment/visibility-m");
184 FGViewer* vw = globals->get_current_view();
185 invisible = (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters);
190 void FGAIAircraft::AccelTo(double speed) {
193 _needsGroundElevation = true;
197 void FGAIAircraft::PitchTo(double angle) {
203 void FGAIAircraft::RollTo(double angle) {
209 void FGAIAircraft::YawTo(double angle) {
214 void FGAIAircraft::ClimbTo(double alt_ft ) {
215 tgt_altitude_ft = alt_ft;
220 void FGAIAircraft::TurnTo(double heading) {
221 tgt_heading = heading;
226 double FGAIAircraft::sign(double x) {
234 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
235 if (!flightplan.empty()) {
236 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
237 fp->setRepeat(repeat);
243 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
249 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
251 // the one behind you
252 FGAIWaypoint* prev = 0;
254 FGAIWaypoint* curr = 0;
256 FGAIWaypoint* next = 0;
258 prev = fp->getPreviousWaypoint();
259 curr = fp->getCurrentWaypoint();
260 next = fp->getNextWaypoint();
264 ///////////////////////////////////////////////////////////////////////////
265 // Initialize the flightplan
266 //////////////////////////////////////////////////////////////////////////
268 handleFirstWaypoint();
270 } // end of initialization
271 if (! fpExecutable(now))
275 double distanceToDescent;
276 if(reachedEndOfCruise(distanceToDescent)) {
277 if (!loadNextLeg(distanceToDescent)) {
281 prev = fp->getPreviousWaypoint();
282 curr = fp->getCurrentWaypoint();
283 next = fp->getNextWaypoint();
285 if (! leadPointReached(curr)) {
286 controlHeading(curr);
287 controlSpeed(curr, next);
290 cerr << getCallSign()
291 << ": verifying lead distance to waypoint : "
292 << fp->getCurrentWaypoint()->name << " "
293 << fp->getLeadDistance() << ". Distance to go "
294 << (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr))
295 << ". Target speed = "
297 << ". Current speed = "
299 << ". Minimum Bearing " << minBearing
303 if (curr->isFinished()) //end of the flight plan
313 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
314 tgt_heading = fp->getBearing(curr, next);
318 //TODO let the fp handle this (loading of next leg)
319 fp->IncrementWaypoint( trafficRef != 0 );
320 if ( ((!(fp->getNextWaypoint()))) && (trafficRef != 0) )
321 if (!loadNextLeg()) {
326 prev = fp->getPreviousWaypoint();
327 curr = fp->getCurrentWaypoint();
328 next = fp->getNextWaypoint();
330 // Now that we have incremented the waypoints, excute some traffic manager specific code
332 //TODO isn't this best executed right at the beginning?
333 if (! aiTrafficVisible()) {
338 if (! handleAirportEndPoints(prev, now)) {
343 announcePositionToController();
348 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
351 if (!(prev->getOn_ground())) // only update the tgt altitude from flightplan if not on the ground
353 tgt_altitude_ft = prev->getAltitude();
354 if (curr->getCrossat() > -1000.0) {
356 tgt_vs = (curr->getCrossat() - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
357 / 6076.0 / speed*60.0);
359 tgt_altitude_ft = curr->getCrossat();
364 AccelTo(prev->getSpeed());
365 hdg_lock = alt_lock = true;
366 no_roll = prev->getOn_ground();
370 void FGAIAircraft::checkTcas(void)
372 if (props->getIntValue("tcas/threat-level",0)==3)
374 int RASense = props->getIntValue("tcas/ra-sense",0);
375 if ((RASense>0)&&(tgt_vs<4000))
381 // downward RA: descend!
382 if (altitude_ft < 1000)
384 // too low: level off
397 void FGAIAircraft::initializeFlightPlan() {
401 bool FGAIAircraft::_getGearDown() const {
402 return _performance->gearExtensible(this);
406 const char * FGAIAircraft::_getTransponderCode() const {
407 return transponderCode.c_str();
410 // NOTE: Check whether the new (delayed leg increment code has any effect on this code.
411 // Probably not, because it should only be executed after we have already passed the leg incrementing waypoint.
413 bool FGAIAircraft::loadNextLeg(double distance) {
416 if ((leg = fp->getLeg()) == 9) {
417 if (!trafficRef->next()) {
420 setCallSign(trafficRef->getCallSign());
425 FGAirport *dep = trafficRef->getDepartureAirport();
426 FGAirport *arr = trafficRef->getArrivalAirport();
431 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
438 trafficRef->getSpeed(),
442 trafficRef->getRadius(),
443 trafficRef->getFlightType(),
447 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
453 // Note: This code is copied from David Luff's AILocalTraffic
454 // Warning - ground elev determination is CPU intensive
455 // Either this function or the logic of how often it is called
456 // will almost certainly change.
458 void FGAIAircraft::getGroundElev(double dt) {
461 if (!needGroundElevation())
463 // Update minimally every three secs, but add some randomness
464 // to prevent all AI objects doing this in synchrony
465 if (dt_elev_count < (3.0) + (rand() % 10))
470 // Only do the proper hitlist stuff if we are within visible range of the viewer.
472 double visibility_meters = fgGetDouble("/environment/visibility-m");
473 FGViewer* vw = globals->get_current_view();
475 if (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters) {
479 double range = 500.0;
480 if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
483 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
485 tgt_altitude_ft = alt * SG_METER_TO_FEET;
488 // aircraft is stationary and we obtained altitude for this spot - we're done.
489 _needsGroundElevation = false;
497 void FGAIAircraft::doGroundAltitude() {
498 if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
500 altitude_ft = (tgt_altitude_ft + groundOffset);
502 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
507 void FGAIAircraft::announcePositionToController() {
509 int leg = fp->getLeg();
511 // Note that leg has been incremented after creating the current leg, so we should use
512 // leg numbers here that are one higher than the number that is used to create the leg
513 // NOTE: As of July, 30, 2011, the post-creation leg updating is no longer happening.
514 // Leg numbers are updated only once the aircraft passes the last waypoint created for that legm so I should probably just use
515 // the original leg numbers here!
517 case 1: // Startup and Push back
518 if (trafficRef->getDepartureAirport()->getDynamics())
519 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
521 case 2: // Taxiing to runway
522 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
523 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
525 case 3: //Take off tower controller
526 if (trafficRef->getDepartureAirport()->getDynamics()) {
527 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
529 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
533 if (trafficRef->getDepartureAirport()->getDynamics()) {
534 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
537 case 8: // Taxiing for parking
538 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
539 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
546 if ((controller != prevController) && (prevController != 0)) {
547 prevController->signOff(getID());
549 prevController = controller;
551 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
552 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
553 trafficRef->getRadius(), leg, this);
558 // Process ATC instructions and report back
560 void FGAIAircraft::processATC(FGATCInstruction instruction) {
561 if (instruction.getCheckForCircularWait()) {
562 // This is not exactly an elegant solution,
563 // but at least it gives me a chance to check
564 // if circular waits are resolved.
565 // For now, just take the offending aircraft
568 // a more proper way should be - of course - to
569 // let an offending aircraft take an evasive action
570 // for instance taxi back a little bit.
572 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
573 if (instruction.getHoldPattern ()) {}
576 if (instruction.getHoldPosition ()) {
584 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
587 // Change speed Instruction. This can only be excecuted when there is no
588 // Hold position instruction.
589 if (instruction.getChangeSpeed ()) {
591 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
592 AccelTo(instruction.getSpeed());
594 if (fp) AccelTo(fp->getPreviousWaypoint()->getSpeed());
597 if (instruction.getChangeHeading ()) {
599 TurnTo(instruction.getHeading());
605 if (instruction.getChangeAltitude()) {}
610 void FGAIAircraft::handleFirstWaypoint() {
611 bool eraseWaypoints; //TODO YAGNI
614 eraseWaypoints = true;
616 eraseWaypoints = false;
619 FGAIWaypoint* prev = 0; // the one behind you
620 FGAIWaypoint* curr = 0; // the one ahead
621 FGAIWaypoint* next = 0;// the next plus 1
626 //TODO fp should handle this
627 fp->IncrementWaypoint(eraseWaypoints);
628 if (!(fp->getNextWaypoint()) && trafficRef)
629 if (!loadNextLeg()) {
634 prev = fp->getPreviousWaypoint(); //first waypoint
635 curr = fp->getCurrentWaypoint(); //second waypoint
636 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
638 setLatitude(prev->getLatitude());
639 setLongitude(prev->getLongitude());
640 setSpeed(prev->getSpeed());
641 setAltitude(prev->getAltitude());
643 if (prev->getSpeed() > 0.0)
644 setHeading(fp->getBearing(prev->getLatitude(), prev->getLongitude(), curr));
646 setHeading(fp->getBearing(curr->getLatitude(), curr->getLongitude(), prev));
648 // If next doesn't exist, as in incrementally created flightplans for
649 // AI/Trafficmanager created plans,
650 // Make sure lead distance is initialized otherwise
652 fp->setLeadDistance(speed, hdg, curr, next);
654 if (curr->getCrossat() > -1000.0) //use a calculated descent/climb rate
657 tgt_vs = (curr->getCrossat() - prev->getAltitude())
658 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
659 / 6076.0 / prev->getSpeed()*60.0);
661 tgt_altitude_ft = curr->getCrossat();
664 tgt_altitude_ft = prev->getAltitude();
666 alt_lock = hdg_lock = true;
667 no_roll = prev->getOn_ground();
669 Transform(); // make sure aip is initialized.
670 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
672 _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
674 // Make sure to announce the aircraft's position
675 announcePositionToController();
681 * Check Execution time (currently once every 100 ms)
682 * Add a bit of randomization to prevent the execution of all flight plans
683 * in synchrony, which can add significant periodic framerate flutter.
688 bool FGAIAircraft::fpExecutable(time_t now) {
689 double rand_exec_time = (rand() % 100) / 100;
690 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
695 * Check to see if we've reached the lead point for our next turn
700 bool FGAIAircraft::leadPointReached(FGAIWaypoint* curr) {
701 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
703 //cerr << "2" << endl;
704 double lead_dist = fp->getLeadDistance();
705 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
706 if ((dist_to_go < fabs(10.0* speed)) && (speed < 0) && (tgt_speed < 0) && fp->getCurrentWaypoint()->contains("PushBackPoint")) {
707 tgt_speed = -(dist_to_go / 10.0);
708 if (tgt_speed > -0.5) {
711 if (fp->getPreviousWaypoint()->getSpeed() < tgt_speed) {
712 fp->getPreviousWaypoint()->setSpeed(tgt_speed);
715 if (lead_dist < fabs(2*speed)) {
716 //don't skip over the waypoint
717 lead_dist = fabs(2*speed);
718 //cerr << "Extending lead distance to " << lead_dist << endl;
721 //prev_dist_to_go = dist_to_go;
722 //if (dist_to_go < lead_dist)
723 // cerr << trafficRef->getCallSign() << " Distance : "
724 // << dist_to_go << ": Lead distance "
725 // << lead_dist << " " << curr->name
726 // << " Ground target speed " << groundTargetSpeed << endl;
728 if (speed > 50) { // don't do bearing calculations for ground traffic
729 bearing = getBearing(fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr));
730 if (bearing < minBearing) {
731 minBearing = bearing;
732 if (minBearing < 10) {
735 if ((minBearing < 360.0) && (minBearing > 10.0)) {
736 speedFraction = cos(minBearing *SG_DEGREES_TO_RADIANS);
743 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
744 /* if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
745 cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
746 << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->name << " " << vs << " " << tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
749 if ((dist_to_go < lead_dist) || (bearing > (minBearing * 1.1))) {
758 bool FGAIAircraft::aiTrafficVisible() {
759 SGGeod userPos(SGGeod::fromDeg(fgGetDouble("/position/longitude-deg"),
760 fgGetDouble("/position/latitude-deg")));
762 return (SGGeodesy::distanceNm(userPos, pos) <= TRAFFICTOAIDISTTODIE);
767 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
768 * in the case of an arrival.
774 //TODO the trafficRef is the right place for the method
775 bool FGAIAircraft::handleAirportEndPoints(FGAIWaypoint* prev, time_t now) {
776 // prepare routing from one airport to another
777 FGAirport * dep = trafficRef->getDepartureAirport();
778 FGAirport * arr = trafficRef->getArrivalAirport();
783 // This waypoint marks the fact that the aircraft has passed the initial taxi
784 // departure waypoint, so it can release the parking.
785 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
786 if (prev->contains("PushBackPoint")) {
787 dep->getDynamics()->releaseParking(fp->getGate());
789 setTaxiClearanceRequest(true);
791 if (prev->contains("legend")) {
795 // This is the last taxi waypoint, and marks the the end of the flight plan
796 // so, the schedule should update and wait for the next departure time.
797 if (prev->contains("END")) {
798 time_t nextDeparture = trafficRef->getDepartureTime();
799 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
800 if (nextDeparture < (now+1200)) {
801 nextDeparture = now + 1200;
803 fp->setTime(nextDeparture); // should be "next departure"
811 * Check difference between target bearing and current heading and correct if necessary.
815 void FGAIAircraft::controlHeading(FGAIWaypoint* curr) {
816 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
817 //cerr << "Bearing = " << calc_bearing << endl;
820 if (calc_bearing > 360)
824 if (finite(calc_bearing)) {
825 double hdg_error = calc_bearing - tgt_heading;
826 if (fabs(hdg_error) > 0.01) {
827 TurnTo( calc_bearing );
831 cerr << "calc_bearing is not a finite number : "
833 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
834 << "waypoint " << curr->getLatitude() << ", " << curr->getLongitude() << endl;
835 cerr << "waypoint name " << curr->getName();
842 * Update the lead distance calculation if speed has changed sufficiently
843 * to prevent spinning (hopefully);
848 void FGAIAircraft::controlSpeed(FGAIWaypoint* curr, FGAIWaypoint* next) {
849 double speed_diff = speed - prevSpeed;
851 if (fabs(speed_diff) > 10) {
854 fp->setLeadDistance(speed, tgt_heading, curr, next);
861 * Update target values (heading, alt, speed) depending on flight plan or control properties
863 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
864 if (fp) // AI object has a flightplan
866 //TODO make this a function of AIBase
867 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
868 //cerr << "UpateTArgetValues() " << endl;
869 ProcessFlightPlan(dt, now);
871 // Do execute Ground elev for inactive aircraft, so they
872 // Are repositioned to the correct ground altitude when the user flies within visibility range.
873 // In addition, check whether we are out of user range, so this aircraft
876 Transform(); // make sure aip is initialized.
880 pos.setElevationFt(altitude_ft);
883 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
884 aiOutOfSight = !aiTrafficVisible();
887 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
892 timeElapsed = now - fp->getStartTime();
893 flightplanActive = fp->isActive(now);
895 // no flight plan, update target heading, speed, and altitude
896 // from control properties. These default to the initial
897 // settings in the config file, but can be changed "on the
899 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
900 if ( lat_mode == "roll" ) {
902 = props->getDoubleValue("controls/flight/target-roll" );
906 = props->getDoubleValue("controls/flight/target-hdg" );
911 = props->getStringValue("controls/flight/longitude-mode");
912 if ( lon_mode == "alt" ) {
913 double alt = props->getDoubleValue("controls/flight/target-alt" );
917 = props->getDoubleValue("controls/flight/target-pitch" );
921 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
925 void FGAIAircraft::updatePosition() {
926 // convert speed to degrees per second
927 double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
928 * speed * 1.686 / ft_per_deg_lat;
929 double speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
930 * speed * 1.686 / ft_per_deg_lon;
933 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
934 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
938 void FGAIAircraft::updateHeading() {
939 // adjust heading based on current bank angle
944 // double turnConstant;
946 // turnConstant = 0.0088362;
948 // turnConstant = 0.088362;
949 // If on ground, calculate heading change directly
951 double headingDiff = fabs(hdg-tgt_heading);
952 double bank_sense = 0.0;
954 double diff = fabs(hdg - tgt_heading);
956 diff = fabs(diff - 360);
958 double sum = hdg + diff;
961 if (fabs(sum - tgt_heading) < 1.0) {
962 bank_sense = 1.0; // right turn
964 bank_sense = -1.0; // left turn
966 if (headingDiff > 180)
967 headingDiff = fabs(headingDiff - 360);
968 double sum = hdg + headingDiff;
971 if (fabs(sum - tgt_heading) > 0.0001) {
977 // cerr << trafficRef->getCallSign() << " Heading "
978 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
979 //if (headingDiff > 60) {
980 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
981 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
983 // groundTargetSpeed = tgt_speed;
985 if (sign(groundTargetSpeed) != sign(tgt_speed))
986 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
988 // 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.
990 if (headingDiff > 30.0) {
991 // invert if pushed backward
992 headingChangeRate += 10.0 * dt * sign(roll);
994 // Clamp the maximum steering rate to 30 degrees per second,
995 // But only do this when the heading error is decreasing.
996 if ((headingDiff < headingError)) {
997 if (headingChangeRate > 30)
998 headingChangeRate = 30;
999 else if (headingChangeRate < -30)
1000 headingChangeRate = -30;
1004 if (fabs(headingChangeRate) > headingDiff)
1005 headingChangeRate = headingDiff*sign(roll);
1007 headingChangeRate += dt * sign(roll);
1012 //cerr << trafficRef->getCallSign() << " Heading "
1013 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << "Heading change rate : " << headingChangeRate << " bacnk sence " << bank_sense << endl;
1014 hdg += headingChangeRate * dt * sqrt(fabs(speed) / 15);
1015 headingError = headingDiff;
1017 if (fabs(speed) > 1.0) {
1018 turn_radius_ft = 0.088362 * speed * speed
1019 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
1021 // Check if turn_radius_ft == 0; this might lead to a division by 0.
1022 turn_radius_ft = 1.0;
1024 double turn_circum_ft = SGD_2PI * turn_radius_ft;
1025 double dist_covered_ft = speed * 1.686 * dt;
1026 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
1027 hdg += alpha * sign(roll);
1029 while ( hdg > 360.0 ) {
1033 while ( hdg < 0.0) {
1041 void FGAIAircraft::updateBankAngleTarget() {
1042 // adjust target bank angle if heading lock engaged
1044 double bank_sense = 0.0;
1045 double diff = fabs(hdg - tgt_heading);
1047 diff = fabs(diff - 360);
1049 double sum = hdg + diff;
1052 if (fabs(sum - tgt_heading) < 1.0) {
1053 bank_sense = 1.0; // right turn
1055 bank_sense = -1.0; // left turn
1057 if (diff < _performance->maximumBankAngle()) {
1058 tgt_roll = diff * bank_sense;
1060 tgt_roll = _performance->maximumBankAngle() * bank_sense;
1062 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
1063 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
1064 // The only way to resolve this is to make them slow down.
1070 void FGAIAircraft::updateVerticalSpeedTarget() {
1071 // adjust target Altitude, based on ground elevation when on ground
1075 } else if (alt_lock) {
1076 // find target vertical speed
1078 if (altitude_ft < tgt_altitude_ft) {
1079 tgt_vs = tgt_altitude_ft - altitude_ft;
1080 if (tgt_vs > _performance->climbRate())
1081 tgt_vs = _performance->climbRate();
1083 tgt_vs = tgt_altitude_ft - altitude_ft;
1084 if (tgt_vs < (-_performance->descentRate()))
1085 tgt_vs = -_performance->descentRate();
1088 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
1089 double min_vs = 100;
1090 if (tgt_altitude_ft < altitude_ft)
1092 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1093 && (fabs(max_vs) < fabs(tgt_vs)))
1096 if (fabs(tgt_vs) < fabs(min_vs))
1104 void FGAIAircraft::updatePitchAngleTarget() {
1105 // if on ground and above vRotate -> initial rotation
1106 if (onGround() && (speed > _performance->vRotate()))
1107 tgt_pitch = 8.0; // some rough B737 value
1109 //TODO pitch angle on approach and landing
1111 // match pitch angle to vertical speed
1112 else if (tgt_vs > 0) {
1113 tgt_pitch = tgt_vs * 0.005;
1115 tgt_pitch = tgt_vs * 0.002;
1119 string FGAIAircraft::atGate() {
1121 if (fp->getLeg() < 3) {
1123 if (fp->getGate() > 0) {
1125 trafficRef->getDepartureAirport()->getDynamics()->getParking(fp->getGate());
1126 tmp = park->getName();
1133 void FGAIAircraft::handleATCRequests() {
1134 //TODO implement NullController for having no ATC to save the conditionals
1136 controller->updateAircraftInformation(getID(),
1137 pos.getLatitudeDeg(),
1138 pos.getLongitudeDeg(),
1142 processATC(controller->getInstruction(getID()));
1146 void FGAIAircraft::updateActualState() {
1147 //update current state
1148 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1152 speed = _performance->actualSpeed(this, groundTargetSpeed, dt);
1154 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt);
1157 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1159 // adjust altitude (meters) based on current vertical speed (fpm)
1160 altitude_ft += vs / 60.0 * dt;
1161 pos.setElevationFt(altitude_ft);
1163 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1164 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1167 void FGAIAircraft::updateSecondaryTargetValues() {
1168 // derived target state values
1169 updateBankAngleTarget();
1170 updateVerticalSpeedTarget();
1171 updatePitchAngleTarget();
1173 //TODO calculate wind correction angle (tgt_yaw)
1177 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1178 FGAIWaypoint* curr = fp->getCurrentWaypoint();
1179 if (curr->getName() == string("BOD")) {
1180 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1181 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1182 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1184 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1185 double descentTimeNeeded = verticalDistance / descentRate;
1186 double distanceCovered = descentSpeed * descentTimeNeeded;
1188 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1189 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1190 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1191 cerr << "Descent rate : " << descentRate << endl;
1192 cerr << "Descent speed : " << descentSpeed << endl;
1193 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1194 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1195 cerr << "DistanceCovered : " << distanceCovered << endl;
1197 //cerr << "Distance = " << distance << endl;
1198 distance = distanceCovered;
1199 if (dist < distanceCovered) {
1200 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1212 void FGAIAircraft::resetPositionFromFlightPlan()
1214 // the one behind you
1215 FGAIWaypoint* prev = 0;
1217 FGAIWaypoint* curr = 0;
1219 FGAIWaypoint* next = 0;
1221 prev = fp->getPreviousWaypoint();
1222 curr = fp->getCurrentWaypoint();
1223 next = fp->getNextWaypoint();
1225 setLatitude(prev->getLatitude());
1226 setLongitude(prev->getLongitude());
1227 double tgt_heading = fp->getBearing(curr, next);
1228 setHeading(tgt_heading);
1229 setAltitude(prev->getAltitude());
1230 setSpeed(prev->getSpeed());
1233 double FGAIAircraft::getBearing(double crse)
1235 double hdgDiff = fabs(hdg-crse);
1237 hdgDiff = fabs(hdgDiff - 360);
1241 time_t FGAIAircraft::checkForArrivalTime(string wptName) {
1242 FGAIWaypoint* curr = 0;
1243 curr = fp->getCurrentWaypoint();
1245 double tracklength = fp->checkTrackLength(wptName);
1246 if (tracklength > 0.1) {
1247 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1251 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1252 time_t arrivalTime = fp->getArrivalTime();
1254 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1255 time_t secondsToGo = arrivalTime - now;
1256 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1257 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1259 return (ete - secondsToGo); // Positive when we're too slow...