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/math/point3d.hxx>
26 #include <simgear/route/waypoint.hxx>
27 #include <Main/fg_props.hxx>
28 #include <Main/globals.hxx>
29 #include <Main/viewer.hxx>
30 #include <Scenery/scenery.hxx>
31 #include <Scenery/tilemgr.hxx>
32 #include <Airports/dynamics.hxx>
39 # define finite _finite
40 #elif defined(__sun) || defined(sgi)
46 #include "AIAircraft.hxx"
47 #include "performancedata.hxx"
48 #include "performancedb.hxx"
50 //#include <Airports/trafficcontroller.hxx>
52 static string tempReg;
54 class AI_OutOfSight{};
57 FGAIAircraft::FGAIAircraft(FGAISchedule *ref) : FGAIBase(otAircraft) {
60 groundOffset = trafficRef->getGroundOffset();
61 setCallSign(trafficRef->getCallSign());
76 groundTargetSpeed = 0;
78 // set heading and altitude locks
82 headingChangeRate = 0.0;
86 _performance = 0; //TODO initialize to JET_TRANSPORT from PerformanceDB
91 FGAIAircraft::~FGAIAircraft() {
94 controller->signOff(getID());
98 void FGAIAircraft::readFromScenario(SGPropertyNode* scFileNode) {
102 FGAIBase::readFromScenario(scFileNode);
104 setPerformance(scFileNode->getStringValue("class", "jet_transport"));
105 setFlightPlan(scFileNode->getStringValue("flightplan"),
106 scFileNode->getBoolValue("repeat", false));
107 setCallSign(scFileNode->getStringValue("callsign"));
111 void FGAIAircraft::bind() {
114 props->tie("controls/gear/gear-down",
115 SGRawValueMethods<FGAIAircraft,bool>(*this,
116 &FGAIAircraft::_getGearDown));
120 void FGAIAircraft::unbind() {
123 props->untie("controls/gear/gear-down");
127 void FGAIAircraft::update(double dt) {
128 FGAIBase::update(dt);
133 void FGAIAircraft::setPerformance(const std::string& acclass) {
134 static PerformanceDB perfdb; //TODO make it a global service
135 setPerformance(perfdb.getDataFor(acclass));
139 void FGAIAircraft::setPerformance(PerformanceData *ps) {
144 void FGAIAircraft::Run(double dt) {
145 FGAIAircraft::dt = dt;
148 updatePrimaryTargetValues(); // target hdg, alt, speed
150 catch (AI_OutOfSight) {
153 catch (FP_Inactive) {
155 groundTargetSpeed = 0;
158 handleATCRequests(); // ATC also has a word to say
159 updateSecondaryTargetValues(); // target roll, vertical speed, pitch
161 UpdateRadar(manager);
166 void FGAIAircraft::AccelTo(double speed) {
171 void FGAIAircraft::PitchTo(double angle) {
177 void FGAIAircraft::RollTo(double angle) {
183 void FGAIAircraft::YawTo(double angle) {
188 void FGAIAircraft::ClimbTo(double alt_ft ) {
189 tgt_altitude_ft = alt_ft;
194 void FGAIAircraft::TurnTo(double heading) {
195 tgt_heading = heading;
200 double FGAIAircraft::sign(double x) {
208 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
209 if (!flightplan.empty()) {
210 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
211 fp->setRepeat(repeat);
217 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
223 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
225 // the one behind you
226 FGAIFlightPlan::waypoint* prev = 0;
228 FGAIFlightPlan::waypoint* curr = 0;
230 FGAIFlightPlan::waypoint* next = 0;
232 prev = fp->getPreviousWaypoint();
233 curr = fp->getCurrentWaypoint();
234 next = fp->getNextWaypoint();
238 ///////////////////////////////////////////////////////////////////////////
239 // Initialize the flightplan
240 //////////////////////////////////////////////////////////////////////////
242 handleFirstWaypoint();
244 } // end of initialization
245 if (! fpExecutable(now))
249 if (! leadPointReached(curr)) {
250 controlHeading(curr);
251 controlSpeed(curr, next);
253 if (curr->finished) //end of the flight plan
263 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
264 tgt_heading = fp->getBearing(curr, next);
268 //TODO let the fp handle this (loading of next leg)
269 fp->IncrementWaypoint((bool) trafficRef);
270 if (!(fp->getNextWaypoint()) && trafficRef)
273 prev = fp->getPreviousWaypoint();
274 curr = fp->getCurrentWaypoint();
275 next = fp->getNextWaypoint();
277 // Now that we have incremented the waypoints, excute some traffic manager specific code
279 //TODO isn't this best executed right at the beginning?
280 if (! aiTrafficVisible()) {
285 if (! handleAirportEndPoints(prev, now)) {
290 announcePositionToController();
295 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
298 if (!(prev->on_ground)) // only update the tgt altitude from flightplan if not on the ground
300 tgt_altitude_ft = prev->altitude;
301 if (curr->crossat > -1000.0) {
303 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
304 / 6076.0 / speed*60.0);
305 tgt_altitude_ft = curr->crossat;
310 tgt_speed = prev->speed;
311 hdg_lock = alt_lock = true;
312 no_roll = prev->on_ground;
317 void FGAIAircraft::initializeFlightPlan() {
321 bool FGAIAircraft::_getGearDown() const {
322 return _performance->gearExtensible(this);
326 void FGAIAircraft::loadNextLeg() {
329 if ((leg = fp->getLeg()) == 10) {
331 setCallSign(trafficRef->getCallSign());
332 //props->setStringValue("callsign", callsign.c_str());
337 FGAirport *dep = trafficRef->getDepartureAirport();
338 FGAirport *arr = trafficRef->getArrivalAirport();
343 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
348 cruiseAlt, //(trafficRef->getCruiseAlt() * 100), // convert from FL to feet
349 trafficRef->getSpeed(),
353 trafficRef->getRadius(),
354 trafficRef->getFlightType(),
361 // Note: This code is copied from David Luff's AILocalTraffic
362 // Warning - ground elev determination is CPU intensive
363 // Either this function or the logic of how often it is called
364 // will almost certainly change.
366 void FGAIAircraft::getGroundElev(double dt) {
369 // Update minimally every three secs, but add some randomness
370 // to prevent all AI objects doing this in synchrony
371 if (dt_elev_count < (3.0) + (rand() % 10))
376 // Only do the proper hitlist stuff if we are within visible range of the viewer.
378 double visibility_meters = fgGetDouble("/environment/visibility-m");
380 FGViewer* vw = globals->get_current_view();
381 double course, distance;
383 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
384 SGWayPoint view (vw->getLongitude_deg(), vw->getLatitude_deg(), 0);
385 view.CourseAndDistance(current, &course, &distance);
386 if (distance > visibility_meters) {
387 //aip.getSGLocation()->set_cur_elev_m(aptElev);
391 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
392 double range = 500.0;
393 if (!globals->get_tile_mgr()->scenery_available(pos.getLatitudeDeg(), pos.getLongitudeDeg(), range)) {
394 // Try to shedule tiles for that position.
395 globals->get_tile_mgr()->update( aip.getSGLocation(), range );
398 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
400 if (globals->get_scenery()->get_elevation_m(pos.getLatitudeDeg(), pos.getLongitudeDeg(), 20000.0, alt, 0))
401 tgt_altitude_ft = alt * SG_METER_TO_FEET;
406 void FGAIAircraft::doGroundAltitude() {
407 if (fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)
408 altitude_ft = (tgt_altitude_ft + groundOffset);
410 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
414 void FGAIAircraft::announcePositionToController() {
416 int leg = fp->getLeg();
418 // Note that leg has been incremented after creating the current leg, so we should use
419 // leg numbers here that are one higher than the number that is used to create the leg
422 case 2: // Startup and Push back
423 if (trafficRef->getDepartureAirport()->getDynamics())
424 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
426 case 3: // Taxiing to runway
427 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
428 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
430 case 4: //Take off tower controller
431 if (trafficRef->getDepartureAirport()->getDynamics()) {
432 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
433 //if (trafficRef->getDepartureAirport()->getId() == "EHAM") {
434 //string trns = trafficRef->getCallSign() + " at runway " + fp->getRunway() +
435 // ". Ready for departure. " + trafficRef->getFlightType() + " to " +
436 // trafficRef->getArrivalAirport()->getId();
437 //fgSetString("/sim/messages/atc", trns.c_str());
438 // if (controller == 0) {
439 //cerr << "Error in assigning controller at " << trafficRef->getDepartureAirport()->getId() << endl;
443 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
446 case 9: // Taxiing for parking
447 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
448 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
455 if ((controller != prevController) && (prevController != 0)) {
456 prevController->signOff(getID());
458 prevController = controller;
460 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
461 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
462 trafficRef->getRadius(), leg, this);
467 // Process ATC instructions and report back
469 void FGAIAircraft::processATC(FGATCInstruction instruction) {
470 if (instruction.getCheckForCircularWait()) {
471 // This is not exactly an elegant solution,
472 // but at least it gives me a chance to check
473 // if circular waits are resolved.
474 // For now, just take the offending aircraft
477 // a more proper way should be - of course - to
478 // let an offending aircraft take an evasive action
479 // for instance taxi back a little bit.
481 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
482 if (instruction.getHoldPattern ()) {}
485 if (instruction.getHoldPosition ()) {
493 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
496 // Change speed Instruction. This can only be excecuted when there is no
497 // Hold position instruction.
498 if (instruction.getChangeSpeed ()) {
500 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
501 AccelTo(instruction.getSpeed());
503 if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
506 if (instruction.getChangeHeading ()) {
508 TurnTo(instruction.getHeading());
514 if (instruction.getChangeAltitude()) {}
519 void FGAIAircraft::handleFirstWaypoint() {
520 bool eraseWaypoints; //TODO YAGNI
523 eraseWaypoints = true;
525 eraseWaypoints = false;
528 FGAIFlightPlan::waypoint* prev = 0; // the one behind you
529 FGAIFlightPlan::waypoint* curr = 0; // the one ahead
530 FGAIFlightPlan::waypoint* next = 0;// the next plus 1
535 //TODO fp should handle this
536 fp->IncrementWaypoint(eraseWaypoints);
537 if (!(fp->getNextWaypoint()) && trafficRef)
540 prev = fp->getPreviousWaypoint(); //first waypoint
541 curr = fp->getCurrentWaypoint(); //second waypoint
542 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
544 setLatitude(prev->latitude);
545 setLongitude(prev->longitude);
546 setSpeed(prev->speed);
547 setAltitude(prev->altitude);
549 if (prev->speed > 0.0)
550 setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
552 setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
554 // If next doesn't exist, as in incrementally created flightplans for
555 // AI/Trafficmanager created plans,
556 // Make sure lead distance is initialized otherwise
558 fp->setLeadDistance(speed, hdg, curr, next);
560 if (curr->crossat > -1000.0) //use a calculated descent/climb rate
563 tgt_vs = (curr->crossat - prev->altitude)
564 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
565 / 6076.0 / prev->speed*60.0);
566 tgt_altitude_ft = curr->crossat;
569 tgt_altitude_ft = prev->altitude;
571 alt_lock = hdg_lock = true;
572 no_roll = prev->on_ground;
574 Transform(); // make sure aip is initialized.
575 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
578 // Make sure to announce the aircraft's position
579 announcePositionToController();
585 * Check Execution time (currently once every 100 ms)
586 * Add a bit of randomization to prevent the execution of all flight plans
587 * in synchrony, which can add significant periodic framerate flutter.
592 bool FGAIAircraft::fpExecutable(time_t now) {
593 double rand_exec_time = (rand() % 100) / 100;
594 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
599 * Check to see if we've reached the lead point for our next turn
604 bool FGAIAircraft::leadPointReached(FGAIFlightPlan::waypoint* curr) {
605 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
607 //cerr << "2" << endl;
608 double lead_dist = fp->getLeadDistance();
609 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
611 if (lead_dist < fabs(2*speed)) {
612 //don't skip over the waypoint
613 lead_dist = fabs(2*speed);
614 //cerr << "Extending lead distance to " << lead_dist << endl;
617 //prev_dist_to_go = dist_to_go;
618 //if (dist_to_go < lead_dist)
619 // cerr << trafficRef->getCallSign() << " Distance : " << dist_to_go << ": Lead distance " << lead_dist << " " << curr->name << endl;
620 return dist_to_go < lead_dist;
624 bool FGAIAircraft::aiTrafficVisible() {
625 double userLatitude = fgGetDouble("/position/latitude-deg");
626 double userLongitude = fgGetDouble("/position/longitude-deg");
627 double course, distance;
629 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
630 SGWayPoint user (userLongitude, userLatitude, 0);
632 user.CourseAndDistance(current, &course, &distance);
634 return ((distance * SG_METER_TO_NM) <= TRAFFICTOAIDIST);
639 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
640 * in the case of an arrival.
646 //TODO the trafficRef is the right place for the method
647 bool FGAIAircraft::handleAirportEndPoints(FGAIFlightPlan::waypoint* prev, time_t now) {
648 // prepare routing from one airport to another
649 FGAirport * dep = trafficRef->getDepartureAirport();
650 FGAirport * arr = trafficRef->getArrivalAirport();
655 // This waypoint marks the fact that the aircraft has passed the initial taxi
656 // departure waypoint, so it can release the parking.
657 if (prev->name == "PushBackPoint") {
658 dep->getDynamics()->releaseParking(fp->getGate());
659 time_t holdUntil = now + 120;
660 fp->setTime(holdUntil);
661 //cerr << _getCallsign() << "Holding at pushback point" << endl;
664 // This is the last taxi waypoint, and marks the the end of the flight plan
665 // so, the schedule should update and wait for the next departure time.
666 if (prev->name == "END") {
667 time_t nextDeparture = trafficRef->getDepartureTime();
668 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
669 if (nextDeparture < (now+1200)) {
670 nextDeparture = now + 1200;
672 fp->setTime(nextDeparture); // should be "next departure"
680 * Check difference between target bearing and current heading and correct if necessary.
684 void FGAIAircraft::controlHeading(FGAIFlightPlan::waypoint* curr) {
685 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
686 //cerr << "Bearing = " << calc_bearing << endl;
689 if (calc_bearing > 360)
693 if (finite(calc_bearing)) {
694 double hdg_error = calc_bearing - tgt_heading;
695 if (fabs(hdg_error) > 0.01) {
696 TurnTo( calc_bearing );
700 cerr << "calc_bearing is not a finite number : "
702 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
703 << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
704 cerr << "waypoint name " << curr->name;
711 * Update the lead distance calculation if speed has changed sufficiently
712 * to prevent spinning (hopefully);
717 void FGAIAircraft::controlSpeed(FGAIFlightPlan::waypoint* curr, FGAIFlightPlan::waypoint* next) {
718 double speed_diff = speed - prevSpeed;
720 if (fabs(speed_diff) > 10) {
723 fp->setLeadDistance(speed, tgt_heading, curr, next);
730 * Update target values (heading, alt, speed) depending on flight plan or control properties
732 void FGAIAircraft::updatePrimaryTargetValues() {
733 if (fp) // AI object has a flightplan
735 //TODO make this a function of AIBase
736 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
737 //cerr << "UpateTArgetValues() " << endl;
738 ProcessFlightPlan(dt, now);
740 // Do execute Ground elev for inactive aircraft, so they
741 // Are repositioned to the correct ground altitude when the user flies within visibility range.
742 // In addition, check whether we are out of user range, so this aircraft
745 Transform(); // make sure aip is initialized.
749 pos.setElevationFt(altitude_ft);
752 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
753 if (! aiTrafficVisible()) {
755 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
756 throw AI_OutOfSight();
759 timeElapsed = now - fp->getStartTime();
760 if (! fp->isActive(now)) {
764 // no flight plan, update target heading, speed, and altitude
765 // from control properties. These default to the initial
766 // settings in the config file, but can be changed "on the
768 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
769 if ( lat_mode == "roll" ) {
771 = props->getDoubleValue("controls/flight/target-roll" );
775 = props->getDoubleValue("controls/flight/target-hdg" );
780 = props->getStringValue("controls/flight/longitude-mode");
781 if ( lon_mode == "alt" ) {
782 double alt = props->getDoubleValue("controls/flight/target-alt" );
786 = props->getDoubleValue("controls/flight/target-pitch" );
790 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
794 void FGAIAircraft::updatePosition() {
795 // convert speed to degrees per second
796 double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
797 * speed * 1.686 / ft_per_deg_lat;
798 double speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
799 * speed * 1.686 / ft_per_deg_lon;
802 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
803 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
807 void FGAIAircraft::updateHeading() {
808 // adjust heading based on current bank angle
813 // double turnConstant;
815 // turnConstant = 0.0088362;
817 // turnConstant = 0.088362;
818 // If on ground, calculate heading change directly
820 double headingDiff = fabs(hdg-tgt_heading);
821 double bank_sense = 0.0;
823 double diff = fabs(hdg - tgt_heading);
825 diff = fabs(diff - 360);
827 double sum = hdg + diff;
830 if (fabs(sum - tgt_heading) < 1.0) {
831 bank_sense = 1.0; // right turn
833 bank_sense = -1.0; // left turn
835 if (headingDiff > 180)
836 headingDiff = fabs(headingDiff - 360);
837 double sum = hdg + headingDiff;
840 if (fabs(sum - tgt_heading) > 0.0001) {
846 //cerr << trafficRef->getCallSign() << " Heading "
847 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
848 //if (headingDiff > 60) {
849 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
850 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
852 // groundTargetSpeed = tgt_speed;
854 if (sign(groundTargetSpeed) != sign(tgt_speed))
855 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
857 if (headingDiff > 30.0) {
858 // invert if pushed backward
859 headingChangeRate += 10.0 * dt * sign(roll);
861 // Clamp the maximum steering rate to 30 degrees per second,
862 // But only do this when the heading error is decreasing.
863 if ((headingDiff < headingError)) {
864 if (headingChangeRate > 30)
865 headingChangeRate = 30;
866 else if (headingChangeRate < -30)
867 headingChangeRate = -30;
870 if (fabs(headingChangeRate) > headingDiff)
871 headingChangeRate = headingDiff*sign(roll);
873 headingChangeRate += dt * sign(roll);
876 hdg += headingChangeRate * dt * (fabs(speed) / 15);
877 headingError = headingDiff;
879 if (fabs(speed) > 1.0) {
880 turn_radius_ft = 0.088362 * speed * speed
881 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
883 // Check if turn_radius_ft == 0; this might lead to a division by 0.
884 turn_radius_ft = 1.0;
886 double turn_circum_ft = SGD_2PI * turn_radius_ft;
887 double dist_covered_ft = speed * 1.686 * dt;
888 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
889 hdg += alpha * sign(roll);
891 while ( hdg > 360.0 ) {
903 void FGAIAircraft::updateBankAngleTarget() {
904 // adjust target bank angle if heading lock engaged
906 double bank_sense = 0.0;
907 double diff = fabs(hdg - tgt_heading);
909 diff = fabs(diff - 360);
911 double sum = hdg + diff;
914 if (fabs(sum - tgt_heading) < 1.0) {
915 bank_sense = 1.0; // right turn
917 bank_sense = -1.0; // left turn
919 if (diff < _performance->maximumBankAngle()) {
920 tgt_roll = diff * bank_sense;
922 tgt_roll = _performance->maximumBankAngle() * bank_sense;
924 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
925 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
926 // The only way to resolve this is to make them slow down.
932 void FGAIAircraft::updateVerticalSpeedTarget() {
933 // adjust target Altitude, based on ground elevation when on ground
937 } else if (alt_lock) {
938 // find target vertical speed
940 if (altitude_ft < tgt_altitude_ft) {
941 tgt_vs = tgt_altitude_ft - altitude_ft;
942 if (tgt_vs > _performance->climbRate())
943 tgt_vs = _performance->climbRate();
945 tgt_vs = tgt_altitude_ft - altitude_ft;
946 if (tgt_vs < (-_performance->descentRate()))
947 tgt_vs = -_performance->descentRate();
950 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
952 if (tgt_altitude_ft < altitude_ft)
954 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
955 && (fabs(max_vs) < fabs(tgt_vs)))
958 if (fabs(tgt_vs) < fabs(min_vs))
965 void FGAIAircraft::updatePitchAngleTarget() {
966 // if on ground and above vRotate -> initial rotation
967 if (onGround() && (speed > _performance->vRotate()))
968 tgt_pitch = 8.0; // some rough B737 value
970 //TODO pitch angle on approach and landing
972 // match pitch angle to vertical speed
973 else if (tgt_vs > 0) {
974 tgt_pitch = tgt_vs * 0.005;
976 tgt_pitch = tgt_vs * 0.002;
980 string FGAIAircraft::atGate() {
982 if (fp->getLeg() < 3) {
984 if (fp->getGate() > 0) {
986 trafficRef->getDepartureAirport()->getDynamics()->getParking(fp->getGate());
987 tmp = park->getName();
994 void FGAIAircraft::handleATCRequests() {
995 //TODO implement NullController for having no ATC to save the conditionals
997 controller->update(getID(),
998 pos.getLatitudeDeg(),
999 pos.getLongitudeDeg(),
1003 processATC(controller->getInstruction(getID()));
1007 void FGAIAircraft::updateActualState() {
1008 //update current state
1009 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1013 speed = _performance->actualSpeed(this, groundTargetSpeed, dt);
1015 speed = _performance->actualSpeed(this, tgt_speed, dt);
1018 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1020 // adjust altitude (meters) based on current vertical speed (fpm)
1021 altitude_ft += vs / 60.0 * dt;
1022 pos.setElevationFt(altitude_ft);
1024 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1025 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1028 void FGAIAircraft::updateSecondaryTargetValues() {
1029 // derived target state values
1030 updateBankAngleTarget();
1031 updateVerticalSpeedTarget();
1032 updatePitchAngleTarget();
1034 //TODO calculate wind correction angle (tgt_yaw)