1 // newauto.cxx -- autopilot defines and prototypes (very alpha)
3 // Started April 1998 Copyright (C) 1998
5 // Contributions by Jeff Goeke-Smith <jgoeke@voyager.net>
6 // Norman Vine <nhv@cape.com>
7 // Curtis Olson <curt@flightgear.org>
9 // This program is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU General Public License as
11 // published by the Free Software Foundation; either version 2 of the
12 // License, or (at your option) any later version.
14 // This program is distributed in the hope that it will be useful, but
15 // WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // General Public License for more details.
19 // You should have received a copy of the GNU General Public License
20 // along with this program; if not, write to the Free Software
21 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
30 #include <stdio.h> // sprintf()
31 #include <string.h> // strcmp()
33 #include <simgear/constants.h>
34 #include <simgear/sg_inlines.h>
35 #include <simgear/debug/logstream.hxx>
36 #include <simgear/math/sg_geodesy.hxx>
37 #include <simgear/math/sg_random.h>
38 #include <simgear/route/route.hxx>
40 #include <Cockpit/steam.hxx>
41 #include <Cockpit/radiostack.hxx>
42 #include <Controls/controls.hxx>
43 #include <FDM/flight.hxx>
44 #include <Main/globals.hxx>
45 #include <Scenery/scenery.hxx>
47 #include "newauto.hxx"
50 /// These statics will eventually go into the class
51 /// they are just here while I am experimenting -- NHV :-)
52 // AutoPilot Gain Adjuster members
53 static double MaxRollAdjust; // MaxRollAdjust = 2 * APData->MaxRoll;
54 static double RollOutAdjust; // RollOutAdjust = 2 * APData->RollOut;
55 static double MaxAileronAdjust; // MaxAileronAdjust = 2 * APData->MaxAileron;
56 static double RollOutSmoothAdjust; // RollOutSmoothAdjust = 2 * APData->RollOutSmooth;
58 static char NewTgtAirportId[16];
59 // static char NewTgtAirportLabel[] = "Enter New TgtAirport ID";
61 extern char *coord_format_lat(float);
62 extern char *coord_format_lon(float);
66 FGAutopilot::FGAutopilot()
71 FGAutopilot::~FGAutopilot() {}
74 void FGAutopilot::MakeTargetLatLonStr( double lat, double lon ) {
75 sprintf( TargetLatitudeStr , "%s", coord_format_lat(get_TargetLatitude()));
76 sprintf( TargetLongitudeStr, "%s", coord_format_lon(get_TargetLongitude()));
77 sprintf( TargetLatLonStr, "%s %s", TargetLatitudeStr, TargetLongitudeStr );
81 void FGAutopilot::MakeTargetAltitudeStr( double altitude ) {
82 if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
83 sprintf( TargetAltitudeStr, "APAltitude %6.0f+", altitude );
85 sprintf( TargetAltitudeStr, "APAltitude %6.0f", altitude );
90 void FGAutopilot::MakeTargetHeadingStr( double bearing ) {
93 } else if (bearing > 360. ) {
96 sprintf( TargetHeadingStr, "APHeading %6.1f", bearing );
100 static inline double get_speed( void ) {
101 return( cur_fdm_state->get_V_equiv_kts() );
104 static inline double get_ground_speed() {
105 // starts in ft/s so we convert to kts
106 static const SGPropertyNode * speedup_node = fgGetNode("/sim/speed-up");
108 double ft_s = cur_fdm_state->get_V_ground_speed()
109 * speedup_node->getIntValue();
110 double kts = ft_s * SG_FEET_TO_METER * 3600 * SG_METER_TO_NM;
116 void FGAutopilot::MakeTargetWPStr( double distance ) {
117 static time_t last_time = 0;
118 time_t current_time = time(NULL);
119 if ( last_time == current_time ) {
123 last_time = current_time;
127 int size = globals->get_route()->size();
129 // start by wiping the strings
136 SGWayPoint wp1 = globals->get_route()->get_waypoint( 0 );
138 double eta = accum * SG_METER_TO_NM / get_ground_speed();
139 if ( eta >= 100.0 ) { eta = 99.999; }
141 if ( eta < (1.0/6.0) ) {
142 // within 10 minutes, bump up to min/secs
146 minor = (int)((eta - (int)eta) * 60.0);
147 sprintf( TargetWP1Str, "%s %.2f NM ETA %d:%02d",
148 wp1.get_id().c_str(),
149 accum*SG_METER_TO_NM, major, minor );
154 SGWayPoint wp2 = globals->get_route()->get_waypoint( 1 );
155 accum += wp2.get_distance();
157 double eta = accum * SG_METER_TO_NM / get_ground_speed();
158 if ( eta >= 100.0 ) { eta = 99.999; }
160 if ( eta < (1.0/6.0) ) {
161 // within 10 minutes, bump up to min/secs
165 minor = (int)((eta - (int)eta) * 60.0);
166 sprintf( TargetWP2Str, "%s %.2f NM ETA %d:%02d",
167 wp2.get_id().c_str(),
168 accum*SG_METER_TO_NM, major, minor );
173 for ( int i = 2; i < size; ++i ) {
174 accum += globals->get_route()->get_waypoint( i ).get_distance();
177 SGWayPoint wpn = globals->get_route()->get_waypoint( size - 1 );
179 double eta = accum * SG_METER_TO_NM / get_ground_speed();
180 if ( eta >= 100.0 ) { eta = 99.999; }
182 if ( eta < (1.0/6.0) ) {
183 // within 10 minutes, bump up to min/secs
187 minor = (int)((eta - (int)eta) * 60.0);
188 sprintf( TargetWP3Str, "%s %.2f NM ETA %d:%02d",
189 wpn.get_id().c_str(),
190 accum*SG_METER_TO_NM, major, minor );
195 void FGAutopilot::update_old_control_values() {
196 old_aileron = globals->get_controls()->get_aileron();
197 old_elevator = globals->get_controls()->get_elevator();
198 old_elevator_trim = globals->get_controls()->get_elevator_trim();
199 old_rudder = globals->get_controls()->get_rudder();
203 // Initialize autopilot subsystem
205 void FGAutopilot::init ()
207 SG_LOG( SG_AUTOPILOT, SG_INFO, "Init AutoPilot Subsystem" );
209 // bind data input property nodes...
210 latitude_node = fgGetNode("/position/latitude-deg", true);
211 longitude_node = fgGetNode("/position/longitude-deg", true);
212 altitude_node = fgGetNode("/position/altitude-ft", true);
213 altitude_agl_node = fgGetNode("/position/altitude-agl-ft", true);
214 vertical_speed_node = fgGetNode("/velocities/vertical-speed-fps", true);
215 heading_node = fgGetNode("/orientation/heading-deg", true);
216 roll_node = fgGetNode("/orientation/roll-deg", true);
217 pitch_node = fgGetNode("/orientation/pitch-deg", true);
219 // bind config property nodes...
221 = fgGetNode("/autopilot/config/target-climb-rate-fpm", true);
223 = fgGetNode("/autopilot/config/target-descent-rate-fpm", true);
224 min_climb = fgGetNode("/autopilot/config/min-climb-speed-kt", true);
225 best_climb = fgGetNode("/autopilot/config/best-climb-speed-kt", true);
227 = fgGetNode("/autopilot/config/elevator-adj-factor", true);
229 = fgGetNode("/autopilot/config/integral-contribution", true);
231 = fgGetNode("/autopilot/config/zero-pitch-throttle", true);
232 zero_pitch_trim_full_throttle
233 = fgGetNode("/autopilot/config/zero-pitch-trim-full-throttle", true);
234 current_throttle = fgGetNode("/controls/throttle");
236 // initialize config properties with defaults (in case config isn't there)
237 if ( TargetClimbRate->getFloatValue() < 1 )
238 fgSetFloat( "/autopilot/config/target-climb-rate-fpm", 500);
239 if ( TargetDescentRate->getFloatValue() < 1 )
240 fgSetFloat( "/autopilot/config/target-descent-rate-fpm", 1000 );
241 if ( min_climb->getFloatValue() < 1)
242 fgSetFloat( "/autopilot/config/min-climb-speed-kt", 70 );
243 if (best_climb->getFloatValue() < 1)
244 fgSetFloat( "/autopilot/config/best-climb-speed-kt", 120 );
245 if (elevator_adj_factor->getFloatValue() < 1)
246 fgSetFloat( "/autopilot/config/elevator-adj-factor", 5000 );
247 if ( integral_contrib->getFloatValue() < 0.0000001 )
248 fgSetFloat( "/autopilot/config/integral-contribution", 0.01 );
249 if ( zero_pitch_throttle->getFloatValue() < 0.0000001 )
250 fgSetFloat( "/autopilot/config/zero-pitch-throttle", 0.60 );
251 if ( zero_pitch_trim_full_throttle->getFloatValue() < 0.0000001 )
252 fgSetFloat( "/autopilot/config/zero-pitch-trim-full-throttle", 0.15 );
255 heading_hold = false ; // turn the heading hold off
256 altitude_hold = false ; // turn the altitude hold off
257 auto_throttle = false ; // turn the auto throttle off
258 heading_mode = DEFAULT_AP_HEADING_LOCK;
260 DGTargetHeading = fgGetDouble("/autopilot/settings/heading-bug-deg");
261 TargetHeading = fgGetDouble("/autopilot/settings/heading-bug-deg");
262 TargetAltitude = fgGetDouble("/autopilot/settings/altitude-ft") * SG_FEET_TO_METER;
264 // Initialize target location to startup location
265 old_lat = latitude_node->getDoubleValue();
266 old_lon = longitude_node->getDoubleValue();
267 // set_WayPoint( old_lon, old_lat, 0.0, "default" );
269 MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
271 alt_error_accum = 0.0;
272 climb_error_accum = 0.0;
274 MakeTargetAltitudeStr( TargetAltitude );
275 MakeTargetHeadingStr( TargetHeading );
277 // These eventually need to be read from current_aircaft somehow.
279 // the maximum roll, in Deg
282 // the deg from heading to start rolling out at, in Deg
285 // how far can I move the aleron from center.
288 // Smoothing distance for alerion control
291 // Hardwired for now should be in options
292 // 25% max control variablilty 0.5 / 2.0
293 disengage_threshold = 1.0;
295 #if !defined( USING_SLIDER_CLASS )
296 MaxRollAdjust = 2 * MaxRoll;
297 RollOutAdjust = 2 * RollOut;
298 MaxAileronAdjust = 2 * MaxAileron;
299 RollOutSmoothAdjust = 2 * RollOutSmooth;
300 #endif // !defined( USING_SLIDER_CLASS )
302 update_old_control_values();
308 // Autopilot control property get/set bindings
309 fgTie("/autopilot/locks/altitude", this,
310 &FGAutopilot::getAPAltitudeLock, &FGAutopilot::setAPAltitudeLock);
311 fgSetArchivable("/autopilot/locks/altitude");
312 fgTie("/autopilot/settings/altitude-ft", this,
313 &FGAutopilot::getAPAltitude, &FGAutopilot::setAPAltitude);
314 fgSetArchivable("/autopilot/settings/altitude-ft");
315 fgTie("/autopilot/locks/glide-slope", this,
316 &FGAutopilot::getAPGSLock, &FGAutopilot::setAPGSLock);
317 fgSetArchivable("/autopilot/locks/glide-slope");
318 fgSetDouble("/autopilot/settings/altitude-ft", 3000.0f);
319 fgTie("/autopilot/locks/terrain", this,
320 &FGAutopilot::getAPTerrainLock, &FGAutopilot::setAPTerrainLock);
321 fgSetArchivable("/autopilot/locks/terrain");
322 fgTie("/autopilot/settings/climb-rate-fpm", this,
323 &FGAutopilot::getAPClimb, &FGAutopilot::setAPClimb, false);
324 fgSetArchivable("/autopilot/settings/climb-rate-fpm");
325 fgTie("/autopilot/locks/heading", this,
326 &FGAutopilot::getAPHeadingLock, &FGAutopilot::setAPHeadingLock);
327 fgSetArchivable("/autopilot/locks/heading");
328 fgTie("/autopilot/settings/heading-bug-deg", this,
329 &FGAutopilot::getAPHeadingBug, &FGAutopilot::setAPHeadingBug);
330 fgSetArchivable("/autopilot/settings/heading-bug-deg");
331 fgSetDouble("/autopilot/settings/heading-bug-deg", 0.0f);
332 fgTie("/autopilot/locks/wing-leveler", this,
333 &FGAutopilot::getAPWingLeveler, &FGAutopilot::setAPWingLeveler);
334 fgSetArchivable("/autopilot/locks/wing-leveler");
335 fgTie("/autopilot/locks/nav[0]", this,
336 &FGAutopilot::getAPNAV1Lock, &FGAutopilot::setAPNAV1Lock);
337 fgSetArchivable("/autopilot/locks/nav[0]");
338 fgTie("/autopilot/locks/auto-throttle", this,
339 &FGAutopilot::getAPAutoThrottleLock,
340 &FGAutopilot::setAPAutoThrottleLock);
341 fgSetArchivable("/autopilot/locks/auto-throttle");
342 fgTie("/autopilot/control-overrides/rudder", this,
343 &FGAutopilot::getAPRudderControl,
344 &FGAutopilot::setAPRudderControl);
345 fgSetArchivable("/autopilot/control-overrides/rudder");
346 fgTie("/autopilot/control-overrides/elevator", this,
347 &FGAutopilot::getAPElevatorControl,
348 &FGAutopilot::setAPElevatorControl);
349 fgSetArchivable("/autopilot/control-overrides/elevator");
350 fgTie("/autopilot/control-overrides/throttle", this,
351 &FGAutopilot::getAPThrottleControl,
352 &FGAutopilot::setAPThrottleControl);
353 fgSetArchivable("/autopilot/control-overrides/throttle");
357 FGAutopilot::unbind ()
361 // Reset the autopilot system
362 void FGAutopilot::reset() {
364 heading_hold = false ; // turn the heading hold off
365 altitude_hold = false ; // turn the altitude hold off
366 auto_throttle = false ; // turn the auto throttle off
367 heading_mode = DEFAULT_AP_HEADING_LOCK;
369 // TargetHeading = 0.0; // default direction, due north
370 MakeTargetHeadingStr( TargetHeading );
372 // TargetAltitude = 3000; // default altitude in meters
373 MakeTargetAltitudeStr( TargetAltitude );
375 alt_error_accum = 0.0;
376 climb_error_accum = 0.0;
378 update_old_control_values();
380 sprintf( NewTgtAirportId, "%s", fgGetString("/sim/startup/airport-id") );
382 MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
386 static double NormalizeDegrees( double Input ) {
387 // normalize the input to the range (-180,180]
388 // Input should not be greater than -360 to 360.
389 // Current rules send the output to an undefined state.
390 while ( Input > 180.0 ) { Input -= 360.0; }
391 while ( Input <= -180.0 ) { Input += 360.0; }
396 static double LinearExtrapolate( double x, double x1, double y1, double x2, double y2 ) {
397 // This procedure extrapolates the y value for the x posistion on a line defined by x1,y1; x2,y2
398 //assert(x1 != x2); // Divide by zero error. Cold abort for now
401 // static double y = 0.0;
402 // double dx = x2 -x1;
403 // if( (dx < -SG_EPSILON ) || ( dx > SG_EPSILON ) )
406 double m, b, y; // the constants to find in y=mx+b
409 m = ( y2 - y1 ) / ( x2 - x1 ); // calculate the m
411 b = y1 - m * x1; // calculate the b
413 y = m * x + b; // the final calculation
423 FGAutopilot::update (int dt)
425 // Remove the following lines when the calling funcitons start
426 // passing in the data pointer
428 // get control settings
430 double lat = latitude_node->getDoubleValue();
431 double lon = longitude_node->getDoubleValue();
432 double alt = altitude_node->getDoubleValue() * SG_FEET_TO_METER;
434 SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run() lat = " << lat <<
435 " lon = " << lon << " alt = " << alt );
437 #ifdef FG_FORCE_AUTO_DISENGAGE
438 // see if somebody else has changed them
439 if( fabs(aileron - old_aileron) > disengage_threshold ||
440 fabs(elevator - old_elevator) > disengage_threshold ||
441 fabs(elevator_trim - old_elevator_trim) >
442 disengage_threshold ||
443 fabs(rudder - old_rudder) > disengage_threshold )
445 // if controls changed externally turn autopilot off
446 waypoint_hold = false ; // turn the target hold off
447 heading_hold = false ; // turn the heading hold off
448 altitude_hold = false ; // turn the altitude hold off
449 terrain_follow = false; // turn the terrain_follow hold off
450 // auto_throttle = false; // turn the auto_throttle off
452 // stash this runs control settings
453 old_aileron = aileron;
454 old_elevator = elevator;
455 old_elevator_trim = elevator_trim;
463 if ( heading_hold == true ) {
464 if ( heading_mode == FG_DG_HEADING_LOCK ) {
465 TargetHeading = DGTargetHeading + FGSteam::get_DG_err();
466 while ( TargetHeading < 0.0 ) { TargetHeading += 360.0; }
467 while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
468 MakeTargetHeadingStr( TargetHeading );
469 } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
470 // we don't set a specific target heading in
471 // TC_HEADING_LOCK mode, we instead try to keep the turn
472 // coordinator zero'd
473 } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
474 // leave "true" target heading as is
475 while ( TargetHeading < 0.0 ) { TargetHeading += 360.0; }
476 while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
477 MakeTargetHeadingStr( TargetHeading );
478 } else if ( heading_mode == FG_HEADING_NAV1 ) {
479 // track the NAV1 heading needle deflection
481 // determine our current radial position relative to the
482 // navaid in "true" heading.
483 double cur_radial = current_radiostack->get_nav1_heading();
484 if ( current_radiostack->get_nav1_loc() ) {
485 // ILS localizers radials are already "true" in our
488 cur_radial += current_radiostack->get_nav1_magvar();
490 if ( current_radiostack->get_nav1_from_flag() ) {
492 while ( cur_radial >= 360.0 ) { cur_radial -= 360.0; }
495 // determine the target radial in "true" heading
496 double tgt_radial = current_radiostack->get_nav1_radial();
497 if ( current_radiostack->get_nav1_loc() ) {
498 // ILS localizers radials are already "true" in our
501 // VOR radials need to have that vor's offset added in
502 tgt_radial += current_radiostack->get_nav1_magvar();
505 // determine the heading adjustment needed.
507 current_radiostack->get_nav1_heading_needle_deflection()
508 * (current_radiostack->get_nav1_loc_dist() * SG_METER_TO_NM);
509 SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
511 // determine the target heading to fly to intercept the
513 TargetHeading = tgt_radial + adjustment;
514 while ( TargetHeading < 0.0 ) { TargetHeading += 360.0; }
515 while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
517 MakeTargetHeadingStr( TargetHeading );
518 } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
519 // update target heading to waypoint
521 double wp_course, wp_distance;
523 #ifdef DO_fgAP_CORRECTED_COURSE
524 // compute course made good
525 // this needs lots of special casing before use
526 double course, reverse, distance, corrected_course;
527 // need to test for iter
528 geo_inverse_wgs_84( 0, //fgAPget_altitude(),
536 #endif // DO_fgAP_CORRECTED_COURSE
538 // compute course to way_point
539 // need to test for iter
540 SGWayPoint wp = globals->get_route()->get_first();
541 wp.CourseAndDistance( lon, lat, alt,
542 &wp_course, &wp_distance );
544 #ifdef DO_fgAP_CORRECTED_COURSE
545 corrected_course = course - wp_course;
546 if( fabs(corrected_course) > 0.1 )
547 printf("fgAP: course %f wp_course %f %f %f\n",
548 course, wp_course, fabs(corrected_course),
550 #endif // DO_fgAP_CORRECTED_COURSE
552 if ( wp_distance > 100 ) {
553 // corrected_course = course - wp_course;
554 TargetHeading = NormalizeDegrees(wp_course);
556 // pop off this waypoint from the list
557 if ( globals->get_route()->size() ) {
558 globals->get_route()->delete_first();
561 // see if there are more waypoints on the list
562 if ( globals->get_route()->size() ) {
564 set_HeadingMode( FG_HEADING_WAYPOINT );
567 heading_mode = FG_TRUE_HEADING_LOCK;
568 // use current heading
569 TargetHeading = heading_node->getDoubleValue();
572 MakeTargetHeadingStr( TargetHeading );
573 // Force this just in case
574 TargetDistance = wp_distance;
575 MakeTargetWPStr( wp_distance );
578 if ( heading_mode == FG_TC_HEADING_LOCK ) {
579 // drive the turn coordinator to zero
580 double turn = FGSteam::get_TC_std();
581 double AileronSet = -turn / 2.0;
582 SG_CLAMP_RANGE( AileronSet, -1.0, 1.0 );
583 globals->get_controls()->set_aileron( AileronSet );
584 globals->get_controls()->set_rudder( AileronSet / 4.0 );
586 // steer towards the target heading
594 = NormalizeDegrees( TargetHeading
595 - heading_node->getDoubleValue() );
596 // figure out how far off we are from desired heading
598 // Now it is time to deterime how far we should be rolled.
599 SG_LOG( SG_AUTOPILOT, SG_DEBUG,
600 "Heading = " << heading_node->getDoubleValue() <<
601 " TargetHeading = " << TargetHeading <<
602 " RelHeading = " << RelHeading );
604 // Check if we are further from heading than the roll out point
605 if ( fabs( RelHeading ) > RollOut ) {
606 // set Target Roll to Max in desired direction
607 if ( RelHeading < 0 ) {
608 TargetRoll = 0 - MaxRoll;
610 TargetRoll = MaxRoll;
613 // We have to calculate the Target roll
615 // This calculation engine thinks that the Target roll
616 // should be a line from (RollOut,MaxRoll) to (-RollOut,
617 // -MaxRoll) I hope this works well. If I get ambitious
618 // some day this might become a fancier curve or
621 TargetRoll = LinearExtrapolate( RelHeading, -RollOut,
626 // Target Roll has now been Found.
628 // Compare Target roll to Current Roll, Generate Rel Roll
630 SG_LOG( SG_COCKPIT, SG_BULK, "TargetRoll: " << TargetRoll );
632 RelRoll = NormalizeDegrees( TargetRoll
633 - roll_node->getDoubleValue() );
635 // Check if we are further from heading than the roll out
637 if ( fabs( RelRoll ) > RollOutSmooth ) {
638 // set Target Roll to Max in desired direction
640 AileronSet = 0 - MaxAileron;
642 AileronSet = MaxAileron;
645 AileronSet = LinearExtrapolate( RelRoll, -RollOutSmooth,
651 globals->get_controls()->set_aileron( AileronSet );
652 globals->get_controls()->set_rudder( AileronSet / 4.0 );
653 // controls.set_rudder( 0.0 );
658 if ( altitude_hold ) {
660 double speed, max_climb, error;
661 double prop_error, int_error;
662 double prop_adj, int_adj, total_adj;
664 if ( altitude_mode == FG_ALTITUDE_LOCK ) {
666 ( TargetAltitude - FGSteam::get_ALT_ft() * SG_FEET_TO_METER ) * 8.0;
667 } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
668 double x = current_radiostack->get_nav1_gs_dist();
669 double y = (altitude_node->getDoubleValue()
670 - current_radiostack->get_nav1_elev()) * SG_FEET_TO_METER;
671 double current_angle = atan2( y, x ) * SGD_RADIANS_TO_DEGREES;
673 double target_angle = current_radiostack->get_nav1_target_gs();
675 double gs_diff = target_angle - current_angle;
677 // convert desired vertical path angle into a climb rate
678 double des_angle = current_angle - 10 * gs_diff;
680 // convert to meter/min
681 double horiz_vel = cur_fdm_state->get_V_ground_speed()
682 * SG_FEET_TO_METER * 60.0;
683 climb_rate = -sin( des_angle * SGD_DEGREES_TO_RADIANS ) * horiz_vel;
684 /* climb_error_accum += gs_diff * 2.0; */
685 /* climb_rate = gs_diff * 200.0 + climb_error_accum; */
686 } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
687 // brain dead ground hugging with no look ahead
689 ( TargetAGL - altitude_agl_node->getDoubleValue()
690 * SG_FEET_TO_METER ) * 16.0;
692 // just try to zero out rate of climb ...
698 if ( speed < min_climb->getFloatValue() ) {
700 } else if ( speed < best_climb->getFloatValue() ) {
701 max_climb = ((best_climb->getFloatValue()
702 - min_climb->getFloatValue())
703 - (best_climb->getFloatValue() - speed))
704 * fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER)
705 / (best_climb->getFloatValue() - min_climb->getFloatValue());
707 max_climb = ( speed - best_climb->getFloatValue() ) * 10.0
708 + fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
711 // this first one could be optional if we wanted to allow
712 // better climb performance assuming we have the airspeed to
715 fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER) ) {
717 = fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
720 if ( climb_rate > max_climb ) {
721 climb_rate = max_climb;
725 -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER) ) {
727 = -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER);
730 error = vertical_speed_node->getDoubleValue() * 60
731 - climb_rate * SG_METER_TO_FEET;
733 // accumulate the error under the curve ... this really should
735 alt_error_accum += error;
737 // calculate integral error, and adjustment amount
738 int_error = alt_error_accum;
739 // printf("error = %.2f int_error = %.2f\n", error, int_error);
740 int_adj = int_error / elevator_adj_factor->getFloatValue();
742 // caclulate proportional error
744 prop_adj = prop_error / elevator_adj_factor->getDoubleValue();
746 total_adj = ((double) 1.0 - (double) integral_contrib->getFloatValue()) * prop_adj
747 + (double) integral_contrib->getFloatValue() * int_adj;
749 // stop on autopilot trim at 30% +/-
750 // if ( total_adj > 0.3 ) {
752 // } else if ( total_adj < -0.3 ) {
756 // adjust for throttle pitch gain
757 total_adj += ((current_throttle->getFloatValue() - zero_pitch_throttle->getFloatValue())
758 / (1 - zero_pitch_throttle->getFloatValue()))
759 * zero_pitch_trim_full_throttle->getFloatValue();
761 globals->get_controls()->set_elevator_trim( total_adj );
765 if ( auto_throttle ) {
767 double prop_error, int_error;
768 double prop_adj, int_adj, total_adj;
770 error = TargetSpeed - get_speed();
772 // accumulate the error under the curve ... this really should
774 speed_error_accum += error;
775 if ( speed_error_accum > 2000.0 ) {
776 speed_error_accum = 2000.0;
778 else if ( speed_error_accum < -2000.0 ) {
779 speed_error_accum = -2000.0;
782 // calculate integral error, and adjustment amount
783 int_error = speed_error_accum;
785 // printf("error = %.2f int_error = %.2f\n", error, int_error);
786 int_adj = int_error / 200.0;
788 // caclulate proportional error
790 prop_adj = 0.5 + prop_error / 50.0;
792 total_adj = 0.9 * prop_adj + 0.1 * int_adj;
793 if ( total_adj > 1.0 ) {
796 else if ( total_adj < 0.0 ) {
800 globals->get_controls()->set_throttle( FGControls::ALL_ENGINES,
804 #ifdef THIS_CODE_IS_NOT_USED
805 if (Mode == 2) // Glide slope hold
810 // First, calculate Relative slope and normalize it
811 RelSlope = NormalizeDegrees( TargetSlope - get_pitch());
813 // Now calculate the elevator offset from current angle
814 if ( abs(RelSlope) > SlopeSmooth )
816 if ( RelSlope < 0 ) // set RelElevator to max in the correct direction
817 RelElevator = -MaxElevator;
819 RelElevator = MaxElevator;
823 RelElevator = LinearExtrapolate(RelSlope,-SlopeSmooth,-MaxElevator,SlopeSmooth,MaxElevator);
826 fgElevMove(RelElevator);
829 #endif // THIS_CODE_IS_NOT_USED
831 // stash this runs control settings
832 // update_old_control_values();
833 old_aileron = globals->get_controls()->get_aileron();
834 old_elevator = globals->get_controls()->get_elevator();
835 old_elevator_trim = globals->get_controls()->get_elevator_trim();
836 old_rudder = globals->get_controls()->get_rudder();
838 // for cross track error
843 SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run( returns )" );
847 void FGAutopilot::set_HeadingMode( fgAutoHeadingMode mode ) {
850 if ( heading_mode == FG_DG_HEADING_LOCK ) {
851 // set heading hold to current heading (as read from DG)
852 // ... no, leave target heading along ... just use the current
854 // DGTargetHeading = FGSteam::get_DG_deg();
855 } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
856 // set autopilot to hold a zero turn (as reported by the TC)
857 } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
858 // set heading hold to current heading
859 TargetHeading = heading_node->getDoubleValue();
860 } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
861 if ( globals->get_route()->size() ) {
862 double course, distance;
864 old_lat = latitude_node->getDoubleValue();
865 old_lon = longitude_node->getDoubleValue();
867 waypoint = globals->get_route()->get_first();
868 waypoint.CourseAndDistance( longitude_node->getDoubleValue(),
869 latitude_node->getDoubleValue(),
870 altitude_node->getDoubleValue()
872 &course, &distance );
873 TargetHeading = course;
874 TargetDistance = distance;
875 MakeTargetLatLonStr( waypoint.get_target_lat(),
876 waypoint.get_target_lon() );
877 MakeTargetWPStr( distance );
879 if ( waypoint.get_target_alt() > 0.0 ) {
880 TargetAltitude = waypoint.get_target_alt();
881 altitude_mode = FG_ALTITUDE_LOCK;
882 set_AltitudeEnabled( true );
883 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
886 SG_LOG( SG_COCKPIT, SG_INFO, " set_HeadingMode: ( "
887 << get_TargetLatitude() << " "
888 << get_TargetLongitude() << " ) "
891 // no more way points, default to heading lock.
892 heading_mode = FG_TC_HEADING_LOCK;
896 MakeTargetHeadingStr( TargetHeading );
897 update_old_control_values();
901 void FGAutopilot::set_AltitudeMode( fgAutoAltitudeMode mode ) {
902 altitude_mode = mode;
904 alt_error_accum = 0.0;
907 if ( altitude_mode == FG_ALTITUDE_LOCK ) {
908 if ( TargetAltitude < altitude_agl_node->getDoubleValue()
909 * SG_FEET_TO_METER ) {
912 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
913 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
915 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
917 } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
918 climb_error_accum = 0.0;
920 } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
921 TargetAGL = altitude_agl_node->getDoubleValue() * SG_FEET_TO_METER;
923 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
924 MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
926 MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
930 update_old_control_values();
931 SG_LOG( SG_COCKPIT, SG_INFO, " set_AltitudeMode():" );
935 void FGAutopilot::AltitudeSet( double new_altitude ) {
936 double target_alt = new_altitude;
938 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
939 target_alt = new_altitude * SG_FEET_TO_METER;
942 if( target_alt < scenery.get_cur_elev() ) {
943 target_alt = scenery.get_cur_elev();
946 TargetAltitude = target_alt;
947 altitude_mode = FG_ALTITUDE_LOCK;
949 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
950 target_alt *= SG_METER_TO_FEET;
952 // ApAltitudeDialogInput->setValue((float)target_alt);
953 MakeTargetAltitudeStr( target_alt );
955 update_old_control_values();
959 void FGAutopilot::AltitudeAdjust( double inc )
961 double target_alt, target_agl;
963 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
964 target_alt = TargetAltitude * SG_METER_TO_FEET;
965 target_agl = TargetAGL * SG_METER_TO_FEET;
967 target_alt = TargetAltitude;
968 target_agl = TargetAGL;
971 if ( fabs((int)(target_alt / inc) * inc - target_alt) < SG_EPSILON ) {
974 target_alt = ( int ) ( target_alt / inc ) * inc + inc;
977 if ( fabs((int)(target_agl / inc) * inc - target_agl) < SG_EPSILON ) {
980 target_agl = ( int ) ( target_agl / inc ) * inc + inc;
983 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
984 target_alt *= SG_FEET_TO_METER;
985 target_agl *= SG_FEET_TO_METER;
988 TargetAltitude = target_alt;
989 TargetAGL = target_agl;
991 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
992 target_alt *= SG_METER_TO_FEET;
993 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
994 target_agl *= SG_METER_TO_FEET;
996 if ( altitude_mode == FG_ALTITUDE_LOCK ) {
997 MakeTargetAltitudeStr( target_alt );
998 } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
999 MakeTargetAltitudeStr( target_agl );
1002 update_old_control_values();
1006 void FGAutopilot::HeadingAdjust( double inc ) {
1007 if ( heading_mode != FG_DG_HEADING_LOCK
1008 && heading_mode != FG_TRUE_HEADING_LOCK )
1010 heading_mode = FG_DG_HEADING_LOCK;
1013 if ( heading_mode == FG_DG_HEADING_LOCK ) {
1014 double target = ( int ) ( DGTargetHeading / inc ) * inc + inc;
1015 DGTargetHeading = NormalizeDegrees( target );
1017 double target = ( int ) ( TargetHeading / inc ) * inc + inc;
1018 TargetHeading = NormalizeDegrees( target );
1021 update_old_control_values();
1025 void FGAutopilot::HeadingSet( double new_heading ) {
1026 if( heading_mode == FG_TRUE_HEADING_LOCK ) {
1027 new_heading = NormalizeDegrees( new_heading );
1028 TargetHeading = new_heading;
1029 MakeTargetHeadingStr( TargetHeading );
1031 heading_mode = FG_DG_HEADING_LOCK;
1033 new_heading = NormalizeDegrees( new_heading );
1034 DGTargetHeading = new_heading;
1035 // following cast needed ambiguous plib
1036 // ApHeadingDialogInput -> setValue ((float)APData->TargetHeading );
1037 MakeTargetHeadingStr( DGTargetHeading );
1039 update_old_control_values();
1042 void FGAutopilot::AutoThrottleAdjust( double inc ) {
1043 double target = ( int ) ( TargetSpeed / inc ) * inc + inc;
1045 TargetSpeed = target;
1049 void FGAutopilot::set_AutoThrottleEnabled( bool value ) {
1050 auto_throttle = value;
1052 if ( auto_throttle == true ) {
1053 TargetSpeed = fgGetDouble("/velocities/airspeed-kt");
1054 speed_error_accum = 0.0;
1057 update_old_control_values();
1058 SG_LOG( SG_COCKPIT, SG_INFO, " fgAPSetAutoThrottle: ("
1059 << auto_throttle << ") " << TargetSpeed );
1065 ////////////////////////////////////////////////////////////////////////
1066 // Kludged methods for tying to properties.
1068 // These should change eventually; they all used to be static
1070 ////////////////////////////////////////////////////////////////////////
1073 * Get the autopilot altitude lock (true=on).
1076 FGAutopilot::getAPAltitudeLock () const
1078 return (get_AltitudeEnabled() &&
1080 == FGAutopilot::FG_ALTITUDE_LOCK);
1085 * Set the autopilot altitude lock (true=on).
1088 FGAutopilot::setAPAltitudeLock (bool lock)
1091 set_AltitudeMode(FGAutopilot::FG_ALTITUDE_LOCK);
1092 if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_LOCK)
1093 set_AltitudeEnabled(lock);
1098 * Get the autopilot target altitude in feet.
1101 FGAutopilot::getAPAltitude () const
1103 return get_TargetAltitude() * SG_METER_TO_FEET;
1108 * Set the autopilot target altitude in feet.
1111 FGAutopilot::setAPAltitude (double altitude)
1113 set_TargetAltitude( altitude * SG_FEET_TO_METER );
1117 * Get the autopilot altitude lock (true=on).
1120 FGAutopilot::getAPGSLock () const
1122 return (get_AltitudeEnabled() &&
1124 == FGAutopilot::FG_ALTITUDE_GS1));
1129 * Set the autopilot altitude lock (true=on).
1132 FGAutopilot::setAPGSLock (bool lock)
1135 set_AltitudeMode(FGAutopilot::FG_ALTITUDE_GS1);
1136 if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_GS1)
1137 set_AltitudeEnabled(lock);
1142 * Get the autopilot terrain lock (true=on).
1145 FGAutopilot::getAPTerrainLock () const
1147 return (get_AltitudeEnabled() &&
1149 == FGAutopilot::FG_ALTITUDE_TERRAIN));
1154 * Set the autopilot terrain lock (true=on).
1157 FGAutopilot::setAPTerrainLock (bool lock)
1160 set_AltitudeMode(FGAutopilot::FG_ALTITUDE_TERRAIN);
1161 set_TargetAGL(fgGetFloat("/position/altitude-agl-ft") *
1164 if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_TERRAIN)
1165 set_AltitudeEnabled(lock);
1170 * Get the autopilot target altitude in feet.
1173 FGAutopilot::getAPClimb () const
1175 return get_TargetClimbRate() * SG_METER_TO_FEET;
1180 * Set the autopilot target altitude in feet.
1183 FGAutopilot::setAPClimb (double rate)
1185 set_TargetClimbRate( rate * SG_FEET_TO_METER );
1190 * Get the autopilot heading lock (true=on).
1193 FGAutopilot::getAPHeadingLock () const
1196 (get_HeadingEnabled() &&
1197 get_HeadingMode() == DEFAULT_AP_HEADING_LOCK);
1202 * Set the autopilot heading lock (true=on).
1205 FGAutopilot::setAPHeadingLock (bool lock)
1208 set_HeadingMode(DEFAULT_AP_HEADING_LOCK);
1209 if (get_HeadingMode() == DEFAULT_AP_HEADING_LOCK)
1210 set_HeadingEnabled(lock);
1215 * Get the autopilot heading bug in degrees.
1218 FGAutopilot::getAPHeadingBug () const
1220 return get_DGTargetHeading();
1225 * Set the autopilot heading bug in degrees.
1228 FGAutopilot::setAPHeadingBug (double heading)
1230 set_DGTargetHeading( heading );
1235 * Get the autopilot wing leveler lock (true=on).
1238 FGAutopilot::getAPWingLeveler () const
1241 (get_HeadingEnabled() &&
1242 get_HeadingMode() == FGAutopilot::FG_TC_HEADING_LOCK);
1247 * Set the autopilot wing leveler lock (true=on).
1250 FGAutopilot::setAPWingLeveler (bool lock)
1253 set_HeadingMode(FGAutopilot::FG_TC_HEADING_LOCK);
1254 if (get_HeadingMode() == FGAutopilot::FG_TC_HEADING_LOCK)
1255 set_HeadingEnabled(lock);
1259 * Return true if the autopilot is locked to NAV1.
1262 FGAutopilot::getAPNAV1Lock () const
1265 (get_HeadingEnabled() &&
1266 get_HeadingMode() == FGAutopilot::FG_HEADING_NAV1);
1271 * Set the autopilot NAV1 lock.
1274 FGAutopilot::setAPNAV1Lock (bool lock)
1277 set_HeadingMode(FGAutopilot::FG_HEADING_NAV1);
1278 if (get_HeadingMode() == FGAutopilot::FG_HEADING_NAV1)
1279 set_HeadingEnabled(lock);
1283 * Get the autopilot autothrottle lock.
1286 FGAutopilot::getAPAutoThrottleLock () const
1288 return get_AutoThrottleEnabled();
1293 * Set the autothrottle lock.
1296 FGAutopilot::setAPAutoThrottleLock (bool lock)
1298 set_AutoThrottleEnabled(lock);
1304 FGAutopilot::getAPRudderControl () const
1306 if (getAPHeadingLock())
1307 return get_TargetHeading();
1309 return globals->get_controls()->get_rudder();
1314 FGAutopilot::setAPRudderControl (double value)
1316 if (getAPHeadingLock()) {
1317 SG_LOG(SG_GENERAL, SG_DEBUG, "setAPRudderControl " << value );
1318 value -= get_TargetHeading();
1319 HeadingAdjust(value < 0.0 ? -1.0 : 1.0);
1321 globals->get_controls()->set_rudder(value);
1327 FGAutopilot::getAPElevatorControl () const
1329 if (getAPAltitudeLock())
1330 return get_TargetAltitude();
1332 return globals->get_controls()->get_elevator();
1337 FGAutopilot::setAPElevatorControl (double value)
1339 if (value != 0 && getAPAltitudeLock()) {
1340 SG_LOG(SG_GENERAL, SG_DEBUG, "setAPElevatorControl " << value );
1341 value -= get_TargetAltitude();
1342 AltitudeAdjust(value < 0.0 ? 100.0 : -100.0);
1344 globals->get_controls()->set_elevator(value);
1350 FGAutopilot::getAPThrottleControl () const
1352 if (getAPAutoThrottleLock())
1353 return 0.0; // always resets
1355 return globals->get_controls()->get_throttle(0);
1360 FGAutopilot::setAPThrottleControl (double value)
1362 if (getAPAutoThrottleLock())
1363 AutoThrottleAdjust(value < 0.0 ? -0.01 : 0.01);
1365 globals->get_controls()->set_throttle(FGControls::ALL_ENGINES, value);
1368 // end of newauto.cxx