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);
165 void FGAIAircraft::checkVisibility()
167 double visibility_meters = fgGetDouble("/environment/visibility-m");
169 FGViewer* vw = globals->get_current_view();
170 double course, distance;
172 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
173 SGWayPoint view (vw->getLongitude_deg(), vw->getLatitude_deg(), 0);
174 view.CourseAndDistance(current, &course, &distance);
175 if (distance > visibility_meters) {
176 //aip.getSGLocation()->set_cur_elev_m(aptElev);
186 void FGAIAircraft::AccelTo(double speed) {
191 void FGAIAircraft::PitchTo(double angle) {
197 void FGAIAircraft::RollTo(double angle) {
203 void FGAIAircraft::YawTo(double angle) {
208 void FGAIAircraft::ClimbTo(double alt_ft ) {
209 tgt_altitude_ft = alt_ft;
214 void FGAIAircraft::TurnTo(double heading) {
215 tgt_heading = heading;
220 double FGAIAircraft::sign(double x) {
228 void FGAIAircraft::setFlightPlan(const std::string& flightplan, bool repeat) {
229 if (!flightplan.empty()) {
230 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
231 fp->setRepeat(repeat);
237 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
243 void FGAIAircraft::ProcessFlightPlan( double dt, time_t now ) {
245 // the one behind you
246 FGAIFlightPlan::waypoint* prev = 0;
248 FGAIFlightPlan::waypoint* curr = 0;
250 FGAIFlightPlan::waypoint* next = 0;
252 prev = fp->getPreviousWaypoint();
253 curr = fp->getCurrentWaypoint();
254 next = fp->getNextWaypoint();
258 ///////////////////////////////////////////////////////////////////////////
259 // Initialize the flightplan
260 //////////////////////////////////////////////////////////////////////////
262 handleFirstWaypoint();
264 } // end of initialization
265 if (! fpExecutable(now))
269 if (! leadPointReached(curr)) {
270 controlHeading(curr);
271 controlSpeed(curr, next);
273 if (curr->finished) //end of the flight plan
283 //TODO more intelligent method in AIFlightPlan, no need to send data it already has :-)
284 tgt_heading = fp->getBearing(curr, next);
288 //TODO let the fp handle this (loading of next leg)
289 fp->IncrementWaypoint((bool) trafficRef);
290 if (!(fp->getNextWaypoint()) && trafficRef)
291 if (!loadNextLeg()) {
296 prev = fp->getPreviousWaypoint();
297 curr = fp->getCurrentWaypoint();
298 next = fp->getNextWaypoint();
300 // Now that we have incremented the waypoints, excute some traffic manager specific code
302 //TODO isn't this best executed right at the beginning?
303 if (! aiTrafficVisible()) {
308 if (! handleAirportEndPoints(prev, now)) {
313 announcePositionToController();
318 fp->setLeadDistance(tgt_speed, tgt_heading, curr, next);
321 if (!(prev->on_ground)) // only update the tgt altitude from flightplan if not on the ground
323 tgt_altitude_ft = prev->altitude;
324 if (curr->crossat > -1000.0) {
326 tgt_vs = (curr->crossat - altitude_ft) / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
327 / 6076.0 / speed*60.0);
328 tgt_altitude_ft = curr->crossat;
333 tgt_speed = prev->speed;
334 hdg_lock = alt_lock = true;
335 no_roll = prev->on_ground;
340 void FGAIAircraft::initializeFlightPlan() {
344 bool FGAIAircraft::_getGearDown() const {
345 return _performance->gearExtensible(this);
349 bool FGAIAircraft::loadNextLeg() {
352 if ((leg = fp->getLeg()) == 10) {
353 if (!trafficRef->next()) {
356 setCallSign(trafficRef->getCallSign());
357 //props->setStringValue("callsign", callsign.c_str());
362 FGAirport *dep = trafficRef->getDepartureAirport();
363 FGAirport *arr = trafficRef->getArrivalAirport();
368 double cruiseAlt = trafficRef->getCruiseAlt() * 100;
373 cruiseAlt, //(trafficRef->getCruiseAlt() * 100), // convert from FL to feet
374 trafficRef->getSpeed(),
378 trafficRef->getRadius(),
379 trafficRef->getFlightType(),
382 //cerr << "created leg " << leg << " for " << trafficRef->getCallSign() << endl;
388 // Note: This code is copied from David Luff's AILocalTraffic
389 // Warning - ground elev determination is CPU intensive
390 // Either this function or the logic of how often it is called
391 // will almost certainly change.
393 void FGAIAircraft::getGroundElev(double dt) {
396 // Update minimally every three secs, but add some randomness
397 // to prevent all AI objects doing this in synchrony
398 if (dt_elev_count < (3.0) + (rand() % 10))
403 // Only do the proper hitlist stuff if we are within visible range of the viewer.
405 double visibility_meters = fgGetDouble("/environment/visibility-m");
407 FGViewer* vw = globals->get_current_view();
408 double course, distance;
410 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
411 SGWayPoint view (vw->getLongitude_deg(), vw->getLatitude_deg(), 0);
412 view.CourseAndDistance(current, &course, &distance);
413 if (distance > visibility_meters) {
414 //aip.getSGLocation()->set_cur_elev_m(aptElev);
418 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
419 double range = 500.0;
420 if (!globals->get_tile_mgr()->scenery_available(pos.getLatitudeDeg(), pos.getLongitudeDeg(), range)) {
421 // Try to shedule tiles for that position.
422 globals->get_tile_mgr()->update( aip.getSGLocation(), range );
425 // FIXME: make sure the pos.lat/pos.lon values are in degrees ...
427 if (globals->get_scenery()->get_elevation_m(pos.getLatitudeDeg(), pos.getLongitudeDeg(), 20000.0, alt, 0))
428 tgt_altitude_ft = alt * SG_METER_TO_FEET;
433 void FGAIAircraft::doGroundAltitude() {
434 if (fabs(altitude_ft - (tgt_altitude_ft+groundOffset)) > 1000.0)
435 altitude_ft = (tgt_altitude_ft + groundOffset);
437 altitude_ft += 0.1 * ((tgt_altitude_ft+groundOffset) - altitude_ft);
441 void FGAIAircraft::announcePositionToController() {
443 int leg = fp->getLeg();
445 // Note that leg has been incremented after creating the current leg, so we should use
446 // leg numbers here that are one higher than the number that is used to create the leg
449 case 2: // Startup and Push back
450 if (trafficRef->getDepartureAirport()->getDynamics())
451 controller = trafficRef->getDepartureAirport()->getDynamics()->getStartupController();
453 case 3: // Taxiing to runway
454 if (trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork()->exists())
455 controller = trafficRef->getDepartureAirport()->getDynamics()->getGroundNetwork();
457 case 4: //Take off tower controller
458 if (trafficRef->getDepartureAirport()->getDynamics()) {
459 controller = trafficRef->getDepartureAirport()->getDynamics()->getTowerController();
460 //if (trafficRef->getDepartureAirport()->getId() == "EHAM") {
461 //string trns = trafficRef->getCallSign() + " at runway " + fp->getRunway() +
462 // ". Ready for departure. " + trafficRef->getFlightType() + " to " +
463 // trafficRef->getArrivalAirport()->getId();
464 //fgSetString("/sim/messages/atc", trns.c_str());
465 // if (controller == 0) {
466 //cerr << "Error in assigning controller at " << trafficRef->getDepartureAirport()->getId() << endl;
470 cerr << "Error: Could not find Dynamics at airport : " << trafficRef->getDepartureAirport()->getId() << endl;
473 case 9: // Taxiing for parking
474 if (trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork()->exists())
475 controller = trafficRef->getArrivalAirport()->getDynamics()->getGroundNetwork();
482 if ((controller != prevController) && (prevController != 0)) {
483 prevController->signOff(getID());
485 prevController = controller;
487 controller->announcePosition(getID(), fp, fp->getCurrentWaypoint()->routeIndex,
488 _getLatitude(), _getLongitude(), hdg, speed, altitude_ft,
489 trafficRef->getRadius(), leg, this);
494 // Process ATC instructions and report back
496 void FGAIAircraft::processATC(FGATCInstruction instruction) {
497 if (instruction.getCheckForCircularWait()) {
498 // This is not exactly an elegant solution,
499 // but at least it gives me a chance to check
500 // if circular waits are resolved.
501 // For now, just take the offending aircraft
504 // a more proper way should be - of course - to
505 // let an offending aircraft take an evasive action
506 // for instance taxi back a little bit.
508 //cerr << "Processing ATC instruction (not Implimented yet)" << endl;
509 if (instruction.getHoldPattern ()) {}
512 if (instruction.getHoldPosition ()) {
520 // cerr << trafficRef->getCallSign() << " Resuming Taxi." << endl;
523 // Change speed Instruction. This can only be excecuted when there is no
524 // Hold position instruction.
525 if (instruction.getChangeSpeed ()) {
527 //cerr << trafficRef->getCallSign() << " Changing Speed " << endl;
528 AccelTo(instruction.getSpeed());
530 if (fp) AccelTo(fp->getPreviousWaypoint()->speed);
533 if (instruction.getChangeHeading ()) {
535 TurnTo(instruction.getHeading());
541 if (instruction.getChangeAltitude()) {}
546 void FGAIAircraft::handleFirstWaypoint() {
547 bool eraseWaypoints; //TODO YAGNI
550 eraseWaypoints = true;
552 eraseWaypoints = false;
555 FGAIFlightPlan::waypoint* prev = 0; // the one behind you
556 FGAIFlightPlan::waypoint* curr = 0; // the one ahead
557 FGAIFlightPlan::waypoint* next = 0;// the next plus 1
562 //TODO fp should handle this
563 fp->IncrementWaypoint(eraseWaypoints);
564 if (!(fp->getNextWaypoint()) && trafficRef)
565 if (!loadNextLeg()) {
570 prev = fp->getPreviousWaypoint(); //first waypoint
571 curr = fp->getCurrentWaypoint(); //second waypoint
572 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
574 setLatitude(prev->latitude);
575 setLongitude(prev->longitude);
576 setSpeed(prev->speed);
577 setAltitude(prev->altitude);
579 if (prev->speed > 0.0)
580 setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
582 setHeading(fp->getBearing(curr->latitude, curr->longitude, prev));
584 // If next doesn't exist, as in incrementally created flightplans for
585 // AI/Trafficmanager created plans,
586 // Make sure lead distance is initialized otherwise
588 fp->setLeadDistance(speed, hdg, curr, next);
590 if (curr->crossat > -1000.0) //use a calculated descent/climb rate
593 tgt_vs = (curr->crossat - prev->altitude)
594 / (fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr)
595 / 6076.0 / prev->speed*60.0);
596 tgt_altitude_ft = curr->crossat;
599 tgt_altitude_ft = prev->altitude;
601 alt_lock = hdg_lock = true;
602 no_roll = prev->on_ground;
604 Transform(); // make sure aip is initialized.
605 getGroundElev(60.1); // make sure it's executed first time around, so force a large dt value
608 // Make sure to announce the aircraft's position
609 announcePositionToController();
615 * Check Execution time (currently once every 100 ms)
616 * Add a bit of randomization to prevent the execution of all flight plans
617 * in synchrony, which can add significant periodic framerate flutter.
622 bool FGAIAircraft::fpExecutable(time_t now) {
623 double rand_exec_time = (rand() % 100) / 100;
624 return (dt_count > (0.1+rand_exec_time)) && (fp->isActive(now));
629 * Check to see if we've reached the lead point for our next turn
634 bool FGAIAircraft::leadPointReached(FGAIFlightPlan::waypoint* curr) {
635 double dist_to_go = fp->getDistanceToGo(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
637 //cerr << "2" << endl;
638 double lead_dist = fp->getLeadDistance();
639 // experimental: Use fabs, because speed can be negative (I hope) during push_back.
641 if (lead_dist < fabs(2*speed)) {
642 //don't skip over the waypoint
643 lead_dist = fabs(2*speed);
644 //cerr << "Extending lead distance to " << lead_dist << endl;
647 //prev_dist_to_go = dist_to_go;
648 //if (dist_to_go < lead_dist)
649 // cerr << trafficRef->getCallSign() << " Distance : "
650 // << dist_to_go << ": Lead distance "
651 // << lead_dist << " " << curr->name
652 // << " Ground target speed " << groundTargetSpeed << endl;
654 return dist_to_go < lead_dist;
658 bool FGAIAircraft::aiTrafficVisible() {
659 double userLatitude = fgGetDouble("/position/latitude-deg");
660 double userLongitude = fgGetDouble("/position/longitude-deg");
661 double course, distance;
663 SGWayPoint current(pos.getLongitudeDeg(), pos.getLatitudeDeg(), 0);
664 SGWayPoint user (userLongitude, userLatitude, 0);
666 user.CourseAndDistance(current, &course, &distance);
668 return ((distance * SG_METER_TO_NM) <= TRAFFICTOAIDISTTODIE);
673 * Handle release of parking gate, once were taxiing. Also ensure service time at the gate
674 * in the case of an arrival.
680 //TODO the trafficRef is the right place for the method
681 bool FGAIAircraft::handleAirportEndPoints(FGAIFlightPlan::waypoint* prev, time_t now) {
682 // prepare routing from one airport to another
683 FGAirport * dep = trafficRef->getDepartureAirport();
684 FGAirport * arr = trafficRef->getArrivalAirport();
689 // This waypoint marks the fact that the aircraft has passed the initial taxi
690 // departure waypoint, so it can release the parking.
691 //cerr << trafficRef->getCallSign() << " has passed waypoint " << prev->name << " at speed " << speed << endl;
692 if (prev->name == "PushBackPoint") {
693 dep->getDynamics()->releaseParking(fp->getGate());
694 time_t holdUntil = now + 120;
695 fp->setTime(holdUntil);
696 //cerr << _getCallsign() << "Holding at pushback point" << endl;
699 // This is the last taxi waypoint, and marks the the end of the flight plan
700 // so, the schedule should update and wait for the next departure time.
701 if (prev->name == "END") {
702 time_t nextDeparture = trafficRef->getDepartureTime();
703 // make sure to wait at least 20 minutes at parking to prevent "nervous" taxi behavior
704 if (nextDeparture < (now+1200)) {
705 nextDeparture = now + 1200;
707 fp->setTime(nextDeparture); // should be "next departure"
715 * Check difference between target bearing and current heading and correct if necessary.
719 void FGAIAircraft::controlHeading(FGAIFlightPlan::waypoint* curr) {
720 double calc_bearing = fp->getBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr);
721 //cerr << "Bearing = " << calc_bearing << endl;
724 if (calc_bearing > 360)
728 if (finite(calc_bearing)) {
729 double hdg_error = calc_bearing - tgt_heading;
730 if (fabs(hdg_error) > 0.01) {
731 TurnTo( calc_bearing );
735 cerr << "calc_bearing is not a finite number : "
737 << "pos : " << pos.getLatitudeDeg() << ", " << pos.getLongitudeDeg()
738 << "waypoint " << curr->latitude << ", " << curr->longitude << endl;
739 cerr << "waypoint name " << curr->name;
746 * Update the lead distance calculation if speed has changed sufficiently
747 * to prevent spinning (hopefully);
752 void FGAIAircraft::controlSpeed(FGAIFlightPlan::waypoint* curr, FGAIFlightPlan::waypoint* next) {
753 double speed_diff = speed - prevSpeed;
755 if (fabs(speed_diff) > 10) {
758 fp->setLeadDistance(speed, tgt_heading, curr, next);
765 * Update target values (heading, alt, speed) depending on flight plan or control properties
767 void FGAIAircraft::updatePrimaryTargetValues() {
768 if (fp) // AI object has a flightplan
770 //TODO make this a function of AIBase
771 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
772 //cerr << "UpateTArgetValues() " << endl;
773 ProcessFlightPlan(dt, now);
775 // Do execute Ground elev for inactive aircraft, so they
776 // Are repositioned to the correct ground altitude when the user flies within visibility range.
777 // In addition, check whether we are out of user range, so this aircraft
780 Transform(); // make sure aip is initialized.
784 pos.setElevationFt(altitude_ft);
787 //cerr << trafficRef->getRegistration() << " Setting altitude to " << altitude_ft;
788 if (! aiTrafficVisible()) {
790 //cerr << trafficRef->getRegistration() << " is set to die " << endl;
791 throw AI_OutOfSight();
794 timeElapsed = now - fp->getStartTime();
795 if (! fp->isActive(now)) {
799 // no flight plan, update target heading, speed, and altitude
800 // from control properties. These default to the initial
801 // settings in the config file, but can be changed "on the
803 string lat_mode = props->getStringValue("controls/flight/lateral-mode");
804 if ( lat_mode == "roll" ) {
806 = props->getDoubleValue("controls/flight/target-roll" );
810 = props->getDoubleValue("controls/flight/target-hdg" );
815 = props->getStringValue("controls/flight/longitude-mode");
816 if ( lon_mode == "alt" ) {
817 double alt = props->getDoubleValue("controls/flight/target-alt" );
821 = props->getDoubleValue("controls/flight/target-pitch" );
825 AccelTo( props->getDoubleValue("controls/flight/target-spd" ) );
829 void FGAIAircraft::updatePosition() {
830 // convert speed to degrees per second
831 double speed_north_deg_sec = cos( hdg * SGD_DEGREES_TO_RADIANS )
832 * speed * 1.686 / ft_per_deg_lat;
833 double speed_east_deg_sec = sin( hdg * SGD_DEGREES_TO_RADIANS )
834 * speed * 1.686 / ft_per_deg_lon;
837 pos.setLatitudeDeg( pos.getLatitudeDeg() + speed_north_deg_sec * dt);
838 pos.setLongitudeDeg( pos.getLongitudeDeg() + speed_east_deg_sec * dt);
842 void FGAIAircraft::updateHeading() {
843 // adjust heading based on current bank angle
848 // double turnConstant;
850 // turnConstant = 0.0088362;
852 // turnConstant = 0.088362;
853 // If on ground, calculate heading change directly
855 double headingDiff = fabs(hdg-tgt_heading);
856 double bank_sense = 0.0;
858 double diff = fabs(hdg - tgt_heading);
860 diff = fabs(diff - 360);
862 double sum = hdg + diff;
865 if (fabs(sum - tgt_heading) < 1.0) {
866 bank_sense = 1.0; // right turn
868 bank_sense = -1.0; // left turn
870 if (headingDiff > 180)
871 headingDiff = fabs(headingDiff - 360);
872 double sum = hdg + headingDiff;
875 if (fabs(sum - tgt_heading) > 0.0001) {
881 //cerr << trafficRef->getCallSign() << " Heading "
882 // << hdg << ". Target " << tgt_heading << ". Diff " << fabs(sum - tgt_heading) << ". Speed " << speed << endl;
883 //if (headingDiff > 60) {
884 groundTargetSpeed = tgt_speed; // * cos(headingDiff * SG_DEGREES_TO_RADIANS);
885 //groundTargetSpeed = tgt_speed - tgt_speed * (headingDiff/180);
887 // groundTargetSpeed = tgt_speed;
889 if (sign(groundTargetSpeed) != sign(tgt_speed))
890 groundTargetSpeed = 0.21 * sign(tgt_speed); // to prevent speed getting stuck in 'negative' mode
892 if (headingDiff > 30.0) {
893 // invert if pushed backward
894 headingChangeRate += 10.0 * dt * sign(roll);
896 // Clamp the maximum steering rate to 30 degrees per second,
897 // But only do this when the heading error is decreasing.
898 if ((headingDiff < headingError)) {
899 if (headingChangeRate > 30)
900 headingChangeRate = 30;
901 else if (headingChangeRate < -30)
902 headingChangeRate = -30;
905 if (fabs(headingChangeRate) > headingDiff)
906 headingChangeRate = headingDiff*sign(roll);
908 headingChangeRate += dt * sign(roll);
911 hdg += headingChangeRate * dt * (fabs(speed) / 15);
912 headingError = headingDiff;
914 if (fabs(speed) > 1.0) {
915 turn_radius_ft = 0.088362 * speed * speed
916 / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
918 // Check if turn_radius_ft == 0; this might lead to a division by 0.
919 turn_radius_ft = 1.0;
921 double turn_circum_ft = SGD_2PI * turn_radius_ft;
922 double dist_covered_ft = speed * 1.686 * dt;
923 double alpha = dist_covered_ft / turn_circum_ft * 360.0;
924 hdg += alpha * sign(roll);
926 while ( hdg > 360.0 ) {
938 void FGAIAircraft::updateBankAngleTarget() {
939 // adjust target bank angle if heading lock engaged
941 double bank_sense = 0.0;
942 double diff = fabs(hdg - tgt_heading);
944 diff = fabs(diff - 360);
946 double sum = hdg + diff;
949 if (fabs(sum - tgt_heading) < 1.0) {
950 bank_sense = 1.0; // right turn
952 bank_sense = -1.0; // left turn
954 if (diff < _performance->maximumBankAngle()) {
955 tgt_roll = diff * bank_sense;
957 tgt_roll = _performance->maximumBankAngle() * bank_sense;
959 if ((fabs((double) spinCounter) > 1) && (diff > _performance->maximumBankAngle())) {
960 tgt_speed *= 0.999; // Ugly hack: If aircraft get stuck, they will continually spin around.
961 // The only way to resolve this is to make them slow down.
967 void FGAIAircraft::updateVerticalSpeedTarget() {
968 // adjust target Altitude, based on ground elevation when on ground
972 } else if (alt_lock) {
973 // find target vertical speed
975 if (altitude_ft < tgt_altitude_ft) {
976 tgt_vs = tgt_altitude_ft - altitude_ft;
977 if (tgt_vs > _performance->climbRate())
978 tgt_vs = _performance->climbRate();
980 tgt_vs = tgt_altitude_ft - altitude_ft;
981 if (tgt_vs < (-_performance->descentRate()))
982 tgt_vs = -_performance->descentRate();
985 double max_vs = 4*(tgt_altitude_ft - altitude_ft);
987 if (tgt_altitude_ft < altitude_ft)
989 if ((fabs(tgt_altitude_ft - altitude_ft) < 1500.0)
990 && (fabs(max_vs) < fabs(tgt_vs)))
993 if (fabs(tgt_vs) < fabs(min_vs))
1000 void FGAIAircraft::updatePitchAngleTarget() {
1001 // if on ground and above vRotate -> initial rotation
1002 if (onGround() && (speed > _performance->vRotate()))
1003 tgt_pitch = 8.0; // some rough B737 value
1005 //TODO pitch angle on approach and landing
1007 // match pitch angle to vertical speed
1008 else if (tgt_vs > 0) {
1009 tgt_pitch = tgt_vs * 0.005;
1011 tgt_pitch = tgt_vs * 0.002;
1015 string FGAIAircraft::atGate() {
1017 if (fp->getLeg() < 3) {
1019 if (fp->getGate() > 0) {
1021 trafficRef->getDepartureAirport()->getDynamics()->getParking(fp->getGate());
1022 tmp = park->getName();
1029 void FGAIAircraft::handleATCRequests() {
1030 //TODO implement NullController for having no ATC to save the conditionals
1032 controller->update(getID(),
1033 pos.getLatitudeDeg(),
1034 pos.getLongitudeDeg(),
1038 processATC(controller->getInstruction(getID()));
1042 void FGAIAircraft::updateActualState() {
1043 //update current state
1044 //TODO have a single tgt_speed and check speed limit on ground on setting tgt_speed
1048 speed = _performance->actualSpeed(this, groundTargetSpeed, dt);
1050 speed = _performance->actualSpeed(this, tgt_speed, dt);
1053 roll = _performance->actualBankAngle(this, tgt_roll, dt);
1055 // adjust altitude (meters) based on current vertical speed (fpm)
1056 altitude_ft += vs / 60.0 * dt;
1057 pos.setElevationFt(altitude_ft);
1059 vs = _performance->actualVerticalSpeed(this, tgt_vs, dt);
1060 pitch = _performance->actualPitch(this, tgt_pitch, dt);
1063 void FGAIAircraft::updateSecondaryTargetValues() {
1064 // derived target state values
1065 updateBankAngleTarget();
1066 updateVerticalSpeedTarget();
1067 updatePitchAngleTarget();
1069 //TODO calculate wind correction angle (tgt_yaw)