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>
8 // Wendell Turner <wendell@adsi-m4.com>
10 // This program is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU General Public License as
12 // published by the Free Software Foundation; either version 2 of the
13 // License, or (at your option) any later version.
15 // This program is distributed in the hope that it will be useful, but
16 // WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // General Public License for more details.
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software
22 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
31 #include <stdio.h> // sprintf()
32 #include <string.h> // strcmp()
34 #include <simgear/constants.h>
35 #include <simgear/sg_inlines.h>
36 #include <simgear/debug/logstream.hxx>
37 #include <simgear/math/sg_geodesy.hxx>
38 #include <simgear/math/sg_random.h>
39 #include <simgear/route/route.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"
48 #include "auto_gui.hxx"
51 /// These statics will eventually go into the class
52 /// they are just here while I am experimenting -- NHV :-)
53 // AutoPilot Gain Adjuster members
54 static double MaxRollAdjust; // MaxRollAdjust = 2 * APData->MaxRoll;
55 static double RollOutAdjust; // RollOutAdjust = 2 * APData->RollOut;
56 static double MaxAileronAdjust; // MaxAileronAdjust = 2 * APData->MaxAileron;
57 static double RollOutSmoothAdjust; // RollOutSmoothAdjust = 2 * APData->RollOutSmooth;
59 static char NewTgtAirportId[16];
60 // static char NewTgtAirportLabel[] = "Enter New TgtAirport ID";
62 extern char *coord_format_lat(float);
63 extern char *coord_format_lon(float);
67 FGAutopilot::FGAutopilot()
72 FGAutopilot::~FGAutopilot() {}
75 void FGAutopilot::MakeTargetLatLonStr( double lat, double lon ) {
76 sprintf( TargetLatitudeStr , "%s", coord_format_lat(get_TargetLatitude()));
77 sprintf( TargetLongitudeStr, "%s", coord_format_lon(get_TargetLongitude()));
78 sprintf( TargetLatLonStr, "%s %s", TargetLatitudeStr, TargetLongitudeStr );
82 void FGAutopilot::MakeTargetAltitudeStr( double altitude ) {
83 if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
84 sprintf( TargetAltitudeStr, "APAltitude %6.0f+", altitude );
86 sprintf( TargetAltitudeStr, "APAltitude %6.0f", altitude );
91 void FGAutopilot::MakeTargetHeadingStr( double bearing ) {
94 } else if (bearing > 360. ) {
97 sprintf( TargetHeadingStr, "APHeading %6.1f", bearing );
101 static inline double get_speed( void ) {
102 return( cur_fdm_state->get_V_equiv_kts() );
105 static inline double get_ground_speed() {
106 // starts in ft/s so we convert to kts
107 static const SGPropertyNode * speedup_node = fgGetNode("/sim/speed-up");
109 double ft_s = cur_fdm_state->get_V_ground_speed()
110 * speedup_node->getIntValue();
111 double kts = ft_s * SG_FEET_TO_METER * 3600 * SG_METER_TO_NM;
117 void FGAutopilot::MakeTargetWPStr( double distance ) {
118 static time_t last_time = 0;
119 time_t current_time = time(NULL);
120 if ( last_time == current_time ) {
124 last_time = current_time;
128 int size = globals->get_route()->size();
130 // start by wiping the strings
137 SGWayPoint wp1 = globals->get_route()->get_waypoint( 0 );
139 double eta = accum * SG_METER_TO_NM / get_ground_speed();
140 if ( eta >= 100.0 ) { eta = 99.999; }
142 if ( eta < (1.0/6.0) ) {
143 // within 10 minutes, bump up to min/secs
147 minor = (int)((eta - (int)eta) * 60.0);
148 sprintf( TargetWP1Str, "%s %.2f NM ETA %d:%02d",
149 wp1.get_id().c_str(),
150 accum*SG_METER_TO_NM, major, minor );
155 SGWayPoint wp2 = globals->get_route()->get_waypoint( 1 );
156 accum += wp2.get_distance();
158 double eta = accum * SG_METER_TO_NM / get_ground_speed();
159 if ( eta >= 100.0 ) { eta = 99.999; }
161 if ( eta < (1.0/6.0) ) {
162 // within 10 minutes, bump up to min/secs
166 minor = (int)((eta - (int)eta) * 60.0);
167 sprintf( TargetWP2Str, "%s %.2f NM ETA %d:%02d",
168 wp2.get_id().c_str(),
169 accum*SG_METER_TO_NM, major, minor );
174 for ( int i = 2; i < size; ++i ) {
175 accum += globals->get_route()->get_waypoint( i ).get_distance();
178 SGWayPoint wpn = globals->get_route()->get_waypoint( size - 1 );
180 double eta = accum * SG_METER_TO_NM / get_ground_speed();
181 if ( eta >= 100.0 ) { eta = 99.999; }
183 if ( eta < (1.0/6.0) ) {
184 // within 10 minutes, bump up to min/secs
188 minor = (int)((eta - (int)eta) * 60.0);
189 sprintf( TargetWP3Str, "%s %.2f NM ETA %d:%02d",
190 wpn.get_id().c_str(),
191 accum*SG_METER_TO_NM, major, minor );
196 void FGAutopilot::update_old_control_values() {
197 old_aileron = globals->get_controls()->get_aileron();
198 old_elevator = globals->get_controls()->get_elevator();
199 old_elevator_trim = globals->get_controls()->get_elevator_trim();
200 old_rudder = globals->get_controls()->get_rudder();
204 // Initialize autopilot subsystem
206 void FGAutopilot::init ()
208 SG_LOG( SG_AUTOPILOT, SG_INFO, "Init AutoPilot Subsystem" );
210 // bind data input property nodes...
211 latitude_node = fgGetNode("/position/latitude-deg", true);
212 longitude_node = fgGetNode("/position/longitude-deg", true);
213 altitude_node = fgGetNode("/position/altitude-ft", true);
214 altitude_agl_node = fgGetNode("/position/altitude-agl-ft", true);
215 vertical_speed_node = fgGetNode("/velocities/vertical-speed-fps", true);
216 heading_node = fgGetNode("/orientation/heading-deg", true);
218 = fgGetNode("/instrumentation/heading-indicator/indicated-heading-deg",
220 roll_node = fgGetNode("/orientation/roll-deg", true);
221 pitch_node = fgGetNode("/orientation/pitch-deg", true);
225 // bind config property nodes...
227 = fgGetNode("/autopilot/config/target-climb-rate-fpm", true);
229 = fgGetNode("/autopilot/config/target-descent-rate-fpm", true);
230 min_climb = fgGetNode("/autopilot/config/min-climb-speed-kt", true);
231 best_climb = fgGetNode("/autopilot/config/best-climb-speed-kt", true);
233 = fgGetNode("/autopilot/config/elevator-adj-factor", true);
235 = fgGetNode("/autopilot/config/integral-contribution", true);
237 = fgGetNode("/autopilot/config/zero-pitch-throttle", true);
238 zero_pitch_trim_full_throttle
239 = fgGetNode("/autopilot/config/zero-pitch-trim-full-throttle", true);
240 max_aileron_node = fgGetNode("/autopilot/config/max-aileron", true);
241 max_roll_node = fgGetNode("/autopilot/config/max-roll-deg", true);
242 roll_out_node = fgGetNode("/autopilot/config/roll-out-deg", true);
243 roll_out_smooth_node = fgGetNode("/autopilot/config/roll-out-smooth-deg", true);
245 current_throttle = fgGetNode("/controls/engines/engine/throttle");
247 // initialize config properties with defaults (in case config isn't there)
248 if ( TargetClimbRate->getFloatValue() < 1 )
249 fgSetFloat( "/autopilot/config/target-climb-rate-fpm", 500);
250 if ( TargetDescentRate->getFloatValue() < 1 )
251 fgSetFloat( "/autopilot/config/target-descent-rate-fpm", 1000 );
252 if ( min_climb->getFloatValue() < 1)
253 fgSetFloat( "/autopilot/config/min-climb-speed-kt", 70 );
254 if (best_climb->getFloatValue() < 1)
255 fgSetFloat( "/autopilot/config/best-climb-speed-kt", 120 );
256 if (elevator_adj_factor->getFloatValue() < 1)
257 fgSetFloat( "/autopilot/config/elevator-adj-factor", 5000 );
258 if ( integral_contrib->getFloatValue() < 0.0000001 )
259 fgSetFloat( "/autopilot/config/integral-contribution", 0.01 );
260 if ( zero_pitch_throttle->getFloatValue() < 0.0000001 )
261 fgSetFloat( "/autopilot/config/zero-pitch-throttle", 0.60 );
262 if ( zero_pitch_trim_full_throttle->getFloatValue() < 0.0000001 )
263 fgSetFloat( "/autopilot/config/zero-pitch-trim-full-throttle", 0.15 );
264 if ( max_aileron_node->getFloatValue() < 0.0000001 )
265 fgSetFloat( "/autopilot/config/max-aileron", 0.2 );
266 if ( max_roll_node->getFloatValue() < 0.0000001 )
267 fgSetFloat( "/autopilot/config/max-roll-deg", 20 );
268 if ( roll_out_node->getFloatValue() < 0.0000001 )
269 fgSetFloat( "/autopilot/config/roll-out-deg", 20 );
270 if ( roll_out_smooth_node->getFloatValue() < 0.0000001 )
271 fgSetFloat( "/autopilot/config/roll-out-smooth-deg", 10 );
274 heading_hold = false ; // turn the heading hold off
275 altitude_hold = false ; // turn the altitude hold off
276 auto_throttle = false ; // turn the auto throttle off
277 heading_mode = DEFAULT_AP_HEADING_LOCK;
278 altitude_mode = DEFAULT_AP_ALTITUDE_LOCK;
280 DGTargetHeading = fgGetDouble("/autopilot/settings/heading-bug-deg");
281 TargetHeading = fgGetDouble("/autopilot/settings/heading-bug-deg");
282 TargetAltitude = fgGetDouble("/autopilot/settings/altitude-ft") * SG_FEET_TO_METER;
284 // Initialize target location to startup location
285 old_lat = latitude_node->getDoubleValue();
286 old_lon = longitude_node->getDoubleValue();
287 // set_WayPoint( old_lon, old_lat, 0.0, "default" );
289 MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
291 alt_error_accum = 0.0;
292 climb_error_accum = 0.0;
294 MakeTargetAltitudeStr( TargetAltitude );
295 MakeTargetHeadingStr( TargetHeading );
297 // These eventually need to be read from current_aircaft somehow.
299 // the maximum roll, in Deg
302 // the deg from heading to start rolling out at, in Deg
305 // Smoothing distance for alerion control
308 // Hardwired for now should be in options
309 // 25% max control variablilty 0.5 / 2.0
310 disengage_threshold = 1.0;
312 // set default aileron max deflection
315 #if !defined( USING_SLIDER_CLASS )
316 MaxRollAdjust = 2 * MaxRoll;
317 RollOutAdjust = 2 * RollOut;
318 //MaxAileronAdjust = 2 * MaxAileron;
319 RollOutSmoothAdjust = 2 * RollOutSmooth;
320 #endif // !defined( USING_SLIDER_CLASS )
322 update_old_control_values();
328 // Autopilot control property get/set bindings
329 fgTie("/autopilot/locks/altitude", this,
330 &FGAutopilot::getAPAltitudeLock, &FGAutopilot::setAPAltitudeLock);
331 fgSetArchivable("/autopilot/locks/altitude");
332 fgTie("/autopilot/settings/altitude-ft", this,
333 &FGAutopilot::getAPAltitude, &FGAutopilot::setAPAltitude);
334 fgSetArchivable("/autopilot/settings/altitude-ft");
335 fgTie("/autopilot/locks/glide-slope", this,
336 &FGAutopilot::getAPGSLock, &FGAutopilot::setAPGSLock);
337 fgSetArchivable("/autopilot/locks/glide-slope");
338 fgSetDouble("/autopilot/settings/altitude-ft", 3000.0f);
339 fgTie("/autopilot/locks/terrain", this,
340 &FGAutopilot::getAPTerrainLock, &FGAutopilot::setAPTerrainLock);
341 fgSetArchivable("/autopilot/locks/terrain");
342 fgTie("/autopilot/settings/climb-rate-fpm", this,
343 &FGAutopilot::getAPClimb, &FGAutopilot::setAPClimb, false);
344 fgSetArchivable("/autopilot/settings/climb-rate-fpm");
345 fgTie("/autopilot/locks/heading", this,
346 &FGAutopilot::getAPHeadingLock, &FGAutopilot::setAPHeadingLock);
347 fgSetArchivable("/autopilot/locks/heading");
349 fgTie("/autopilot/settings/heading-bug-deg", this,
350 &FGAutopilot::getAPHeadingBug, &FGAutopilot::setAPHeadingBug);
351 fgSetArchivable("/autopilot/settings/heading-bug-deg");
352 fgSetDouble("/autopilot/settings/heading-bug-deg", 0.0f);
354 fgTie("/autopilot/settings/waypoint", this,
355 &FGAutopilot::getAPwaypoint, &FGAutopilot::setAPwaypoint);
356 fgSetArchivable("/autopilot/settings/waypoint");
357 fgSetString("/autopilot/settings/waypoint", "");
359 fgTie("/autopilot/locks/wing-leveler", this,
360 &FGAutopilot::getAPWingLeveler, &FGAutopilot::setAPWingLeveler);
361 fgSetArchivable("/autopilot/locks/wing-leveler");
362 fgTie("/autopilot/locks/nav[0]", this,
363 &FGAutopilot::getAPNAV1Lock, &FGAutopilot::setAPNAV1Lock);
364 fgSetArchivable("/autopilot/locks/nav[0]");
365 fgTie("/autopilot/locks/auto-throttle", this,
366 &FGAutopilot::getAPAutoThrottleLock,
367 &FGAutopilot::setAPAutoThrottleLock);
368 fgSetArchivable("/autopilot/locks/auto-throttle");
369 fgTie("/autopilot/control-overrides/rudder", this,
370 &FGAutopilot::getAPRudderControl,
371 &FGAutopilot::setAPRudderControl);
372 fgSetArchivable("/autopilot/control-overrides/rudder");
373 fgTie("/autopilot/control-overrides/elevator", this,
374 &FGAutopilot::getAPElevatorControl,
375 &FGAutopilot::setAPElevatorControl);
376 fgSetArchivable("/autopilot/control-overrides/elevator");
377 fgTie("/autopilot/control-overrides/throttle", this,
378 &FGAutopilot::getAPThrottleControl,
379 &FGAutopilot::setAPThrottleControl);
380 fgSetArchivable("/autopilot/control-overrides/throttle");
384 FGAutopilot::unbind ()
388 // Reset the autopilot system
389 void FGAutopilot::reset() {
391 heading_hold = false ; // turn the heading hold off
392 altitude_hold = false ; // turn the altitude hold off
393 auto_throttle = false ; // turn the auto throttle off
394 heading_mode = DEFAULT_AP_HEADING_LOCK;
396 // TargetHeading = 0.0; // default direction, due north
397 MakeTargetHeadingStr( TargetHeading );
399 // TargetAltitude = 3000; // default altitude in meters
400 MakeTargetAltitudeStr( TargetAltitude );
402 alt_error_accum = 0.0;
403 climb_error_accum = 0.0;
405 update_old_control_values();
407 sprintf( NewTgtAirportId, "%s", fgGetString("/sim/presets/airport-id") );
409 MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
413 static double NormalizeDegrees( double Input ) {
414 // normalize the input to the range (-180,180]
415 // Input should not be greater than -360 to 360.
416 // Current rules send the output to an undefined state.
417 while ( Input > 180.0 ) { Input -= 360.0; }
418 while ( Input <= -180.0 ) { Input += 360.0; }
423 static double LinearExtrapolate( double x, double x1, double y1, double x2, double y2 ) {
424 // This procedure extrapolates the y value for the x posistion on a line defined by x1,y1; x2,y2
425 //assert(x1 != x2); // Divide by zero error. Cold abort for now
428 // static double y = 0.0;
429 // double dx = x2 -x1;
430 // if( (dx < -SG_EPSILON ) || ( dx > SG_EPSILON ) )
433 double m, b, y; // the constants to find in y=mx+b
436 m = ( y2 - y1 ) / ( x2 - x1 ); // calculate the m
438 b = y1 - m * x1; // calculate the b
440 y = m * x + b; // the final calculation
450 FGAutopilot::update (double dt)
452 // Remove the following lines when the calling funcitons start
453 // passing in the data pointer
455 // get control settings
457 double lat = latitude_node->getDoubleValue();
458 double lon = longitude_node->getDoubleValue();
459 double alt = altitude_node->getDoubleValue() * SG_FEET_TO_METER;
461 // get config settings
462 MaxAileron = max_aileron_node->getDoubleValue();
463 MaxRoll = max_roll_node->getDoubleValue();
464 RollOut = roll_out_node->getDoubleValue();
465 RollOutSmooth = roll_out_smooth_node->getDoubleValue();
467 SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run() lat = " << lat <<
468 " lon = " << lon << " alt = " << alt );
470 #ifdef FG_FORCE_AUTO_DISENGAGE
471 // see if somebody else has changed them
472 if( fabs(aileron - old_aileron) > disengage_threshold ||
473 fabs(elevator - old_elevator) > disengage_threshold ||
474 fabs(elevator_trim - old_elevator_trim) >
475 disengage_threshold ||
476 fabs(rudder - old_rudder) > disengage_threshold )
478 // if controls changed externally turn autopilot off
479 waypoint_hold = false ; // turn the target hold off
480 heading_hold = false ; // turn the heading hold off
481 altitude_hold = false ; // turn the altitude hold off
482 terrain_follow = false; // turn the terrain_follow hold off
483 // auto_throttle = false; // turn the auto_throttle off
485 // stash this runs control settings
486 old_aileron = aileron;
487 old_elevator = elevator;
488 old_elevator_trim = elevator_trim;
496 if ( heading_hold == true ) {
497 if ( heading_mode == FG_DG_HEADING_LOCK ) {
498 double dg_error = heading_node->getDoubleValue()
499 - dg_heading_node->getDoubleValue();
500 TargetHeading = DGTargetHeading + dg_error;
501 // cout << "dg_error = " << dg_error << endl;
502 while ( TargetHeading < 0.0 ) { TargetHeading += 360.0; }
503 while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
504 MakeTargetHeadingStr( TargetHeading );
505 } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
506 // we don't set a specific target heading in
507 // TC_HEADING_LOCK mode, we instead try to keep the turn
508 // coordinator zero'd
509 } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
510 // leave "true" target heading as is
511 while ( TargetHeading < 0.0 ) { TargetHeading += 360.0; }
512 while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
513 MakeTargetHeadingStr( TargetHeading );
514 } else if ( heading_mode == FG_HEADING_NAV1 ) {
515 // track the NAV1 heading needle deflection
517 // determine our current radial position relative to the
518 // navaid in "true" heading.
519 double cur_radial = current_radiostack->get_navcom1()->get_nav_heading();
520 if ( current_radiostack->get_navcom1()->get_nav_loc() ) {
521 // ILS localizers radials are already "true" in our
524 cur_radial += current_radiostack->get_navcom1()->get_nav_magvar();
526 if ( current_radiostack->get_navcom1()->get_nav_from_flag() ) {
528 while ( cur_radial >= 360.0 ) { cur_radial -= 360.0; }
531 // determine the target radial in "true" heading
532 double tgt_radial = current_radiostack->get_navcom1()->get_nav_radial();
533 if ( current_radiostack->get_navcom1()->get_nav_loc() ) {
534 // ILS localizers radials are already "true" in our
537 // VOR radials need to have that vor's offset added in
538 tgt_radial += current_radiostack->get_navcom1()->get_nav_magvar();
541 // determine the heading adjustment needed.
543 current_radiostack->get_navcom1()->get_nav_heading_needle_deflection()
544 * (current_radiostack->get_navcom1()->get_nav_loc_dist() * SG_METER_TO_NM);
545 SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
547 // clamp closer when inside cone when beyond 5km...
548 if (current_radiostack->get_navcom1()->get_nav_loc_dist() > 5000) {
549 double clamp_angle = fabs(current_radiostack->get_navcom1()->get_nav_heading_needle_deflection()) * 3;
550 if (clamp_angle < 30)
551 SG_CLAMP_RANGE( adjustment, -clamp_angle, clamp_angle);
554 // determine the target heading to fly to intercept the
556 TargetHeading = tgt_radial + adjustment;
557 while ( TargetHeading < 0.0 ) { TargetHeading += 360.0; }
558 while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
560 MakeTargetHeadingStr( TargetHeading );
561 } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
562 // update target heading to waypoint
564 double wp_course, wp_distance;
566 #ifdef DO_fgAP_CORRECTED_COURSE
567 // compute course made good
568 // this needs lots of special casing before use
569 double course, reverse, distance, corrected_course;
570 // need to test for iter
571 geo_inverse_wgs_84( 0, //fgAPget_altitude(),
579 #endif // DO_fgAP_CORRECTED_COURSE
581 // compute course to way_point
582 // need to test for iter
583 SGWayPoint wp = globals->get_route()->get_first();
584 wp.CourseAndDistance( lon, lat, alt,
585 &wp_course, &wp_distance );
587 #ifdef DO_fgAP_CORRECTED_COURSE
588 corrected_course = course - wp_course;
589 if( fabs(corrected_course) > 0.1 )
590 printf("fgAP: course %f wp_course %f %f %f\n",
591 course, wp_course, fabs(corrected_course),
593 #endif // DO_fgAP_CORRECTED_COURSE
595 if ( wp_distance > 100 ) {
596 // corrected_course = course - wp_course;
597 TargetHeading = NormalizeDegrees(wp_course);
599 // pop off this waypoint from the list
600 if ( globals->get_route()->size() ) {
601 globals->get_route()->delete_first();
604 // see if there are more waypoints on the list
605 if ( globals->get_route()->size() ) {
607 set_HeadingMode( FG_HEADING_WAYPOINT );
610 heading_mode = DEFAULT_AP_HEADING_LOCK;
611 // use current heading
612 TargetHeading = heading_node->getDoubleValue();
615 MakeTargetHeadingStr( TargetHeading );
616 // Force this just in case
617 TargetDistance = wp_distance;
618 MakeTargetWPStr( wp_distance );
621 if ( heading_mode == FG_TC_HEADING_LOCK ) {
622 // drive the turn coordinator to zero
624 fgGetDouble("/instrumentation/turn-indicator/indicated-turn-rate");
625 double AileronSet = -turn / 2.0;
626 SG_CLAMP_RANGE( AileronSet, -1.0, 1.0 );
627 globals->get_controls()->set_aileron( AileronSet );
628 globals->get_controls()->set_rudder( AileronSet / 4.0 );
630 // steer towards the target heading
638 = NormalizeDegrees( TargetHeading
639 - heading_node->getDoubleValue() );
640 // figure out how far off we are from desired heading
642 // Now it is time to deterime how far we should be rolled.
643 SG_LOG( SG_AUTOPILOT, SG_DEBUG,
644 "Heading = " << heading_node->getDoubleValue() <<
645 " TargetHeading = " << TargetHeading <<
646 " RelHeading = " << RelHeading );
648 // Check if we are further from heading than the roll out point
649 if ( fabs( RelHeading ) > RollOut ) {
650 // set Target Roll to Max in desired direction
651 if ( RelHeading < 0 ) {
652 TargetRoll = 0 - MaxRoll;
654 TargetRoll = MaxRoll;
657 // We have to calculate the Target roll
659 // This calculation engine thinks that the Target roll
660 // should be a line from (RollOut,MaxRoll) to (-RollOut,
661 // -MaxRoll) I hope this works well. If I get ambitious
662 // some day this might become a fancier curve or
665 TargetRoll = LinearExtrapolate( RelHeading, -RollOut,
670 // Target Roll has now been Found.
672 // Compare Target roll to Current Roll, Generate Rel Roll
674 SG_LOG( SG_COCKPIT, SG_BULK, "TargetRoll: " << TargetRoll );
676 RelRoll = NormalizeDegrees( TargetRoll
677 - roll_node->getDoubleValue() );
679 // Check if we are further from heading than the roll out
681 if ( fabs( RelRoll ) > RollOutSmooth ) {
682 // set Target Roll to Max in desired direction
684 AileronSet = 0 - MaxAileron;
686 AileronSet = MaxAileron;
689 AileronSet = LinearExtrapolate( RelRoll, -RollOutSmooth,
695 globals->get_controls()->set_aileron( AileronSet );
696 globals->get_controls()->set_rudder( AileronSet / 4.0 );
697 // controls.set_rudder( 0.0 );
702 if ( altitude_hold ) {
704 double speed, max_climb, error;
705 double prop_error, int_error;
706 double prop_adj, int_adj, total_adj;
708 if ( altitude_mode == FG_ALTITUDE_LOCK ) {
711 fgGetDouble("/instrumentation/altimeter/indicated-altitude-ft") * SG_FEET_TO_METER ) * 8.0;
712 } else if ( altitude_mode == FG_TRUE_ALTITUDE_LOCK ) {
713 climb_rate = ( TargetAltitude - alt ) * 8.0;
714 } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
715 double x = current_radiostack->get_navcom1()->get_nav_gs_dist();
716 double y = (altitude_node->getDoubleValue()
717 - current_radiostack->get_navcom1()->get_nav_elev()) * SG_FEET_TO_METER;
718 double current_angle = atan2( y, x ) * SGD_RADIANS_TO_DEGREES;
720 double target_angle = current_radiostack->get_navcom1()->get_nav_target_gs();
722 double gs_diff = target_angle - current_angle;
724 // convert desired vertical path angle into a climb rate
725 double des_angle = current_angle - 10 * gs_diff;
727 // convert to meter/min
728 double horiz_vel = cur_fdm_state->get_V_ground_speed()
729 * SG_FEET_TO_METER * 60.0;
730 climb_rate = -sin( des_angle * SGD_DEGREES_TO_RADIANS ) * horiz_vel;
731 /* climb_error_accum += gs_diff * 2.0; */
732 /* climb_rate = gs_diff * 200.0 + climb_error_accum; */
733 } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
734 // brain dead ground hugging with no look ahead
736 ( TargetAGL - altitude_agl_node->getDoubleValue()
737 * SG_FEET_TO_METER ) * 16.0;
739 // just try to zero out rate of climb ...
745 if ( speed < min_climb->getFloatValue() ) {
747 } else if ( speed < best_climb->getFloatValue() ) {
748 max_climb = ((best_climb->getFloatValue()
749 - min_climb->getFloatValue())
750 - (best_climb->getFloatValue() - speed))
751 * fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER)
752 / (best_climb->getFloatValue() - min_climb->getFloatValue());
754 max_climb = ( speed - best_climb->getFloatValue() ) * 10.0
755 + fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
758 // this first one could be optional if we wanted to allow
759 // better climb performance assuming we have the airspeed to
762 fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER) ) {
764 = fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
767 if ( climb_rate > max_climb ) {
768 climb_rate = max_climb;
772 -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER) ) {
774 = -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER);
777 error = vertical_speed_node->getDoubleValue() * 60
778 - climb_rate * SG_METER_TO_FEET;
780 // accumulate the error under the curve ... this really should
782 alt_error_accum += error;
784 // calculate integral error, and adjustment amount
785 int_error = alt_error_accum;
786 // printf("error = %.2f int_error = %.2f\n", error, int_error);
788 // scale elev_adj_factor by speed of aircraft in relation to min climb
789 double elev_adj_factor = elevator_adj_factor->getFloatValue();
791 pow(float(speed / min_climb->getFloatValue()), 3.0f);
793 int_adj = int_error / elev_adj_factor;
795 // caclulate proportional error
797 prop_adj = prop_error / elev_adj_factor;
799 total_adj = ((double) 1.0 - (double) integral_contrib->getFloatValue()) * prop_adj
800 + (double) integral_contrib->getFloatValue() * int_adj;
802 // stop on autopilot trim at 30% +/-
803 // if ( total_adj > 0.3 ) {
805 // } else if ( total_adj < -0.3 ) {
809 // adjust for throttle pitch gain
810 total_adj += ((current_throttle->getFloatValue() - zero_pitch_throttle->getFloatValue())
811 / (1 - zero_pitch_throttle->getFloatValue()))
812 * zero_pitch_trim_full_throttle->getFloatValue();
814 globals->get_controls()->set_elevator_trim( total_adj );
818 if ( auto_throttle ) {
820 double prop_error, int_error;
821 double prop_adj, int_adj, total_adj;
823 error = TargetSpeed - get_speed();
825 // accumulate the error under the curve ... this really should
827 speed_error_accum += error;
828 if ( speed_error_accum > 2000.0 ) {
829 speed_error_accum = 2000.0;
831 else if ( speed_error_accum < -2000.0 ) {
832 speed_error_accum = -2000.0;
835 // calculate integral error, and adjustment amount
836 int_error = speed_error_accum;
838 // printf("error = %.2f int_error = %.2f\n", error, int_error);
839 int_adj = int_error / 200.0;
841 // caclulate proportional error
843 prop_adj = 0.5 + prop_error / 50.0;
845 total_adj = 0.9 * prop_adj + 0.1 * int_adj;
846 if ( total_adj > 1.0 ) {
849 else if ( total_adj < 0.0 ) {
853 globals->get_controls()->set_throttle( FGControls::ALL_ENGINES,
857 #ifdef THIS_CODE_IS_NOT_USED
858 if (Mode == 2) // Glide slope hold
863 // First, calculate Relative slope and normalize it
864 RelSlope = NormalizeDegrees( TargetSlope - get_pitch());
866 // Now calculate the elevator offset from current angle
867 if ( abs(RelSlope) > SlopeSmooth )
869 if ( RelSlope < 0 ) // set RelElevator to max in the correct direction
870 RelElevator = -MaxElevator;
872 RelElevator = MaxElevator;
876 RelElevator = LinearExtrapolate(RelSlope,-SlopeSmooth,-MaxElevator,SlopeSmooth,MaxElevator);
879 fgElevMove(RelElevator);
882 #endif // THIS_CODE_IS_NOT_USED
884 // stash this runs control settings
885 // update_old_control_values();
886 old_aileron = globals->get_controls()->get_aileron();
887 old_elevator = globals->get_controls()->get_elevator();
888 old_elevator_trim = globals->get_controls()->get_elevator_trim();
889 old_rudder = globals->get_controls()->get_rudder();
891 // for cross track error
896 SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run( returns )" );
900 void FGAutopilot::set_HeadingMode( fgAutoHeadingMode mode ) {
903 if ( heading_mode == FG_DG_HEADING_LOCK ) {
904 // use current heading bug value
905 } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
906 // set autopilot to hold a zero turn (as reported by the TC)
907 } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
908 // set heading hold to current heading
909 TargetHeading = heading_node->getDoubleValue();
910 } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
911 if ( globals->get_route()->size() ) {
912 double course, distance;
914 old_lat = latitude_node->getDoubleValue();
915 old_lon = longitude_node->getDoubleValue();
917 waypoint = globals->get_route()->get_first();
918 waypoint.CourseAndDistance( longitude_node->getDoubleValue(),
919 latitude_node->getDoubleValue(),
920 altitude_node->getDoubleValue()
922 &course, &distance );
923 TargetHeading = course;
924 TargetDistance = distance;
925 MakeTargetLatLonStr( waypoint.get_target_lat(),
926 waypoint.get_target_lon() );
927 MakeTargetWPStr( distance );
929 if ( waypoint.get_target_alt() > 0.0 ) {
930 TargetAltitude = waypoint.get_target_alt();
931 altitude_mode = DEFAULT_AP_ALTITUDE_LOCK;
932 set_AltitudeEnabled( true );
933 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
936 SG_LOG( SG_COCKPIT, SG_INFO, " set_HeadingMode: ( "
937 << get_TargetLatitude() << " "
938 << get_TargetLongitude() << " ) "
941 // no more way points, default to heading lock.
942 heading_mode = FG_TC_HEADING_LOCK;
946 MakeTargetHeadingStr( TargetHeading );
947 update_old_control_values();
951 void FGAutopilot::set_AltitudeMode( fgAutoAltitudeMode mode ) {
952 altitude_mode = mode;
954 alt_error_accum = 0.0;
957 if ( altitude_mode == DEFAULT_AP_ALTITUDE_LOCK ) {
958 if ( TargetAltitude < altitude_agl_node->getDoubleValue()
959 * SG_FEET_TO_METER ) {
962 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
963 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
965 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
967 } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
968 climb_error_accum = 0.0;
970 } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
971 TargetAGL = altitude_agl_node->getDoubleValue() * SG_FEET_TO_METER;
973 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
974 MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
976 MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
980 update_old_control_values();
981 SG_LOG( SG_COCKPIT, SG_INFO, " set_AltitudeMode():" );
985 void FGAutopilot::AltitudeSet( double new_altitude ) {
986 double target_alt = new_altitude;
987 altitude_mode = DEFAULT_AP_ALTITUDE_LOCK;
989 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
990 target_alt = new_altitude * SG_FEET_TO_METER;
993 if( target_alt < globals->get_scenery()->get_cur_elev() ) {
994 target_alt = globals->get_scenery()->get_cur_elev();
997 TargetAltitude = target_alt;
999 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
1000 target_alt *= SG_METER_TO_FEET;
1002 // ApAltitudeDialogInput->setValue((float)target_alt);
1003 MakeTargetAltitudeStr( target_alt );
1005 update_old_control_values();
1009 void FGAutopilot::AltitudeAdjust( double inc )
1011 double target_alt, target_agl;
1013 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
1014 target_alt = TargetAltitude * SG_METER_TO_FEET;
1015 target_agl = TargetAGL * SG_METER_TO_FEET;
1017 target_alt = TargetAltitude;
1018 target_agl = TargetAGL;
1021 if ( fabs((int)(target_alt / inc) * inc - target_alt) < SG_EPSILON ) {
1024 target_alt = ( int ) ( target_alt / inc ) * inc + inc;
1027 if ( fabs((int)(target_agl / inc) * inc - target_agl) < SG_EPSILON ) {
1030 target_agl = ( int ) ( target_agl / inc ) * inc + inc;
1033 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
1034 target_alt *= SG_FEET_TO_METER;
1035 target_agl *= SG_FEET_TO_METER;
1038 TargetAltitude = target_alt;
1039 TargetAGL = target_agl;
1041 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
1042 target_alt *= SG_METER_TO_FEET;
1043 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
1044 target_agl *= SG_METER_TO_FEET;
1046 if ( altitude_mode == DEFAULT_AP_ALTITUDE_LOCK ) {
1047 MakeTargetAltitudeStr( target_alt );
1048 } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
1049 MakeTargetAltitudeStr( target_agl );
1052 update_old_control_values();
1056 void FGAutopilot::HeadingAdjust( double inc ) {
1057 if ( heading_mode != FG_DG_HEADING_LOCK
1058 && heading_mode != FG_TRUE_HEADING_LOCK )
1060 heading_mode = DEFAULT_AP_HEADING_LOCK;
1063 if ( heading_mode == FG_DG_HEADING_LOCK ) {
1064 double target = ( int ) ( DGTargetHeading / inc ) * inc + inc;
1065 DGTargetHeading = NormalizeDegrees( target );
1067 double target = ( int ) ( TargetHeading / inc ) * inc + inc;
1068 TargetHeading = NormalizeDegrees( target );
1071 update_old_control_values();
1075 void FGAutopilot::HeadingSet( double new_heading ) {
1076 heading_mode = DEFAULT_AP_HEADING_LOCK;
1077 if( heading_mode == FG_TRUE_HEADING_LOCK ) {
1078 new_heading = NormalizeDegrees( new_heading );
1079 TargetHeading = new_heading;
1080 MakeTargetHeadingStr( TargetHeading );
1082 heading_mode = FG_DG_HEADING_LOCK;
1084 new_heading = NormalizeDegrees( new_heading );
1085 DGTargetHeading = new_heading;
1086 // following cast needed ambiguous plib
1087 // ApHeadingDialogInput -> setValue ((float)APData->TargetHeading );
1088 MakeTargetHeadingStr( DGTargetHeading );
1090 update_old_control_values();
1093 void FGAutopilot::AutoThrottleAdjust( double inc ) {
1094 double target = ( int ) ( TargetSpeed / inc ) * inc + inc;
1096 TargetSpeed = target;
1100 void FGAutopilot::set_AutoThrottleEnabled( bool value ) {
1101 auto_throttle = value;
1103 if ( auto_throttle == true ) {
1104 TargetSpeed = fgGetDouble("/velocities/airspeed-kt");
1105 speed_error_accum = 0.0;
1108 update_old_control_values();
1109 SG_LOG( SG_COCKPIT, SG_INFO, " fgAPSetAutoThrottle: ("
1110 << auto_throttle << ") " << TargetSpeed );
1116 ////////////////////////////////////////////////////////////////////////
1117 // Kludged methods for tying to properties.
1119 // These should change eventually; they all used to be static
1121 ////////////////////////////////////////////////////////////////////////
1124 * Get the autopilot altitude lock (true=on).
1127 FGAutopilot::getAPAltitudeLock () const
1129 return (get_AltitudeEnabled() &&
1131 == DEFAULT_AP_ALTITUDE_LOCK);
1136 * Set the autopilot altitude lock (true=on).
1139 FGAutopilot::setAPAltitudeLock (bool lock)
1142 set_AltitudeMode(DEFAULT_AP_ALTITUDE_LOCK);
1143 if (get_AltitudeMode() == DEFAULT_AP_ALTITUDE_LOCK)
1144 set_AltitudeEnabled(lock);
1149 * Get the autopilot target altitude in feet.
1152 FGAutopilot::getAPAltitude () const
1154 return get_TargetAltitude() * SG_METER_TO_FEET;
1159 * Set the autopilot target altitude in feet.
1162 FGAutopilot::setAPAltitude (double altitude)
1164 set_TargetAltitude( altitude * SG_FEET_TO_METER );
1168 * Get the autopilot altitude lock (true=on).
1171 FGAutopilot::getAPGSLock () const
1173 return (get_AltitudeEnabled() &&
1175 == FGAutopilot::FG_ALTITUDE_GS1));
1180 * Set the autopilot altitude lock (true=on).
1183 FGAutopilot::setAPGSLock (bool lock)
1186 set_AltitudeMode(FGAutopilot::FG_ALTITUDE_GS1);
1187 if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_GS1)
1188 set_AltitudeEnabled(lock);
1193 * Get the autopilot terrain lock (true=on).
1196 FGAutopilot::getAPTerrainLock () const
1198 return (get_AltitudeEnabled() &&
1200 == FGAutopilot::FG_ALTITUDE_TERRAIN));
1205 * Set the autopilot terrain lock (true=on).
1208 FGAutopilot::setAPTerrainLock (bool lock)
1211 set_AltitudeMode(FGAutopilot::FG_ALTITUDE_TERRAIN);
1212 set_TargetAGL(fgGetFloat("/position/altitude-agl-ft") *
1215 if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_TERRAIN)
1216 set_AltitudeEnabled(lock);
1221 * Get the autopilot target altitude in feet.
1224 FGAutopilot::getAPClimb () const
1226 return get_TargetClimbRate() * SG_METER_TO_FEET;
1231 * Set the autopilot target altitude in feet.
1234 FGAutopilot::setAPClimb (double rate)
1236 set_TargetClimbRate( rate * SG_FEET_TO_METER );
1241 * Get the autopilot heading lock (true=on).
1244 FGAutopilot::getAPHeadingLock () const
1247 (get_HeadingEnabled() &&
1248 get_HeadingMode() == DEFAULT_AP_HEADING_LOCK);
1253 * Set the autopilot heading lock (true=on).
1256 FGAutopilot::setAPHeadingLock (bool lock)
1259 set_HeadingMode(DEFAULT_AP_HEADING_LOCK);
1260 if (get_HeadingMode() == DEFAULT_AP_HEADING_LOCK)
1261 set_HeadingEnabled(lock);
1266 * Get the autopilot heading bug in degrees.
1269 FGAutopilot::getAPHeadingBug () const
1271 return get_DGTargetHeading();
1276 * Set the autopilot heading bug in degrees.
1279 FGAutopilot::setAPHeadingBug (double heading)
1281 set_DGTargetHeading( heading );
1286 * return blank-separated string of waypoints
1289 FGAutopilot::getAPwaypoint () const
1291 static char wplist[500];
1295 // FIXME: This can cause a possible buffer overflow, EMH
1296 if ( globals->get_route()->size() > 0 ) {
1297 WPListsize = globals->get_route()->size();
1299 for (i = 0; i < globals->get_route()->size(); i++ ) {
1300 p += sprintf(p, "%5s ",
1301 globals->get_route()->get_waypoint(i).get_id().c_str() );
1306 return "none specified";
1312 * set next waypoint (if str='0', then delete next(first) waypoint)
1315 FGAutopilot::setAPwaypoint (const char * apt)
1317 if (strcmp(apt, "0")==0)
1319 SG_LOG( SG_AUTOPILOT, SG_INFO, "delete of first wp" );
1320 if ( globals->get_route()->size() )
1321 globals->get_route()->delete_first();
1325 if ( NewWaypoint( apt ) == 0)
1326 SG_LOG( SG_AUTOPILOT, SG_INFO, "Waypoint " << apt << "not in d.b." );
1329 /* SG_LOG( SG_AUTOPILOT, SG_INFO, "GOOD!" ); */
1334 * Get the autopilot wing leveler lock (true=on).
1337 FGAutopilot::getAPWingLeveler () const
1340 (get_HeadingEnabled() &&
1341 get_HeadingMode() == FGAutopilot::FG_TC_HEADING_LOCK);
1346 * Set the autopilot wing leveler lock (true=on).
1349 FGAutopilot::setAPWingLeveler (bool lock)
1352 set_HeadingMode(FGAutopilot::FG_TC_HEADING_LOCK);
1353 if (get_HeadingMode() == FGAutopilot::FG_TC_HEADING_LOCK)
1354 set_HeadingEnabled(lock);
1358 * Return true if the autopilot is locked to NAV1.
1361 FGAutopilot::getAPNAV1Lock () const
1364 (get_HeadingEnabled() &&
1365 get_HeadingMode() == FGAutopilot::FG_HEADING_NAV1);
1370 * Set the autopilot NAV1 lock.
1373 FGAutopilot::setAPNAV1Lock (bool lock)
1376 set_HeadingMode(FGAutopilot::FG_HEADING_NAV1);
1377 if (get_HeadingMode() == FGAutopilot::FG_HEADING_NAV1)
1378 set_HeadingEnabled(lock);
1382 * Get the autopilot autothrottle lock.
1385 FGAutopilot::getAPAutoThrottleLock () const
1387 return get_AutoThrottleEnabled();
1392 * Set the autothrottle lock.
1395 FGAutopilot::setAPAutoThrottleLock (bool lock)
1397 set_AutoThrottleEnabled(lock);
1403 FGAutopilot::getAPRudderControl () const
1405 if (getAPHeadingLock())
1406 return get_TargetHeading();
1408 return globals->get_controls()->get_rudder();
1413 FGAutopilot::setAPRudderControl (double value)
1415 if (getAPHeadingLock()) {
1416 SG_LOG(SG_GENERAL, SG_DEBUG, "setAPRudderControl " << value );
1417 value -= get_TargetHeading();
1418 HeadingAdjust(value < 0.0 ? -1.0 : 1.0);
1420 globals->get_controls()->set_rudder(value);
1426 FGAutopilot::getAPElevatorControl () const
1428 if (getAPAltitudeLock())
1429 return get_TargetAltitude();
1431 return globals->get_controls()->get_elevator();
1436 FGAutopilot::setAPElevatorControl (double value)
1438 if (value != 0 && getAPAltitudeLock()) {
1439 SG_LOG(SG_GENERAL, SG_DEBUG, "setAPElevatorControl " << value );
1440 value -= get_TargetAltitude();
1441 AltitudeAdjust(value < 0.0 ? 100.0 : -100.0);
1443 globals->get_controls()->set_elevator(value);
1449 FGAutopilot::getAPThrottleControl () const
1451 if (getAPAutoThrottleLock())
1452 return 0.0; // always resets
1454 return globals->get_controls()->get_throttle(0);
1459 FGAutopilot::setAPThrottleControl (double value)
1461 if (getAPAutoThrottleLock())
1462 AutoThrottleAdjust(value < 0.0 ? -0.01 : 0.01);
1464 globals->get_controls()->set_throttle(FGControls::ALL_ENGINES, value);
1467 // end of newauto.cxx