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) : FGAIBase(otAircraft) {
58 groundOffset = trafficRef->getGroundOffset();
59 setCallSign(trafficRef->getCallSign());
74 groundTargetSpeed = 0;
76 // set heading and altitude locks
80 headingChangeRate = 0.0;
86 needsTaxiClearance = false;
87 _needsGroundElevation = true;
89 _performance = 0; //TODO initialize to JET_TRANSPORT from PerformanceDB
94 FGAIAircraft::~FGAIAircraft() {
97 controller->signOff(getID());
101 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
105 FGAIBase::readFromScenario(scFileNode);
107 setPerformance(scFileNode->getStringValue("class", "jet_transport"));
108 setFlightPlan(scFileNode->getStringValue("flightplan"),
109 scFileNode->getBoolValue("repeat", false));
110 setCallSign(scFileNode->getStringValue("callsign"));
114 void FGAIAircraft::bind() {
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));
126 void FGAIAircraft::unbind() {
129 props->untie("controls/gear/gear-down");
130 props->untie("transponder-id");
134 void FGAIAircraft::update(double dt) {
135 FGAIBase::update(dt);
140 void FGAIAircraft::setPerformance(const std::string& acclass) {
141 static PerformanceDB perfdb; //TODO make it a global service
142 setPerformance(perfdb.getDataFor(acclass));
146 void FGAIAircraft::setPerformance(PerformanceData *ps) {
151 void FGAIAircraft::Run(double dt) {
152 FGAIAircraft::dt = dt;
154 bool outOfSight = false,
155 flightplanActive = true;
156 updatePrimaryTargetValues(flightplanActive, outOfSight); // target hdg, alt, speed
161 if (!flightplanActive) {
162 groundTargetSpeed = 0;
165 handleATCRequests(); // ATC also has a word to say
166 updateSecondaryTargetValues(); // target roll, vertical speed, pitch
168 UpdateRadar(manager);
172 void FGAIAircraft::checkVisibility()
174 double visibility_meters = fgGetDouble("/environment/visibility-m");
175 FGViewer* vw = globals->get_current_view();
176 invisible = (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters);
181 void FGAIAircraft::AccelTo(double 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 FGAIFlightPlan::waypoint* prev = 0;
245 FGAIFlightPlan::waypoint* curr = 0;
247 FGAIFlightPlan::waypoint* 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();
276 if (! leadPointReached(curr)) {
277 controlHeading(curr);
278 controlSpeed(curr, next);
280 if (curr->finished) //end of the flight plan
290 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
291 tgt_heading = fp->getBearing(curr, next);
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()) {
303 prev = fp->getPreviousWaypoint();
304 curr = fp->getCurrentWaypoint();
305 next = fp->getNextWaypoint();
307 // Now that we have incremented the waypoints, excute some traffic manager specific code
309 //TODO isn't this best executed right at the beginning?
310 if (! aiTrafficVisible()) {
315 if (! handleAirportEndPoints(prev, now)) {
320 announcePositionToController();
325 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
328 if (!(prev->on_ground)) // only update the tgt altitude from flightplan if not on the ground
330 tgt_altitude_ft = prev->altitude;
331 if (curr->crossat > -1000.0) {
333 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
334 / 6076.0 / speed*60.0);
335 tgt_altitude_ft = curr->crossat;
340 AccelTo(prev->speed);
341 hdg_lock = alt_lock = true;
342 no_roll = prev->on_ground;
347 void FGAIAircraft::initializeFlightPlan() {
351 bool FGAIAircraft::_getGearDown() const {
352 return _performance->gearExtensible(this);
356 const char * FGAIAircraft::_getTransponderCode() const {
357 return transponderCode.c_str();
361 bool FGAIAircraft::loadNextLeg(double distance) {
364 if ((leg = fp->getLeg()) == 10) {
365 if (!trafficRef->next()) {
368 setCallSign(trafficRef->getCallSign());
373 FGAirport *dep = trafficRef->getDepartureAirport();
374 FGAirport *arr = trafficRef->getArrivalAirport();
379 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
386 trafficRef->getSpeed(),
390 trafficRef->getRadius(),
391 trafficRef->getFlightType(),
395 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
401 // Note: This code is copied from David Luff's AILocalTraffic
402 // Warning - ground elev determination is CPU intensive
403 // Either this function or the logic of how often it is called
404 // will almost certainly change.
406 void FGAIAircraft::getGroundElev(double dt) {
409 if (!needGroundElevation())
411 // Update minimally every three secs, but add some randomness
412 // to prevent all AI objects doing this in synchrony
413 if (dt_elev_count < (3.0) + (rand() % 10))
418 // Only do the proper hitlist stuff if we are within visible range of the viewer.
420 double visibility_meters = fgGetDouble("/environment/visibility-m");
421 FGViewer* vw = globals->get_current_view();
423 if (SGGeodesy::distanceM(vw->getPosition(), pos) > visibility_meters) {
427 double range = 500.0;
428 if (globals->get_tile_mgr()->schedule_scenery(pos, range, 5.0))
431 if (getGroundElevationM(SGGeod::fromGeodM(pos, 20000), alt, 0))
433 tgt_altitude_ft = alt * SG_METER_TO_FEET;
436 // aircraft is stationary and we obtained altitude for this spot - we're done.
437 _needsGroundElevation = false;
445 void FGAIAircraft::doGroundAltitude() {
446 if ((fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)||
448 altitude_ft = (tgt_altitude_ft + groundOffset);
450 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
455 void FGAIAircraft::announcePositionToController() {
457 int leg = fp->getLeg();
459 // Note that leg has been incremented after creating the current leg, so we should use
460 // leg numbers here that are one higher than the number that is used to create the leg
463 case 2: // Startup and Push back
464 if (trafficRef->getDepartureAirport()->getDynamics())
465 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
467 case 3: // Taxiing to runway
468 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
469 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
471 case 4: //Take off tower controller
472 if (trafficRef->getDepartureAirport()->getDynamics()) {
473 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
475 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
479 if (trafficRef->getDepartureAirport()->getDynamics()) {
480 controller = trafficRef->getArrivalAirport()->getDynamics()->getApproachController();
483 case 9: // Taxiing for parking
484 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
485 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
492 if ((controller != prevController) && (prevController != 0)) {
493 prevController->signOff(getID());
495 prevController = controller;
497 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
498 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
499 trafficRef->getRadius(), leg, this);
504 // Process ATC instructions and report back
506 void FGAIAircraft::processATC(FGATCInstruction instruction) {
507 if (instruction.getCheckForCircularWait()) {
508 // This is not exactly an elegant solution,
509 // but at least it gives me a chance to check
510 // if circular waits are resolved.
511 // For now, just take the offending aircraft
514 // a more proper way should be - of course - to
515 // let an offending aircraft take an evasive action
516 // for instance taxi back a little bit.
518 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
519 if (instruction.getHoldPattern ()) {}
522 if (instruction.getHoldPosition ()) {
530 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
533 // Change speed Instruction. This can only be excecuted when there is no
534 // Hold position instruction.
535 if (instruction.getChangeSpeed ()) {
537 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
538 AccelTo(instruction.getSpeed());
540 if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
543 if (instruction.getChangeHeading ()) {
545 TurnTo(instruction.getHeading());
551 if (instruction.getChangeAltitude()) {}
556 void FGAIAircraft::handleFirstWaypoint() {
557 bool eraseWaypoints; //TODO YAGNI
560 eraseWaypoints = true;
562 eraseWaypoints = false;
565 FGAIFlightPlan::waypoint* prev = 0; // the one behind you
566 FGAIFlightPlan::waypoint* curr = 0; // the one ahead
567 FGAIFlightPlan::waypoint* next = 0;// the next plus 1
572 //TODO fp should handle this
573 fp->IncrementWaypoint(eraseWaypoints);
574 if (!(fp->getNextWaypoint()) && trafficRef)
575 if (!loadNextLeg()) {
580 prev = fp->getPreviousWaypoint(); //first waypoint
581 curr = fp->getCurrentWaypoint(); //second waypoint
582 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
584 setLatitude(prev->latitude);
585 setLongitude(prev->longitude);
586 setSpeed(prev->speed);
587 setAltitude(prev->altitude);
589 if (prev->speed > 0.0)
590 setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
592 setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
594 // If next doesn't exist, as in incrementally created flightplans for
595 // AI/Trafficmanager created plans,
596 // Make sure lead distance is initialized otherwise
598 fp->setLeadDistance(speed, hdg, curr, next);
600 if (curr->crossat > -1000.0) //use a calculated descent/climb rate
603 tgt_vs = (curr->crossat - prev->altitude)
604 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
605 / 6076.0 / prev->speed*60.0);
606 tgt_altitude_ft = curr->crossat;
609 tgt_altitude_ft = prev->altitude;
611 alt_lock = hdg_lock = true;
612 no_roll = prev->on_ground;
614 Transform(); // make sure aip is initialized.
615 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
617 _needsGroundElevation = true; // check ground elevation again (maybe scenery wasn't available yet)
619 // Make sure to announce the aircraft's position
620 announcePositionToController();
626 * Check Execution time (currently once every 100 ms)
627 * Add a bit of randomization to prevent the execution of all flight plans
628 * in synchrony, which can add significant periodic framerate flutter.
633 bool FGAIAircraft::fpExecutable(time_t now) {
634 double rand_exec_time = (rand() % 100) / 100;
635 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
640 * Check to see if we've reached the lead point for our next turn
645 bool FGAIAircraft::leadPointReached(FGAIFlightPlan::waypoint* curr) {
646 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
648 //cerr << "2" << endl;
649 double lead_dist = fp->getLeadDistance();
650 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
652 if (lead_dist < fabs(2*speed)) {
653 //don't skip over the waypoint
654 lead_dist = fabs(2*speed);
655 //cerr << "Extending lead distance to " << lead_dist << endl;
658 //prev_dist_to_go = dist_to_go;
659 //if (dist_to_go < lead_dist)
660 // cerr << trafficRef->getCallSign() << " Distance : "
661 // << dist_to_go << ": Lead distance "
662 // << lead_dist << " " << curr->name
663 // << " Ground target speed " << groundTargetSpeed << endl;
665 if (speed > 50) { // don't do bearing calculations for ground traffic
666 bearing = getBearing(fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr));
667 if (bearing < minBearing) {
668 minBearing = bearing;
669 if (minBearing < 10) {
672 if ((minBearing < 360.0) && (minBearing > 10.0)) {
673 speedFraction = cos(minBearing *SG_DEGREES_TO_RADIANS);
680 //cerr << "Tracking callsign : \"" << fgGetString("/ai/track-callsign") << "\"" << endl;
681 /* if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
682 cerr << trafficRef->getCallSign() << " " << tgt_altitude_ft << " " << _getSpeed() << " "
683 << _getAltitude() << " "<< _getLatitude() << " " << _getLongitude() << " " << dist_to_go << " " << lead_dist << " " << curr->name << " " << vs << " " << tgt_vs << " " << bearing << " " << minBearing << " " << speedFraction << endl;
686 if ((dist_to_go < lead_dist) || (bearing > (minBearing * 1.1))) {
695 bool FGAIAircraft::aiTrafficVisible() {
696 SGGeod userPos(SGGeod::fromDeg(fgGetDouble("/position/longitude-deg"),
697 fgGetDouble("/position/latitude-deg")));
699 return (SGGeodesy::distanceNm(userPos, pos) <= TRAFFICTOAIDISTTODIE);
704 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
705 * in the case of an arrival.
711 //TODO the trafficRef is the right place for the method
712 bool FGAIAircraft::handleAirportEndPoints(FGAIFlightPlan::waypoint* prev, time_t now) {
713 // prepare routing from one airport to another
714 FGAirport * dep = trafficRef->getDepartureAirport();
715 FGAirport * arr = trafficRef->getArrivalAirport();
720 // This waypoint marks the fact that the aircraft has passed the initial taxi
721 // departure waypoint, so it can release the parking.
722 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
723 if (prev->name == "PushBackPoint") {
724 dep->getDynamics()->releaseParking(fp->getGate());
726 setTaxiClearanceRequest(true);
729 // This is the last taxi waypoint, and marks the the end of the flight plan
730 // so, the schedule should update and wait for the next departure time.
731 if (prev->name == "END") {
732 time_t nextDeparture = trafficRef->getDepartureTime();
733 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
734 if (nextDeparture < (now+1200)) {
735 nextDeparture = now + 1200;
737 fp->setTime(nextDeparture); // should be "next departure"
745 * Check difference between target bearing and current heading and correct if necessary.
749 void FGAIAircraft::controlHeading(FGAIFlightPlan::waypoint* curr) {
750 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
751 //cerr << "Bearing = " << calc_bearing << endl;
754 if (calc_bearing > 360)
758 if (finite(calc_bearing)) {
759 double hdg_error = calc_bearing - tgt_heading;
760 if (fabs(hdg_error) > 0.01) {
761 TurnTo( calc_bearing );
765 cerr << "calc_bearing is not a finite number : "
767 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
768 << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
769 cerr << "waypoint name " << curr->name;
776 * Update the lead distance calculation if speed has changed sufficiently
777 * to prevent spinning (hopefully);
782 void FGAIAircraft::controlSpeed(FGAIFlightPlan::waypoint* curr, FGAIFlightPlan::waypoint* next) {
783 double speed_diff = speed - prevSpeed;
785 if (fabs(speed_diff) > 10) {
788 fp->setLeadDistance(speed, tgt_heading, curr, next);
795 * Update target values (heading, alt, speed) depending on flight plan or control properties
797 void FGAIAircraft::updatePrimaryTargetValues(bool& flightplanActive, bool& aiOutOfSight) {
798 if (fp) // AI object has a flightplan
800 //TODO make this a function of AIBase
801 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
802 //cerr << "UpateTArgetValues() " << endl;
803 ProcessFlightPlan(dt, now);
805 // Do execute Ground elev for inactive aircraft, so they
806 // Are repositioned to the correct ground altitude when the user flies within visibility range.
807 // In addition, check whether we are out of user range, so this aircraft
810 Transform(); // make sure aip is initialized.
814 pos.setElevationFt(altitude_ft);
817 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
818 aiOutOfSight = !aiTrafficVisible();
821 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
826 timeElapsed = now - fp->getStartTime();
827 flightplanActive = fp->isActive(now);
829 // no flight plan, update target heading, speed, and altitude
830 // from control properties. These default to the initial
831 // settings in the config file, but can be changed "on the
833 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
834 if ( lat_mode == "roll" ) {
836 = props->getDoubleValue("controls/flight/target-roll" );
840 = props->getDoubleValue("controls/flight/target-hdg" );
845 = props->getStringValue("controls/flight/longitude-mode");
846 if ( lon_mode == "alt" ) {
847 double alt = props->getDoubleValue("controls/flight/target-alt" );
851 = props->getDoubleValue("controls/flight/target-pitch" );
855 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
859 void FGAIAircraft::updatePosition() {
860 // convert speed to degrees per second
861 double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
862 * speed * 1.686 / ft_per_deg_lat;
863 double speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
864 * speed * 1.686 / ft_per_deg_lon;
867 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
868 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
872 void FGAIAircraft::updateHeading() {
873 // adjust heading based on current bank angle
878 // double turnConstant;
880 // turnConstant = 0.0088362;
882 // turnConstant = 0.088362;
883 // If on ground, calculate heading change directly
885 double headingDiff = fabs(hdg-tgt_heading);
886 double bank_sense = 0.0;
888 double diff = fabs(hdg - tgt_heading);
890 diff = fabs(diff - 360);
892 double sum = hdg + diff;
895 if (fabs(sum - tgt_heading) < 1.0) {
896 bank_sense = 1.0; // right turn
898 bank_sense = -1.0; // left turn
900 if (headingDiff > 180)
901 headingDiff = fabs(headingDiff - 360);
902 double sum = hdg + headingDiff;
905 if (fabs(sum - tgt_heading) > 0.0001) {
911 //cerr << trafficRef->getCallSign() << " Heading "
912 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
913 //if (headingDiff > 60) {
914 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
915 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
917 // groundTargetSpeed = tgt_speed;
919 if (sign(groundTargetSpeed) != sign(tgt_speed))
920 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
922 if (headingDiff > 30.0) {
923 // invert if pushed backward
924 headingChangeRate += 10.0 * dt * sign(roll);
926 // Clamp the maximum steering rate to 30 degrees per second,
927 // But only do this when the heading error is decreasing.
928 if ((headingDiff < headingError)) {
929 if (headingChangeRate > 30)
930 headingChangeRate = 30;
931 else if (headingChangeRate < -30)
932 headingChangeRate = -30;
935 if (fabs(headingChangeRate) > headingDiff)
936 headingChangeRate = headingDiff*sign(roll);
938 headingChangeRate += dt * sign(roll);
941 hdg += headingChangeRate * dt * (fabs(speed) / 15);
942 headingError = headingDiff;
944 if (fabs(speed) > 1.0) {
945 turn_radius_ft = 0.088362 * speed * speed
946 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
948 // Check if turn_radius_ft == 0; this might lead to a division by 0.
949 turn_radius_ft = 1.0;
951 double turn_circum_ft = SGD_2PI * turn_radius_ft;
952 double dist_covered_ft = speed * 1.686 * dt;
953 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
954 hdg += alpha * sign(roll);
956 while ( hdg > 360.0 ) {
968 void FGAIAircraft::updateBankAngleTarget() {
969 // adjust target bank angle if heading lock engaged
971 double bank_sense = 0.0;
972 double diff = fabs(hdg - tgt_heading);
974 diff = fabs(diff - 360);
976 double sum = hdg + diff;
979 if (fabs(sum - tgt_heading) < 1.0) {
980 bank_sense = 1.0; // right turn
982 bank_sense = -1.0; // left turn
984 if (diff < _performance->maximumBankAngle()) {
985 tgt_roll = diff * bank_sense;
987 tgt_roll = _performance->maximumBankAngle() * bank_sense;
989 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
990 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
991 // The only way to resolve this is to make them slow down.
997 void FGAIAircraft::updateVerticalSpeedTarget() {
998 // adjust target Altitude, based on ground elevation when on ground
1002 } else if (alt_lock) {
1003 // find target vertical speed
1005 if (altitude_ft < tgt_altitude_ft) {
1006 tgt_vs = tgt_altitude_ft - altitude_ft;
1007 if (tgt_vs > _performance->climbRate())
1008 tgt_vs = _performance->climbRate();
1010 tgt_vs = tgt_altitude_ft - altitude_ft;
1011 if (tgt_vs < (-_performance->descentRate()))
1012 tgt_vs = -_performance->descentRate();
1015 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
1016 double min_vs = 100;
1017 if (tgt_altitude_ft < altitude_ft)
1019 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
1020 && (fabs(max_vs) < fabs(tgt_vs)))
1023 if (fabs(tgt_vs) < fabs(min_vs))
1030 void FGAIAircraft::updatePitchAngleTarget() {
1031 // if on ground and above vRotate -> initial rotation
1032 if (onGround() && (speed > _performance->vRotate()))
1033 tgt_pitch = 8.0; // some rough B737 value
1035 //TODO pitch angle on approach and landing
1037 // match pitch angle to vertical speed
1038 else if (tgt_vs > 0) {
1039 tgt_pitch = tgt_vs * 0.005;
1041 tgt_pitch = tgt_vs * 0.002;
1045 string FGAIAircraft::atGate() {
1047 if (fp->getLeg() < 3) {
1049 if (fp->getGate() > 0) {
1051 trafficRef->getDepartureAirport()->getDynamics()->getParking(fp->getGate());
1052 tmp = park->getName();
1059 void FGAIAircraft::handleATCRequests() {
1060 //TODO implement NullController for having no ATC to save the conditionals
1062 controller->update(getID(),
1063 pos.getLatitudeDeg(),
1064 pos.getLongitudeDeg(),
1068 processATC(controller->getInstruction(getID()));
1072 void FGAIAircraft::updateActualState() {
1073 //update current state
1074 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1078 speed = _performance->actualSpeed(this, groundTargetSpeed, dt);
1080 speed = _performance->actualSpeed(this, (tgt_speed *speedFraction), dt);
1083 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1085 // adjust altitude (meters) based on current vertical speed (fpm)
1086 altitude_ft += vs / 60.0 * dt;
1087 pos.setElevationFt(altitude_ft);
1089 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1090 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1093 void FGAIAircraft::updateSecondaryTargetValues() {
1094 // derived target state values
1095 updateBankAngleTarget();
1096 updateVerticalSpeedTarget();
1097 updatePitchAngleTarget();
1099 //TODO calculate wind correction angle (tgt_yaw)
1103 bool FGAIAircraft::reachedEndOfCruise(double &distance) {
1104 FGAIFlightPlan::waypoint* curr = fp->getCurrentWaypoint();
1105 if (curr->name == "BOD") {
1106 double dist = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1107 double descentSpeed = (getPerformance()->vDescent() * SG_NM_TO_METER) / 3600.0; // convert from kts to meter/s
1108 double descentRate = (getPerformance()->descentRate() * SG_FEET_TO_METER) / 60.0; // convert from feet/min to meter/s
1110 double verticalDistance = ((altitude_ft - 2000.0) - trafficRef->getArrivalAirport()->getElevation()) *SG_FEET_TO_METER;
1111 double descentTimeNeeded = verticalDistance / descentRate;
1112 double distanceCovered = descentSpeed * descentTimeNeeded;
1114 //cerr << "Tracking : " << fgGetString("/ai/track-callsign");
1115 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1116 cerr << "Checking for end of cruise stage for :" << trafficRef->getCallSign() << endl;
1117 cerr << "Descent rate : " << descentRate << endl;
1118 cerr << "Descent speed : " << descentSpeed << endl;
1119 cerr << "VerticalDistance : " << verticalDistance << ". Altitude : " << altitude_ft << ". Elevation " << trafficRef->getArrivalAirport()->getElevation() << endl;
1120 cerr << "DecentTimeNeeded : " << descentTimeNeeded << endl;
1121 cerr << "DistanceCovered : " << distanceCovered << endl;
1123 //cerr << "Distance = " << distance << endl;
1124 distance = distanceCovered;
1125 if (dist < distanceCovered) {
1126 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1138 void FGAIAircraft::resetPositionFromFlightPlan()
1140 // the one behind you
1141 FGAIFlightPlan::waypoint* prev = 0;
1143 FGAIFlightPlan::waypoint* curr = 0;
1145 FGAIFlightPlan::waypoint* next = 0;
1147 prev = fp->getPreviousWaypoint();
1148 curr = fp->getCurrentWaypoint();
1149 next = fp->getNextWaypoint();
1151 setLatitude(prev->latitude);
1152 setLongitude(prev->longitude);
1153 double tgt_heading = fp->getBearing(curr, next);
1154 setHeading(tgt_heading);
1155 setAltitude(prev->altitude);
1156 setSpeed(prev->speed);
1159 double FGAIAircraft::getBearing(double crse)
1161 double hdgDiff = fabs(hdg-crse);
1163 hdgDiff = fabs(hdgDiff - 360);
1167 time_t FGAIAircraft::checkForArrivalTime(string wptName) {
1168 FGAIFlightPlan::waypoint* curr = 0;
1169 curr = fp->getCurrentWaypoint();
1171 double tracklength = fp->checkTrackLength(wptName);
1172 if (tracklength > 0.1) {
1173 tracklength += fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
1177 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1178 time_t arrivalTime = fp->getArrivalTime();
1180 time_t ete = tracklength / ((speed * SG_NM_TO_METER) / 3600.0);
1181 time_t secondsToGo = arrivalTime - now;
1182 if (trafficRef->getCallSign() == fgGetString("/ai/track-callsign")) {
1183 cerr << "Checking arrival time: ete " << ete << ". Time to go : " << secondsToGo << ". Track length = " << tracklength << endl;
1185 return (ete - secondsToGo); // Positive when we're too slow...