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>
38 # define finite _finite
39 #elif defined(__sun) || defined(sgi)
45 #include "AIAircraft.hxx"
46 #include "performancedata.hxx"
47 #include "performancedb.hxx"
49 //#include <Airports/trafficcontroller.hxx>
51 static string tempReg;
53 class AI_OutOfSight{};
56 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) : FGAIBase(otAircraft) {
59 groundOffset = trafficRef->getGroundOffset();
60 setCallSign(trafficRef->getCallSign());
75 groundTargetSpeed = 0;
77 // set heading and altitude locks
81 headingChangeRate = 0.0;
85 _performance = 0; //TODO initialize to JET_TRANSPORT from PerformanceDB
90 FGAIAircraft::~FGAIAircraft() {
93 controller->signOff(getID());
97 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
101 FGAIBase::readFromScenario(scFileNode);
103 setPerformance(scFileNode->getStringValue("class", "jet_transport"));
104 setFlightPlan(scFileNode->getStringValue("flightplan"),
105 scFileNode->getBoolValue("repeat", false));
106 setCallSign(scFileNode->getStringValue("callsign"));
110 void FGAIAircraft::bind() {
113 props->tie("controls/gear/gear-down",
114 SGRawValueMethods<FGAIAircraft,bool>(*this,
115 &FGAIAircraft::_getGearDown));
116 props->tie("transponder-id",
117 SGRawValueMethods<FGAIAircraft,const char*>(*this,
118 &FGAIAircraft::_getTransponderCode));
122 void FGAIAircraft::unbind() {
125 props->untie("controls/gear/gear-down");
126 props->untie("transponder-id");
130 void FGAIAircraft::update(double dt) {
131 FGAIBase::update(dt);
136 void FGAIAircraft::setPerformance(const std::string& acclass) {
137 static PerformanceDB perfdb; //TODO make it a global service
138 setPerformance(perfdb.getDataFor(acclass));
142 void FGAIAircraft::setPerformance(PerformanceData *ps) {
147 void FGAIAircraft::Run(double dt) {
148 FGAIAircraft::dt = dt;
151 updatePrimaryTargetValues(); // target hdg, alt, speed
153 catch (AI_OutOfSight) {
156 catch (FP_Inactive) {
158 groundTargetSpeed = 0;
161 handleATCRequests(); // ATC also has a word to say
162 updateSecondaryTargetValues(); // target roll, vertical speed, pitch
164 UpdateRadar(manager);
168 void FGAIAircraft::checkVisibility()
170 double visibility_meters = fgGetDouble("/environment/visibility-m");
172 FGViewer* vw = globals->get_current_view();
173 double course, distance;
175 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
176 SGWayPoint view (vw->getLongitude_deg(), vw->getLatitude_deg(), 0);
177 view.CourseAndDistance(current, &course, &distance);
178 if (distance > visibility_meters) {
187 void FGAIAircraft::AccelTo(double speed) {
192 void FGAIAircraft::PitchTo(double angle) {
198 void FGAIAircraft::RollTo(double angle) {
204 void FGAIAircraft::YawTo(double angle) {
209 void FGAIAircraft::ClimbTo(double alt_ft ) {
210 tgt_altitude_ft = alt_ft;
215 void FGAIAircraft::TurnTo(double heading) {
216 tgt_heading = heading;
221 double FGAIAircraft::sign(double x) {
229 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
230 if (!flightplan.empty()) {
231 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
232 fp->setRepeat(repeat);
238 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
244 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
246 // the one behind you
247 FGAIFlightPlan::waypoint* prev = 0;
249 FGAIFlightPlan::waypoint* curr = 0;
251 FGAIFlightPlan::waypoint* next = 0;
253 prev = fp->getPreviousWaypoint();
254 curr = fp->getCurrentWaypoint();
255 next = fp->getNextWaypoint();
259 ///////////////////////////////////////////////////////////////////////////
260 // Initialize the flightplan
261 //////////////////////////////////////////////////////////////////////////
263 handleFirstWaypoint();
265 } // end of initialization
266 if (! fpExecutable(now))
270 if (! leadPointReached(curr)) {
271 controlHeading(curr);
272 controlSpeed(curr, next);
274 if (curr->finished) //end of the flight plan
284 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
285 tgt_heading = fp->getBearing(curr, next);
289 //TODO let the fp handle this (loading of next leg)
290 fp->IncrementWaypoint((bool) trafficRef);
291 if (!(fp->getNextWaypoint()) && trafficRef)
292 if (!loadNextLeg()) {
297 prev = fp->getPreviousWaypoint();
298 curr = fp->getCurrentWaypoint();
299 next = fp->getNextWaypoint();
301 // Now that we have incremented the waypoints, excute some traffic manager specific code
303 //TODO isn't this best executed right at the beginning?
304 if (! aiTrafficVisible()) {
309 if (! handleAirportEndPoints(prev, now)) {
314 announcePositionToController();
319 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
322 if (!(prev->on_ground)) // only update the tgt altitude from flightplan if not on the ground
324 tgt_altitude_ft = prev->altitude;
325 if (curr->crossat > -1000.0) {
327 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
328 / 6076.0 / speed*60.0);
329 tgt_altitude_ft = curr->crossat;
334 tgt_speed = prev->speed;
335 hdg_lock = alt_lock = true;
336 no_roll = prev->on_ground;
341 void FGAIAircraft::initializeFlightPlan() {
345 bool FGAIAircraft::_getGearDown() const {
346 return _performance->gearExtensible(this);
350 const char * FGAIAircraft::_getTransponderCode() const {
351 return transponderCode.c_str();
355 bool FGAIAircraft::loadNextLeg() {
358 if ((leg = fp->getLeg()) == 10) {
359 if (!trafficRef->next()) {
362 setCallSign(trafficRef->getCallSign());
367 FGAirport *dep = trafficRef->getDepartureAirport();
368 FGAirport *arr = trafficRef->getArrivalAirport();
373 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
380 trafficRef->getSpeed(),
384 trafficRef->getRadius(),
385 trafficRef->getFlightType(),
388 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
394 // Note: This code is copied from David Luff's AILocalTraffic
395 // Warning - ground elev determination is CPU intensive
396 // Either this function or the logic of how often it is called
397 // will almost certainly change.
399 void FGAIAircraft::getGroundElev(double dt) {
402 // Update minimally every three secs, but add some randomness
403 // to prevent all AI objects doing this in synchrony
404 if (dt_elev_count < (3.0) + (rand() % 10))
409 // Only do the proper hitlist stuff if we are within visible range of the viewer.
411 double visibility_meters = fgGetDouble("/environment/visibility-m");
413 FGViewer* vw = globals->get_current_view();
414 double course, distance;
416 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
417 SGWayPoint view (vw->getLongitude_deg(), vw->getLatitude_deg(), 0);
418 view.CourseAndDistance(current, &course, &distance);
419 if (distance > visibility_meters) {
423 double range = 500.0;
424 if (!globals->get_tile_mgr()->scenery_available(pos, range)) {
425 // Try to shedule tiles for that position.
426 globals->get_tile_mgr()->update( pos, range );
430 if (globals->get_scenery()->get_elevation_m(SGGeod::fromGeodM(pos, 20000), alt, 0))
431 tgt_altitude_ft = alt * SG_METER_TO_FEET;
436 void FGAIAircraft::doGroundAltitude() {
437 if (fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)
438 altitude_ft = (tgt_altitude_ft + groundOffset);
440 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
444 void FGAIAircraft::announcePositionToController() {
446 int leg = fp->getLeg();
448 // Note that leg has been incremented after creating the current leg, so we should use
449 // leg numbers here that are one higher than the number that is used to create the leg
452 case 2: // Startup and Push back
453 if (trafficRef->getDepartureAirport()->getDynamics())
454 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
456 case 3: // Taxiing to runway
457 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
458 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
460 case 4: //Take off tower controller
461 if (trafficRef->getDepartureAirport()->getDynamics()) {
462 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
463 //if (trafficRef->getDepartureAirport()->getId() == "EHAM") {
464 //string trns = trafficRef->getCallSign() + " at runway " + fp->getRunway() +
465 // ". Ready for departure. " + trafficRef->getFlightType() + " to " +
466 // trafficRef->getArrivalAirport()->getId();
467 //fgSetString("/sim/messages/atc", trns.c_str());
468 // if (controller == 0) {
469 //cerr << "Error in assigning controller at " << trafficRef->getDepartureAirport()->getId() << endl;
473 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
476 case 9: // Taxiing for parking
477 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
478 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
485 if ((controller != prevController) && (prevController != 0)) {
486 prevController->signOff(getID());
488 prevController = controller;
490 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
491 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
492 trafficRef->getRadius(), leg, this);
497 // Process ATC instructions and report back
499 void FGAIAircraft::processATC(FGATCInstruction instruction) {
500 if (instruction.getCheckForCircularWait()) {
501 // This is not exactly an elegant solution,
502 // but at least it gives me a chance to check
503 // if circular waits are resolved.
504 // For now, just take the offending aircraft
507 // a more proper way should be - of course - to
508 // let an offending aircraft take an evasive action
509 // for instance taxi back a little bit.
511 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
512 if (instruction.getHoldPattern ()) {}
515 if (instruction.getHoldPosition ()) {
523 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
526 // Change speed Instruction. This can only be excecuted when there is no
527 // Hold position instruction.
528 if (instruction.getChangeSpeed ()) {
530 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
531 AccelTo(instruction.getSpeed());
533 if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
536 if (instruction.getChangeHeading ()) {
538 TurnTo(instruction.getHeading());
544 if (instruction.getChangeAltitude()) {}
549 void FGAIAircraft::handleFirstWaypoint() {
550 bool eraseWaypoints; //TODO YAGNI
553 eraseWaypoints = true;
555 eraseWaypoints = false;
558 FGAIFlightPlan::waypoint* prev = 0; // the one behind you
559 FGAIFlightPlan::waypoint* curr = 0; // the one ahead
560 FGAIFlightPlan::waypoint* next = 0;// the next plus 1
565 //TODO fp should handle this
566 fp->IncrementWaypoint(eraseWaypoints);
567 if (!(fp->getNextWaypoint()) && trafficRef)
568 if (!loadNextLeg()) {
573 prev = fp->getPreviousWaypoint(); //first waypoint
574 curr = fp->getCurrentWaypoint(); //second waypoint
575 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
577 setLatitude(prev->latitude);
578 setLongitude(prev->longitude);
579 setSpeed(prev->speed);
580 setAltitude(prev->altitude);
582 if (prev->speed > 0.0)
583 setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
585 setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
587 // If next doesn't exist, as in incrementally created flightplans for
588 // AI/Trafficmanager created plans,
589 // Make sure lead distance is initialized otherwise
591 fp->setLeadDistance(speed, hdg, curr, next);
593 if (curr->crossat > -1000.0) //use a calculated descent/climb rate
596 tgt_vs = (curr->crossat - prev->altitude)
597 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
598 / 6076.0 / prev->speed*60.0);
599 tgt_altitude_ft = curr->crossat;
602 tgt_altitude_ft = prev->altitude;
604 alt_lock = hdg_lock = true;
605 no_roll = prev->on_ground;
607 Transform(); // make sure aip is initialized.
608 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
611 // Make sure to announce the aircraft's position
612 announcePositionToController();
618 * Check Execution time (currently once every 100 ms)
619 * Add a bit of randomization to prevent the execution of all flight plans
620 * in synchrony, which can add significant periodic framerate flutter.
625 bool FGAIAircraft::fpExecutable(time_t now) {
626 double rand_exec_time = (rand() % 100) / 100;
627 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
632 * Check to see if we've reached the lead point for our next turn
637 bool FGAIAircraft::leadPointReached(FGAIFlightPlan::waypoint* curr) {
638 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
640 //cerr << "2" << endl;
641 double lead_dist = fp->getLeadDistance();
642 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
644 if (lead_dist < fabs(2*speed)) {
645 //don't skip over the waypoint
646 lead_dist = fabs(2*speed);
647 //cerr << "Extending lead distance to " << lead_dist << endl;
650 //prev_dist_to_go = dist_to_go;
651 //if (dist_to_go < lead_dist)
652 // cerr << trafficRef->getCallSign() << " Distance : "
653 // << dist_to_go << ": Lead distance "
654 // << lead_dist << " " << curr->name
655 // << " Ground target speed " << groundTargetSpeed << endl;
657 return dist_to_go < lead_dist;
661 bool FGAIAircraft::aiTrafficVisible() {
662 double userLatitude = fgGetDouble("/position/latitude-deg");
663 double userLongitude = fgGetDouble("/position/longitude-deg");
664 double course, distance;
666 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
667 SGWayPoint user (userLongitude, userLatitude, 0);
669 user.CourseAndDistance(current, &course, &distance);
671 return ((distance * SG_METER_TO_NM) <= TRAFFICTOAIDISTTODIE);
676 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
677 * in the case of an arrival.
683 //TODO the trafficRef is the right place for the method
684 bool FGAIAircraft::handleAirportEndPoints(FGAIFlightPlan::waypoint* prev, time_t now) {
685 // prepare routing from one airport to another
686 FGAirport * dep = trafficRef->getDepartureAirport();
687 FGAirport * arr = trafficRef->getArrivalAirport();
692 // This waypoint marks the fact that the aircraft has passed the initial taxi
693 // departure waypoint, so it can release the parking.
694 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
695 if (prev->name == "PushBackPoint") {
696 dep->getDynamics()->releaseParking(fp->getGate());
697 time_t holdUntil = now + 120;
698 fp->setTime(holdUntil);
699 //cerr << _getCallsign() << "Holding at pushback point" << endl;
702 // This is the last taxi waypoint, and marks the the end of the flight plan
703 // so, the schedule should update and wait for the next departure time.
704 if (prev->name == "END") {
705 time_t nextDeparture = trafficRef->getDepartureTime();
706 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
707 if (nextDeparture < (now+1200)) {
708 nextDeparture = now + 1200;
710 fp->setTime(nextDeparture); // should be "next departure"
718 * Check difference between target bearing and current heading and correct if necessary.
722 void FGAIAircraft::controlHeading(FGAIFlightPlan::waypoint* curr) {
723 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
724 //cerr << "Bearing = " << calc_bearing << endl;
727 if (calc_bearing > 360)
731 if (finite(calc_bearing)) {
732 double hdg_error = calc_bearing - tgt_heading;
733 if (fabs(hdg_error) > 0.01) {
734 TurnTo( calc_bearing );
738 cerr << "calc_bearing is not a finite number : "
740 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
741 << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
742 cerr << "waypoint name " << curr->name;
749 * Update the lead distance calculation if speed has changed sufficiently
750 * to prevent spinning (hopefully);
755 void FGAIAircraft::controlSpeed(FGAIFlightPlan::waypoint* curr, FGAIFlightPlan::waypoint* next) {
756 double speed_diff = speed - prevSpeed;
758 if (fabs(speed_diff) > 10) {
761 fp->setLeadDistance(speed, tgt_heading, curr, next);
768 * Update target values (heading, alt, speed) depending on flight plan or control properties
770 void FGAIAircraft::updatePrimaryTargetValues() {
771 if (fp) // AI object has a flightplan
773 //TODO make this a function of AIBase
774 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
775 //cerr << "UpateTArgetValues() " << endl;
776 ProcessFlightPlan(dt, now);
778 // Do execute Ground elev for inactive aircraft, so they
779 // Are repositioned to the correct ground altitude when the user flies within visibility range.
780 // In addition, check whether we are out of user range, so this aircraft
783 Transform(); // make sure aip is initialized.
787 pos.setElevationFt(altitude_ft);
790 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
791 if (! aiTrafficVisible()) {
793 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
794 throw AI_OutOfSight();
797 timeElapsed = now - fp->getStartTime();
798 if (! fp->isActive(now)) {
802 // no flight plan, update target heading, speed, and altitude
803 // from control properties. These default to the initial
804 // settings in the config file, but can be changed "on the
806 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
807 if ( lat_mode == "roll" ) {
809 = props->getDoubleValue("controls/flight/target-roll" );
813 = props->getDoubleValue("controls/flight/target-hdg" );
818 = props->getStringValue("controls/flight/longitude-mode");
819 if ( lon_mode == "alt" ) {
820 double alt = props->getDoubleValue("controls/flight/target-alt" );
824 = props->getDoubleValue("controls/flight/target-pitch" );
828 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
832 void FGAIAircraft::updatePosition() {
833 // convert speed to degrees per second
834 double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
835 * speed * 1.686 / ft_per_deg_lat;
836 double speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
837 * speed * 1.686 / ft_per_deg_lon;
840 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
841 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
845 void FGAIAircraft::updateHeading() {
846 // adjust heading based on current bank angle
851 // double turnConstant;
853 // turnConstant = 0.0088362;
855 // turnConstant = 0.088362;
856 // If on ground, calculate heading change directly
858 double headingDiff = fabs(hdg-tgt_heading);
859 double bank_sense = 0.0;
861 double diff = fabs(hdg - tgt_heading);
863 diff = fabs(diff - 360);
865 double sum = hdg + diff;
868 if (fabs(sum - tgt_heading) < 1.0) {
869 bank_sense = 1.0; // right turn
871 bank_sense = -1.0; // left turn
873 if (headingDiff > 180)
874 headingDiff = fabs(headingDiff - 360);
875 double sum = hdg + headingDiff;
878 if (fabs(sum - tgt_heading) > 0.0001) {
884 //cerr << trafficRef->getCallSign() << " Heading "
885 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
886 //if (headingDiff > 60) {
887 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
888 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
890 // groundTargetSpeed = tgt_speed;
892 if (sign(groundTargetSpeed) != sign(tgt_speed))
893 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
895 if (headingDiff > 30.0) {
896 // invert if pushed backward
897 headingChangeRate += 10.0 * dt * sign(roll);
899 // Clamp the maximum steering rate to 30 degrees per second,
900 // But only do this when the heading error is decreasing.
901 if ((headingDiff < headingError)) {
902 if (headingChangeRate > 30)
903 headingChangeRate = 30;
904 else if (headingChangeRate < -30)
905 headingChangeRate = -30;
908 if (fabs(headingChangeRate) > headingDiff)
909 headingChangeRate = headingDiff*sign(roll);
911 headingChangeRate += dt * sign(roll);
914 hdg += headingChangeRate * dt * (fabs(speed) / 15);
915 headingError = headingDiff;
917 if (fabs(speed) > 1.0) {
918 turn_radius_ft = 0.088362 * speed * speed
919 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
921 // Check if turn_radius_ft == 0; this might lead to a division by 0.
922 turn_radius_ft = 1.0;
924 double turn_circum_ft = SGD_2PI * turn_radius_ft;
925 double dist_covered_ft = speed * 1.686 * dt;
926 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
927 hdg += alpha * sign(roll);
929 while ( hdg > 360.0 ) {
941 void FGAIAircraft::updateBankAngleTarget() {
942 // adjust target bank angle if heading lock engaged
944 double bank_sense = 0.0;
945 double diff = fabs(hdg - tgt_heading);
947 diff = fabs(diff - 360);
949 double sum = hdg + diff;
952 if (fabs(sum - tgt_heading) < 1.0) {
953 bank_sense = 1.0; // right turn
955 bank_sense = -1.0; // left turn
957 if (diff < _performance->maximumBankAngle()) {
958 tgt_roll = diff * bank_sense;
960 tgt_roll = _performance->maximumBankAngle() * bank_sense;
962 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
963 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
964 // The only way to resolve this is to make them slow down.
970 void FGAIAircraft::updateVerticalSpeedTarget() {
971 // adjust target Altitude, based on ground elevation when on ground
975 } else if (alt_lock) {
976 // find target vertical speed
978 if (altitude_ft < tgt_altitude_ft) {
979 tgt_vs = tgt_altitude_ft - altitude_ft;
980 if (tgt_vs > _performance->climbRate())
981 tgt_vs = _performance->climbRate();
983 tgt_vs = tgt_altitude_ft - altitude_ft;
984 if (tgt_vs < (-_performance->descentRate()))
985 tgt_vs = -_performance->descentRate();
988 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
990 if (tgt_altitude_ft < altitude_ft)
992 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
993 && (fabs(max_vs) < fabs(tgt_vs)))
996 if (fabs(tgt_vs) < fabs(min_vs))
1003 void FGAIAircraft::updatePitchAngleTarget() {
1004 // if on ground and above vRotate -> initial rotation
1005 if (onGround() && (speed > _performance->vRotate()))
1006 tgt_pitch = 8.0; // some rough B737 value
1008 //TODO pitch angle on approach and landing
1010 // match pitch angle to vertical speed
1011 else if (tgt_vs > 0) {
1012 tgt_pitch = tgt_vs * 0.005;
1014 tgt_pitch = tgt_vs * 0.002;
1018 string FGAIAircraft::atGate() {
1020 if (fp->getLeg() < 3) {
1022 if (fp->getGate() > 0) {
1024 trafficRef->getDepartureAirport()->getDynamics()->getParking(fp->getGate());
1025 tmp = park->getName();
1032 void FGAIAircraft::handleATCRequests() {
1033 //TODO implement NullController for having no ATC to save the conditionals
1035 controller->update(getID(),
1036 pos.getLatitudeDeg(),
1037 pos.getLongitudeDeg(),
1041 processATC(controller->getInstruction(getID()));
1045 void FGAIAircraft::updateActualState() {
1046 //update current state
1047 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1051 speed = _performance->actualSpeed(this, groundTargetSpeed, dt);
1053 speed = _performance->actualSpeed(this, tgt_speed, dt);
1056 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1058 // adjust altitude (meters) based on current vertical speed (fpm)
1059 altitude_ft += vs / 60.0 * dt;
1060 pos.setElevationFt(altitude_ft);
1062 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1063 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1066 void FGAIAircraft::updateSecondaryTargetValues() {
1067 // derived target state values
1068 updateBankAngleTarget();
1069 updateVerticalSpeedTarget();
1070 updatePitchAngleTarget();
1072 //TODO calculate wind correction angle (tgt_yaw)