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()
32 #include <simgear/constants.h>
33 #include <simgear/sg_inlines.h>
34 #include <simgear/debug/logstream.hxx>
35 #include <simgear/math/sg_geodesy.hxx>
36 #include <simgear/math/sg_random.h>
37 #include <simgear/route/route.hxx>
39 #include <Cockpit/steam.hxx>
40 #include <Cockpit/radiostack.hxx>
41 #include <Controls/controls.hxx>
42 #include <FDM/flight.hxx>
43 #include <Main/globals.hxx>
44 #include <Scenery/scenery.hxx>
46 #include "newauto.hxx"
49 /// These statics will eventually go into the class
50 /// they are just here while I am experimenting -- NHV :-)
51 // AutoPilot Gain Adjuster members
52 static double MaxRollAdjust; // MaxRollAdjust = 2 * APData->MaxRoll;
53 static double RollOutAdjust; // RollOutAdjust = 2 * APData->RollOut;
54 static double MaxAileronAdjust; // MaxAileronAdjust = 2 * APData->MaxAileron;
55 static double RollOutSmoothAdjust; // RollOutSmoothAdjust = 2 * APData->RollOutSmooth;
57 static char NewTgtAirportId[16];
58 // static char NewTgtAirportLabel[] = "Enter New TgtAirport ID";
60 extern char *coord_format_lat(float);
61 extern char *coord_format_lon(float);
65 FGAutopilot::FGAutopilot()
70 FGAutopilot::~FGAutopilot() {}
73 void FGAutopilot::MakeTargetLatLonStr( double lat, double lon ) {
74 sprintf( TargetLatitudeStr , "%s", coord_format_lat(get_TargetLatitude()));
75 sprintf( TargetLongitudeStr, "%s", coord_format_lon(get_TargetLongitude()));
76 sprintf( TargetLatLonStr, "%s %s", TargetLatitudeStr, TargetLongitudeStr );
80 void FGAutopilot::MakeTargetAltitudeStr( double altitude ) {
81 if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
82 sprintf( TargetAltitudeStr, "APAltitude %6.0f+", altitude );
84 sprintf( TargetAltitudeStr, "APAltitude %6.0f", altitude );
89 void FGAutopilot::MakeTargetHeadingStr( double bearing ) {
92 } else if (bearing > 360. ) {
95 sprintf( TargetHeadingStr, "APHeading %6.1f", bearing );
99 static inline double get_speed( void ) {
100 return( cur_fdm_state->get_V_equiv_kts() );
103 static inline double get_ground_speed() {
104 // starts in ft/s so we convert to kts
105 static const SGPropertyNode * speedup_node = fgGetNode("/sim/speed-up");
107 double ft_s = cur_fdm_state->get_V_ground_speed()
108 * speedup_node->getIntValue();
109 double kts = ft_s * SG_FEET_TO_METER * 3600 * SG_METER_TO_NM;
115 void FGAutopilot::MakeTargetWPStr( double distance ) {
116 static time_t last_time = 0;
117 time_t current_time = time(NULL);
118 if ( last_time == current_time ) {
122 last_time = current_time;
126 int size = globals->get_route()->size();
128 // start by wiping the strings
135 SGWayPoint wp1 = globals->get_route()->get_waypoint( 0 );
137 double eta = accum * SG_METER_TO_NM / get_ground_speed();
138 if ( eta >= 100.0 ) { eta = 99.999; }
140 if ( eta < (1.0/6.0) ) {
141 // within 10 minutes, bump up to min/secs
145 minor = (int)((eta - (int)eta) * 60.0);
146 sprintf( TargetWP1Str, "%s %.2f NM ETA %d:%02d",
147 wp1.get_id().c_str(),
148 accum*SG_METER_TO_NM, major, minor );
153 SGWayPoint wp2 = globals->get_route()->get_waypoint( 1 );
154 accum += wp2.get_distance();
156 double eta = accum * SG_METER_TO_NM / get_ground_speed();
157 if ( eta >= 100.0 ) { eta = 99.999; }
159 if ( eta < (1.0/6.0) ) {
160 // within 10 minutes, bump up to min/secs
164 minor = (int)((eta - (int)eta) * 60.0);
165 sprintf( TargetWP2Str, "%s %.2f NM ETA %d:%02d",
166 wp2.get_id().c_str(),
167 accum*SG_METER_TO_NM, major, minor );
172 for ( int i = 2; i < size; ++i ) {
173 accum += globals->get_route()->get_waypoint( i ).get_distance();
176 SGWayPoint wpn = globals->get_route()->get_waypoint( size - 1 );
178 double eta = accum * SG_METER_TO_NM / get_ground_speed();
179 if ( eta >= 100.0 ) { eta = 99.999; }
181 if ( eta < (1.0/6.0) ) {
182 // within 10 minutes, bump up to min/secs
186 minor = (int)((eta - (int)eta) * 60.0);
187 sprintf( TargetWP3Str, "%s %.2f NM ETA %d:%02d",
188 wpn.get_id().c_str(),
189 accum*SG_METER_TO_NM, major, minor );
194 void FGAutopilot::update_old_control_values() {
195 old_aileron = globals->get_controls()->get_aileron();
196 old_elevator = globals->get_controls()->get_elevator();
197 old_elevator_trim = globals->get_controls()->get_elevator_trim();
198 old_rudder = globals->get_controls()->get_rudder();
202 // Initialize autopilot subsystem
204 void FGAutopilot::init ()
206 SG_LOG( SG_AUTOPILOT, SG_INFO, "Init AutoPilot Subsystem" );
208 // bind data input property nodes...
209 latitude_node = fgGetNode("/position/latitude-deg", true);
210 longitude_node = fgGetNode("/position/longitude-deg", true);
211 altitude_node = fgGetNode("/position/altitude-ft", true);
212 altitude_agl_node = fgGetNode("/position/altitude-agl-ft", true);
213 vertical_speed_node = fgGetNode("/velocities/vertical-speed-fps", true);
214 heading_node = fgGetNode("/orientation/heading-deg", true);
215 roll_node = fgGetNode("/orientation/roll-deg", true);
216 pitch_node = fgGetNode("/orientation/pitch-deg", true);
218 // bind config property nodes...
220 = fgGetNode("/autopilot/config/target-climb-rate-fpm", true);
222 = fgGetNode("/autopilot/config/target-descent-rate-fpm", true);
223 min_climb = fgGetNode("/autopilot/config/min-climb-speed-kt", true);
224 best_climb = fgGetNode("/autopilot/config/best-climb-speed-kt", true);
226 = fgGetNode("/autopilot/config/elevator-adj-factor", true);
228 = fgGetNode("/autopilot/config/integral-contribution", true);
230 = fgGetNode("/autopilot/config/zero-pitch-throttle", true);
231 zero_pitch_trim_full_throttle
232 = fgGetNode("/autopilot/config/zero-pitch-trim-full-throttle", true);
233 current_throttle = fgGetNode("/controls/throttle");
235 // initialize config properties with defaults (in case config isn't there)
236 if ( TargetClimbRate->getFloatValue() < 1 )
237 fgSetFloat( "/autopilot/config/target-climb-rate-fpm", 500);
238 if ( TargetDescentRate->getFloatValue() < 1 )
239 fgSetFloat( "/autopilot/config/target-descent-rate-fpm", 1000 );
240 if ( min_climb->getFloatValue() < 1)
241 fgSetFloat( "/autopilot/config/min-climb-speed-kt", 70 );
242 if (best_climb->getFloatValue() < 1)
243 fgSetFloat( "/autopilot/config/best-climb-speed-kt", 120 );
244 if (elevator_adj_factor->getFloatValue() < 1)
245 fgSetFloat( "/autopilot/config/elevator-adj-factor", 5000 );
246 if ( integral_contrib->getFloatValue() < 0.0000001 )
247 fgSetFloat( "/autopilot/config/integral-contribution", 0.01 );
248 if ( zero_pitch_throttle->getFloatValue() < 0.0000001 )
249 fgSetFloat( "/autopilot/config/zero-pitch-throttle", 0.60 );
250 if ( zero_pitch_trim_full_throttle->getFloatValue() < 0.0000001 )
251 fgSetFloat( "/autopilot/config/zero-pitch-trim-full-throttle", 0.15 );
254 heading_hold = false ; // turn the heading hold off
255 altitude_hold = false ; // turn the altitude hold off
256 auto_throttle = false ; // turn the auto throttle off
257 heading_mode = DEFAULT_AP_HEADING_LOCK;
259 DGTargetHeading = fgGetDouble("/autopilot/settings/heading-bug-deg");
260 TargetHeading = fgGetDouble("/autopilot/settings/heading-bug-deg");
261 TargetAltitude = fgGetDouble("/autopilot/settings/altitude-ft") * SG_FEET_TO_METER;
263 // Initialize target location to startup location
264 old_lat = latitude_node->getDoubleValue();
265 old_lon = longitude_node->getDoubleValue();
266 // set_WayPoint( old_lon, old_lat, 0.0, "default" );
268 MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
270 alt_error_accum = 0.0;
271 climb_error_accum = 0.0;
273 MakeTargetAltitudeStr( TargetAltitude );
274 MakeTargetHeadingStr( TargetHeading );
276 // These eventually need to be read from current_aircaft somehow.
278 // the maximum roll, in Deg
281 // the deg from heading to start rolling out at, in Deg
284 // how far can I move the aleron from center.
287 // Smoothing distance for alerion control
290 // Hardwired for now should be in options
291 // 25% max control variablilty 0.5 / 2.0
292 disengage_threshold = 1.0;
294 #if !defined( USING_SLIDER_CLASS )
295 MaxRollAdjust = 2 * MaxRoll;
296 RollOutAdjust = 2 * RollOut;
297 MaxAileronAdjust = 2 * MaxAileron;
298 RollOutSmoothAdjust = 2 * RollOutSmooth;
299 #endif // !defined( USING_SLIDER_CLASS )
301 update_old_control_values();
307 // Autopilot control property get/set bindings
308 fgTie("/autopilot/locks/altitude", this,
309 &FGAutopilot::getAPAltitudeLock, &FGAutopilot::setAPAltitudeLock);
310 fgSetArchivable("/autopilot/locks/altitude");
311 fgTie("/autopilot/settings/altitude-ft", this,
312 &FGAutopilot::getAPAltitude, &FGAutopilot::setAPAltitude);
313 fgSetArchivable("/autopilot/settings/altitude-ft");
314 fgTie("/autopilot/locks/glide-slope", this,
315 &FGAutopilot::getAPGSLock, &FGAutopilot::setAPGSLock);
316 fgSetArchivable("/autopilot/locks/glide-slope");
317 fgSetDouble("/autopilot/settings/altitude-ft", 3000.0f);
318 fgTie("/autopilot/locks/terrain", this,
319 &FGAutopilot::getAPTerrainLock, &FGAutopilot::setAPTerrainLock);
320 fgSetArchivable("/autopilot/locks/terrain");
321 fgTie("/autopilot/settings/climb-rate-fpm", this,
322 &FGAutopilot::getAPClimb, &FGAutopilot::setAPClimb, false);
323 fgSetArchivable("/autopilot/settings/climb-rate-fpm");
324 fgTie("/autopilot/locks/heading", this,
325 &FGAutopilot::getAPHeadingLock, &FGAutopilot::setAPHeadingLock);
326 fgSetArchivable("/autopilot/locks/heading");
327 fgTie("/autopilot/settings/heading-bug-deg", this,
328 &FGAutopilot::getAPHeadingBug, &FGAutopilot::setAPHeadingBug);
329 fgSetArchivable("/autopilot/settings/heading-bug-deg");
330 fgSetDouble("/autopilot/settings/heading-bug-deg", 0.0f);
331 fgTie("/autopilot/locks/wing-leveler", this,
332 &FGAutopilot::getAPWingLeveler, &FGAutopilot::setAPWingLeveler);
333 fgSetArchivable("/autopilot/locks/wing-leveler");
334 fgTie("/autopilot/locks/nav[0]", this,
335 &FGAutopilot::getAPNAV1Lock, &FGAutopilot::setAPNAV1Lock);
336 fgSetArchivable("/autopilot/locks/nav[0]");
337 fgTie("/autopilot/locks/auto-throttle", this,
338 &FGAutopilot::getAPAutoThrottleLock,
339 &FGAutopilot::setAPAutoThrottleLock);
340 fgSetArchivable("/autopilot/locks/auto-throttle");
341 fgTie("/autopilot/control-overrides/rudder", this,
342 &FGAutopilot::getAPRudderControl,
343 &FGAutopilot::setAPRudderControl);
344 fgSetArchivable("/autopilot/control-overrides/rudder");
345 fgTie("/autopilot/control-overrides/elevator", this,
346 &FGAutopilot::getAPElevatorControl,
347 &FGAutopilot::setAPElevatorControl);
348 fgSetArchivable("/autopilot/control-overrides/elevator");
349 fgTie("/autopilot/control-overrides/throttle", this,
350 &FGAutopilot::getAPThrottleControl,
351 &FGAutopilot::setAPThrottleControl);
352 fgSetArchivable("/autopilot/control-overrides/throttle");
356 FGAutopilot::unbind ()
360 // Reset the autopilot system
361 void FGAutopilot::reset() {
363 heading_hold = false ; // turn the heading hold off
364 altitude_hold = false ; // turn the altitude hold off
365 auto_throttle = false ; // turn the auto throttle off
366 heading_mode = DEFAULT_AP_HEADING_LOCK;
368 // TargetHeading = 0.0; // default direction, due north
369 MakeTargetHeadingStr( TargetHeading );
371 // TargetAltitude = 3000; // default altitude in meters
372 MakeTargetAltitudeStr( TargetAltitude );
374 alt_error_accum = 0.0;
375 climb_error_accum = 0.0;
377 update_old_control_values();
379 sprintf( NewTgtAirportId, "%s", fgGetString("/sim/startup/airport-id") );
381 MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
385 static double NormalizeDegrees( double Input ) {
386 // normalize the input to the range (-180,180]
387 // Input should not be greater than -360 to 360.
388 // Current rules send the output to an undefined state.
389 while ( Input > 180.0 ) { Input -= 360.0; }
390 while ( Input <= -180.0 ) { Input += 360.0; }
395 static double LinearExtrapolate( double x, double x1, double y1, double x2, double y2 ) {
396 // This procedure extrapolates the y value for the x posistion on a line defined by x1,y1; x2,y2
397 //assert(x1 != x2); // Divide by zero error. Cold abort for now
400 // static double y = 0.0;
401 // double dx = x2 -x1;
402 // if( (dx < -SG_EPSILON ) || ( dx > SG_EPSILON ) )
405 double m, b, y; // the constants to find in y=mx+b
408 m = ( y2 - y1 ) / ( x2 - x1 ); // calculate the m
410 b = y1 - m * x1; // calculate the b
412 y = m * x + b; // the final calculation
422 FGAutopilot::update (int dt)
424 // Remove the following lines when the calling funcitons start
425 // passing in the data pointer
427 // get control settings
429 double lat = latitude_node->getDoubleValue();
430 double lon = longitude_node->getDoubleValue();
431 double alt = altitude_node->getDoubleValue() * SG_FEET_TO_METER;
433 SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run() lat = " << lat <<
434 " lon = " << lon << " alt = " << alt );
436 #ifdef FG_FORCE_AUTO_DISENGAGE
437 // see if somebody else has changed them
438 if( fabs(aileron - old_aileron) > disengage_threshold ||
439 fabs(elevator - old_elevator) > disengage_threshold ||
440 fabs(elevator_trim - old_elevator_trim) >
441 disengage_threshold ||
442 fabs(rudder - old_rudder) > disengage_threshold )
444 // if controls changed externally turn autopilot off
445 waypoint_hold = false ; // turn the target hold off
446 heading_hold = false ; // turn the heading hold off
447 altitude_hold = false ; // turn the altitude hold off
448 terrain_follow = false; // turn the terrain_follow hold off
449 // auto_throttle = false; // turn the auto_throttle off
451 // stash this runs control settings
452 old_aileron = aileron;
453 old_elevator = elevator;
454 old_elevator_trim = elevator_trim;
462 if ( heading_hold == true ) {
463 if ( heading_mode == FG_DG_HEADING_LOCK ) {
464 TargetHeading = DGTargetHeading + FGSteam::get_DG_err();
465 while ( TargetHeading < 0.0 ) { TargetHeading += 360.0; }
466 while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
467 MakeTargetHeadingStr( TargetHeading );
468 } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
469 // we don't set a specific target heading in
470 // TC_HEADING_LOCK mode, we instead try to keep the turn
471 // coordinator zero'd
472 } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
473 // leave "true" target heading as is
474 while ( TargetHeading < 0.0 ) { TargetHeading += 360.0; }
475 while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
476 MakeTargetHeadingStr( TargetHeading );
477 } else if ( heading_mode == FG_HEADING_NAV1 ) {
478 // track the NAV1 heading needle deflection
480 // determine our current radial position relative to the
481 // navaid in "true" heading.
482 double cur_radial = current_radiostack->get_nav1_heading();
483 if ( current_radiostack->get_nav1_loc() ) {
484 // ILS localizers radials are already "true" in our
487 cur_radial += current_radiostack->get_nav1_magvar();
489 if ( current_radiostack->get_nav1_from_flag() ) {
491 while ( cur_radial >= 360.0 ) { cur_radial -= 360.0; }
494 // determine the target radial in "true" heading
495 double tgt_radial = current_radiostack->get_nav1_radial();
496 if ( current_radiostack->get_nav1_loc() ) {
497 // ILS localizers radials are already "true" in our
500 // VOR radials need to have that vor's offset added in
501 tgt_radial += current_radiostack->get_nav1_magvar();
504 // determine the heading adjustment needed.
506 current_radiostack->get_nav1_heading_needle_deflection()
507 * (current_radiostack->get_nav1_loc_dist() * SG_METER_TO_NM);
508 SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
510 // determine the target heading to fly to intercept the
512 TargetHeading = tgt_radial + adjustment;
513 while ( TargetHeading < 0.0 ) { TargetHeading += 360.0; }
514 while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
516 MakeTargetHeadingStr( TargetHeading );
517 } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
518 // update target heading to waypoint
520 double wp_course, wp_distance;
522 #ifdef DO_fgAP_CORRECTED_COURSE
523 // compute course made good
524 // this needs lots of special casing before use
525 double course, reverse, distance, corrected_course;
526 // need to test for iter
527 geo_inverse_wgs_84( 0, //fgAPget_altitude(),
535 #endif // DO_fgAP_CORRECTED_COURSE
537 // compute course to way_point
538 // need to test for iter
539 SGWayPoint wp = globals->get_route()->get_first();
540 wp.CourseAndDistance( lon, lat, alt,
541 &wp_course, &wp_distance );
543 #ifdef DO_fgAP_CORRECTED_COURSE
544 corrected_course = course - wp_course;
545 if( fabs(corrected_course) > 0.1 )
546 printf("fgAP: course %f wp_course %f %f %f\n",
547 course, wp_course, fabs(corrected_course),
549 #endif // DO_fgAP_CORRECTED_COURSE
551 if ( wp_distance > 100 ) {
552 // corrected_course = course - wp_course;
553 TargetHeading = NormalizeDegrees(wp_course);
555 // pop off this waypoint from the list
556 if ( globals->get_route()->size() ) {
557 globals->get_route()->delete_first();
560 // see if there are more waypoints on the list
561 if ( globals->get_route()->size() ) {
563 set_HeadingMode( FG_HEADING_WAYPOINT );
566 heading_mode = FG_TRUE_HEADING_LOCK;
567 // use current heading
568 TargetHeading = heading_node->getDoubleValue();
571 MakeTargetHeadingStr( TargetHeading );
572 // Force this just in case
573 TargetDistance = wp_distance;
574 MakeTargetWPStr( wp_distance );
577 if ( heading_mode == FG_TC_HEADING_LOCK ) {
578 // drive the turn coordinator to zero
579 double turn = FGSteam::get_TC_std();
580 double AileronSet = -turn / 2.0;
581 SG_CLAMP_RANGE( AileronSet, -1.0, 1.0 );
582 globals->get_controls()->set_aileron( AileronSet );
583 globals->get_controls()->set_rudder( AileronSet / 4.0 );
585 // steer towards the target heading
593 = NormalizeDegrees( TargetHeading
594 - heading_node->getDoubleValue() );
595 // figure out how far off we are from desired heading
597 // Now it is time to deterime how far we should be rolled.
598 SG_LOG( SG_AUTOPILOT, SG_DEBUG, "RelHeading: " << RelHeading );
601 // Check if we are further from heading than the roll out point
602 if ( fabs( RelHeading ) > RollOut ) {
603 // set Target Roll to Max in desired direction
604 if ( RelHeading < 0 ) {
605 TargetRoll = 0 - MaxRoll;
607 TargetRoll = MaxRoll;
610 // We have to calculate the Target roll
612 // This calculation engine thinks that the Target roll
613 // should be a line from (RollOut,MaxRoll) to (-RollOut,
614 // -MaxRoll) I hope this works well. If I get ambitious
615 // some day this might become a fancier curve or
618 TargetRoll = LinearExtrapolate( RelHeading, -RollOut,
623 // Target Roll has now been Found.
625 // Compare Target roll to Current Roll, Generate Rel Roll
627 SG_LOG( SG_COCKPIT, SG_BULK, "TargetRoll: " << TargetRoll );
629 RelRoll = NormalizeDegrees( TargetRoll
630 - roll_node->getDoubleValue() );
632 // Check if we are further from heading than the roll out
634 if ( fabs( RelRoll ) > RollOutSmooth ) {
635 // set Target Roll to Max in desired direction
637 AileronSet = 0 - MaxAileron;
639 AileronSet = MaxAileron;
642 AileronSet = LinearExtrapolate( RelRoll, -RollOutSmooth,
648 globals->get_controls()->set_aileron( AileronSet );
649 globals->get_controls()->set_rudder( AileronSet / 4.0 );
650 // controls.set_rudder( 0.0 );
655 if ( altitude_hold ) {
657 double speed, max_climb, error;
658 double prop_error, int_error;
659 double prop_adj, int_adj, total_adj;
661 if ( altitude_mode == FG_ALTITUDE_LOCK ) {
663 ( TargetAltitude - FGSteam::get_ALT_ft() * SG_FEET_TO_METER ) * 8.0;
664 } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
665 double x = current_radiostack->get_nav1_gs_dist();
666 double y = (altitude_node->getDoubleValue()
667 - current_radiostack->get_nav1_elev()) * SG_FEET_TO_METER;
668 double current_angle = atan2( y, x ) * SGD_RADIANS_TO_DEGREES;
670 double target_angle = current_radiostack->get_nav1_target_gs();
672 double gs_diff = target_angle - current_angle;
674 // convert desired vertical path angle into a climb rate
675 double des_angle = current_angle - 10 * gs_diff;
677 // convert to meter/min
678 double horiz_vel = cur_fdm_state->get_V_ground_speed()
679 * SG_FEET_TO_METER * 60.0;
680 climb_rate = -sin( des_angle * SGD_DEGREES_TO_RADIANS ) * horiz_vel;
681 /* climb_error_accum += gs_diff * 2.0; */
682 /* climb_rate = gs_diff * 200.0 + climb_error_accum; */
683 } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
684 // brain dead ground hugging with no look ahead
686 ( TargetAGL - altitude_agl_node->getDoubleValue()
687 * SG_FEET_TO_METER ) * 16.0;
689 // just try to zero out rate of climb ...
695 if ( speed < min_climb->getFloatValue() ) {
697 } else if ( speed < best_climb->getFloatValue() ) {
698 max_climb = ((best_climb->getFloatValue()
699 - min_climb->getFloatValue())
700 - (best_climb->getFloatValue() - speed))
701 * fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER)
702 / (best_climb->getFloatValue() - min_climb->getFloatValue());
704 max_climb = ( speed - best_climb->getFloatValue() ) * 10.0
705 + fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
708 // this first one could be optional if we wanted to allow
709 // better climb performance assuming we have the airspeed to
712 fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER) ) {
714 = fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
717 if ( climb_rate > max_climb ) {
718 climb_rate = max_climb;
722 -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER) ) {
724 = -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER);
727 error = vertical_speed_node->getDoubleValue() * 60
728 - climb_rate * SG_METER_TO_FEET;
730 // accumulate the error under the curve ... this really should
732 alt_error_accum += error;
734 // calculate integral error, and adjustment amount
735 int_error = alt_error_accum;
736 // printf("error = %.2f int_error = %.2f\n", error, int_error);
737 int_adj = int_error / elevator_adj_factor->getFloatValue();
739 // caclulate proportional error
741 prop_adj = prop_error / elevator_adj_factor->getDoubleValue();
743 total_adj = ((double) 1.0 - (double) integral_contrib->getFloatValue()) * prop_adj
744 + (double) integral_contrib->getFloatValue() * int_adj;
746 // stop on autopilot trim at 30% +/-
747 // if ( total_adj > 0.3 ) {
749 // } else if ( total_adj < -0.3 ) {
753 // adjust for throttle pitch gain
754 total_adj += ((current_throttle->getFloatValue() - zero_pitch_throttle->getFloatValue())
755 / (1 - zero_pitch_throttle->getFloatValue()))
756 * zero_pitch_trim_full_throttle->getFloatValue();
758 globals->get_controls()->set_elevator_trim( total_adj );
762 if ( auto_throttle ) {
764 double prop_error, int_error;
765 double prop_adj, int_adj, total_adj;
767 error = TargetSpeed - get_speed();
769 // accumulate the error under the curve ... this really should
771 speed_error_accum += error;
772 if ( speed_error_accum > 2000.0 ) {
773 speed_error_accum = 2000.0;
775 else if ( speed_error_accum < -2000.0 ) {
776 speed_error_accum = -2000.0;
779 // calculate integral error, and adjustment amount
780 int_error = speed_error_accum;
782 // printf("error = %.2f int_error = %.2f\n", error, int_error);
783 int_adj = int_error / 200.0;
785 // caclulate proportional error
787 prop_adj = 0.5 + prop_error / 50.0;
789 total_adj = 0.9 * prop_adj + 0.1 * int_adj;
790 if ( total_adj > 1.0 ) {
793 else if ( total_adj < 0.0 ) {
797 globals->get_controls()->set_throttle( FGControls::ALL_ENGINES,
801 #ifdef THIS_CODE_IS_NOT_USED
802 if (Mode == 2) // Glide slope hold
807 // First, calculate Relative slope and normalize it
808 RelSlope = NormalizeDegrees( TargetSlope - get_pitch());
810 // Now calculate the elevator offset from current angle
811 if ( abs(RelSlope) > SlopeSmooth )
813 if ( RelSlope < 0 ) // set RelElevator to max in the correct direction
814 RelElevator = -MaxElevator;
816 RelElevator = MaxElevator;
820 RelElevator = LinearExtrapolate(RelSlope,-SlopeSmooth,-MaxElevator,SlopeSmooth,MaxElevator);
823 fgElevMove(RelElevator);
826 #endif // THIS_CODE_IS_NOT_USED
828 // stash this runs control settings
829 // update_old_control_values();
830 old_aileron = globals->get_controls()->get_aileron();
831 old_elevator = globals->get_controls()->get_elevator();
832 old_elevator_trim = globals->get_controls()->get_elevator_trim();
833 old_rudder = globals->get_controls()->get_rudder();
835 // for cross track error
840 SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run( returns )" );
844 void FGAutopilot::set_HeadingMode( fgAutoHeadingMode mode ) {
847 if ( heading_mode == FG_DG_HEADING_LOCK ) {
848 // set heading hold to current heading (as read from DG)
849 // ... no, leave target heading along ... just use the current
851 // DGTargetHeading = FGSteam::get_DG_deg();
852 } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
853 // set autopilot to hold a zero turn (as reported by the TC)
854 } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
855 // set heading hold to current heading
856 TargetHeading = heading_node->getDoubleValue();
857 } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
858 if ( globals->get_route()->size() ) {
859 double course, distance;
861 old_lat = latitude_node->getDoubleValue();
862 old_lon = longitude_node->getDoubleValue();
864 waypoint = globals->get_route()->get_first();
865 waypoint.CourseAndDistance( longitude_node->getDoubleValue(),
866 latitude_node->getDoubleValue(),
867 altitude_node->getDoubleValue()
869 &course, &distance );
870 TargetHeading = course;
871 TargetDistance = distance;
872 MakeTargetLatLonStr( waypoint.get_target_lat(),
873 waypoint.get_target_lon() );
874 MakeTargetWPStr( distance );
876 if ( waypoint.get_target_alt() > 0.0 ) {
877 TargetAltitude = waypoint.get_target_alt();
878 altitude_mode = FG_ALTITUDE_LOCK;
879 set_AltitudeEnabled( true );
880 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
883 SG_LOG( SG_COCKPIT, SG_INFO, " set_HeadingMode: ( "
884 << get_TargetLatitude() << " "
885 << get_TargetLongitude() << " ) "
888 // no more way points, default to heading lock.
889 heading_mode = FG_TC_HEADING_LOCK;
893 MakeTargetHeadingStr( TargetHeading );
894 update_old_control_values();
898 void FGAutopilot::set_AltitudeMode( fgAutoAltitudeMode mode ) {
899 altitude_mode = mode;
901 alt_error_accum = 0.0;
904 if ( altitude_mode == FG_ALTITUDE_LOCK ) {
905 if ( TargetAltitude < altitude_agl_node->getDoubleValue()
906 * SG_FEET_TO_METER ) {
909 if ( fgGetString("/sim/startup/units") == "feet" ) {
910 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
912 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
914 } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
915 climb_error_accum = 0.0;
917 } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
918 TargetAGL = altitude_agl_node->getDoubleValue() * SG_FEET_TO_METER;
920 if ( fgGetString("/sim/startup/units") == "feet" ) {
921 MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
923 MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
927 update_old_control_values();
928 SG_LOG( SG_COCKPIT, SG_INFO, " set_AltitudeMode():" );
932 void FGAutopilot::AltitudeSet( double new_altitude ) {
933 double target_alt = new_altitude;
935 if ( fgGetString("/sim/startup/units") == "feet" ) {
936 target_alt = new_altitude * SG_FEET_TO_METER;
939 if( target_alt < scenery.get_cur_elev() ) {
940 target_alt = scenery.get_cur_elev();
943 TargetAltitude = target_alt;
944 altitude_mode = FG_ALTITUDE_LOCK;
946 if ( fgGetString("/sim/startup/units") == "feet" ) {
947 target_alt *= SG_METER_TO_FEET;
949 // ApAltitudeDialogInput->setValue((float)target_alt);
950 MakeTargetAltitudeStr( target_alt );
952 update_old_control_values();
956 void FGAutopilot::AltitudeAdjust( double inc )
958 double target_alt, target_agl;
960 if ( fgGetString("/sim/startup/units") == "feet" ) {
961 target_alt = TargetAltitude * SG_METER_TO_FEET;
962 target_agl = TargetAGL * SG_METER_TO_FEET;
964 target_alt = TargetAltitude;
965 target_agl = TargetAGL;
968 if ( fabs((int)(target_alt / inc) * inc - target_alt) < SG_EPSILON ) {
971 target_alt = ( int ) ( target_alt / inc ) * inc + inc;
974 if ( fabs((int)(target_agl / inc) * inc - target_agl) < SG_EPSILON ) {
977 target_agl = ( int ) ( target_agl / inc ) * inc + inc;
980 if ( fgGetString("/sim/startup/units") == "feet" ) {
981 target_alt *= SG_FEET_TO_METER;
982 target_agl *= SG_FEET_TO_METER;
985 TargetAltitude = target_alt;
986 TargetAGL = target_agl;
988 if ( fgGetString("/sim/startup/units") == "feet" )
989 target_alt *= SG_METER_TO_FEET;
990 if ( fgGetString("/sim/startup/units") == "feet" )
991 target_agl *= SG_METER_TO_FEET;
993 if ( altitude_mode == FG_ALTITUDE_LOCK ) {
994 MakeTargetAltitudeStr( target_alt );
995 } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
996 MakeTargetAltitudeStr( target_agl );
999 update_old_control_values();
1003 void FGAutopilot::HeadingAdjust( double inc ) {
1004 if ( heading_mode != FG_DG_HEADING_LOCK
1005 && heading_mode != FG_TRUE_HEADING_LOCK )
1007 heading_mode = FG_DG_HEADING_LOCK;
1010 if ( heading_mode == FG_DG_HEADING_LOCK ) {
1011 double target = ( int ) ( DGTargetHeading / inc ) * inc + inc;
1012 DGTargetHeading = NormalizeDegrees( target );
1014 double target = ( int ) ( TargetHeading / inc ) * inc + inc;
1015 TargetHeading = NormalizeDegrees( target );
1018 update_old_control_values();
1022 void FGAutopilot::HeadingSet( double new_heading ) {
1023 if( heading_mode == FG_TRUE_HEADING_LOCK ) {
1024 new_heading = NormalizeDegrees( new_heading );
1025 TargetHeading = new_heading;
1026 MakeTargetHeadingStr( TargetHeading );
1028 heading_mode = FG_DG_HEADING_LOCK;
1030 new_heading = NormalizeDegrees( new_heading );
1031 DGTargetHeading = new_heading;
1032 // following cast needed ambiguous plib
1033 // ApHeadingDialogInput -> setValue ((float)APData->TargetHeading );
1034 MakeTargetHeadingStr( DGTargetHeading );
1036 update_old_control_values();
1039 void FGAutopilot::AutoThrottleAdjust( double inc ) {
1040 double target = ( int ) ( TargetSpeed / inc ) * inc + inc;
1042 TargetSpeed = target;
1046 void FGAutopilot::set_AutoThrottleEnabled( bool value ) {
1047 auto_throttle = value;
1049 if ( auto_throttle == true ) {
1050 TargetSpeed = fgGetDouble("/velocities/airspeed-kt");
1051 speed_error_accum = 0.0;
1054 update_old_control_values();
1055 SG_LOG( SG_COCKPIT, SG_INFO, " fgAPSetAutoThrottle: ("
1056 << auto_throttle << ") " << TargetSpeed );
1062 ////////////////////////////////////////////////////////////////////////
1063 // Kludged methods for tying to properties.
1065 // These should change eventually; they all used to be static
1067 ////////////////////////////////////////////////////////////////////////
1070 * Get the autopilot altitude lock (true=on).
1073 FGAutopilot::getAPAltitudeLock () const
1075 return (get_AltitudeEnabled() &&
1077 == FGAutopilot::FG_ALTITUDE_LOCK);
1082 * Set the autopilot altitude lock (true=on).
1085 FGAutopilot::setAPAltitudeLock (bool lock)
1088 set_AltitudeMode(FGAutopilot::FG_ALTITUDE_LOCK);
1089 if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_LOCK)
1090 set_AltitudeEnabled(lock);
1095 * Get the autopilot target altitude in feet.
1098 FGAutopilot::getAPAltitude () const
1100 return get_TargetAltitude() * SG_METER_TO_FEET;
1105 * Set the autopilot target altitude in feet.
1108 FGAutopilot::setAPAltitude (double altitude)
1110 set_TargetAltitude( altitude * SG_FEET_TO_METER );
1114 * Get the autopilot altitude lock (true=on).
1117 FGAutopilot::getAPGSLock () const
1119 return (get_AltitudeEnabled() &&
1121 == FGAutopilot::FG_ALTITUDE_GS1));
1126 * Set the autopilot altitude lock (true=on).
1129 FGAutopilot::setAPGSLock (bool lock)
1132 set_AltitudeMode(FGAutopilot::FG_ALTITUDE_GS1);
1133 if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_GS1)
1134 set_AltitudeEnabled(lock);
1139 * Get the autopilot terrain lock (true=on).
1142 FGAutopilot::getAPTerrainLock () const
1144 return (get_AltitudeEnabled() &&
1146 == FGAutopilot::FG_ALTITUDE_TERRAIN));
1151 * Set the autopilot terrain lock (true=on).
1154 FGAutopilot::setAPTerrainLock (bool lock)
1157 set_AltitudeMode(FGAutopilot::FG_ALTITUDE_TERRAIN);
1158 set_TargetAGL(fgGetFloat("/position/altitude-agl-ft") *
1161 if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_TERRAIN)
1162 set_AltitudeEnabled(lock);
1167 * Get the autopilot target altitude in feet.
1170 FGAutopilot::getAPClimb () const
1172 return get_TargetClimbRate() * SG_METER_TO_FEET;
1177 * Set the autopilot target altitude in feet.
1180 FGAutopilot::setAPClimb (double rate)
1182 set_TargetClimbRate( rate * SG_FEET_TO_METER );
1187 * Get the autopilot heading lock (true=on).
1190 FGAutopilot::getAPHeadingLock () const
1193 (get_HeadingEnabled() &&
1194 get_HeadingMode() == DEFAULT_AP_HEADING_LOCK);
1199 * Set the autopilot heading lock (true=on).
1202 FGAutopilot::setAPHeadingLock (bool lock)
1205 set_HeadingMode(DEFAULT_AP_HEADING_LOCK);
1206 if (get_HeadingMode() == DEFAULT_AP_HEADING_LOCK)
1207 set_HeadingEnabled(lock);
1212 * Get the autopilot heading bug in degrees.
1215 FGAutopilot::getAPHeadingBug () const
1217 return get_DGTargetHeading();
1222 * Set the autopilot heading bug in degrees.
1225 FGAutopilot::setAPHeadingBug (double heading)
1227 set_DGTargetHeading( heading );
1232 * Get the autopilot wing leveler lock (true=on).
1235 FGAutopilot::getAPWingLeveler () const
1238 (get_HeadingEnabled() &&
1239 get_HeadingMode() == FGAutopilot::FG_TC_HEADING_LOCK);
1244 * Set the autopilot wing leveler lock (true=on).
1247 FGAutopilot::setAPWingLeveler (bool lock)
1250 set_HeadingMode(FGAutopilot::FG_TC_HEADING_LOCK);
1251 if (get_HeadingMode() == FGAutopilot::FG_TC_HEADING_LOCK)
1252 set_HeadingEnabled(lock);
1256 * Return true if the autopilot is locked to NAV1.
1259 FGAutopilot::getAPNAV1Lock () const
1262 (get_HeadingEnabled() &&
1263 get_HeadingMode() == FGAutopilot::FG_HEADING_NAV1);
1268 * Set the autopilot NAV1 lock.
1271 FGAutopilot::setAPNAV1Lock (bool lock)
1274 set_HeadingMode(FGAutopilot::FG_HEADING_NAV1);
1275 if (get_HeadingMode() == FGAutopilot::FG_HEADING_NAV1)
1276 set_HeadingEnabled(lock);
1280 * Get the autopilot autothrottle lock.
1283 FGAutopilot::getAPAutoThrottleLock () const
1285 return get_AutoThrottleEnabled();
1290 * Set the autothrottle lock.
1293 FGAutopilot::setAPAutoThrottleLock (bool lock)
1295 set_AutoThrottleEnabled(lock);
1301 FGAutopilot::getAPRudderControl () const
1303 if (getAPHeadingLock())
1304 return get_TargetHeading();
1306 return globals->get_controls()->get_rudder();
1311 FGAutopilot::setAPRudderControl (double value)
1313 if (getAPHeadingLock()) {
1314 SG_LOG(SG_GENERAL, SG_DEBUG, "setAPRudderControl " << value );
1315 value -= get_TargetHeading();
1316 HeadingAdjust(value < 0.0 ? -1.0 : 1.0);
1318 globals->get_controls()->set_rudder(value);
1324 FGAutopilot::getAPElevatorControl () const
1326 if (getAPAltitudeLock())
1327 return get_TargetAltitude();
1329 return globals->get_controls()->get_elevator();
1334 FGAutopilot::setAPElevatorControl (double value)
1336 if (value != 0 && getAPAltitudeLock()) {
1337 SG_LOG(SG_GENERAL, SG_DEBUG, "setAPElevatorControl " << value );
1338 value -= get_TargetAltitude();
1339 AltitudeAdjust(value < 0.0 ? 100.0 : -100.0);
1341 globals->get_controls()->set_elevator(value);
1347 FGAutopilot::getAPThrottleControl () const
1349 if (getAPAutoThrottleLock())
1350 return 0.0; // always resets
1352 return globals->get_controls()->get_throttle(0);
1357 FGAutopilot::setAPThrottleControl (double value)
1359 if (getAPAutoThrottleLock())
1360 AutoThrottleAdjust(value < 0.0 ? -0.01 : 0.01);
1362 globals->get_controls()->set_throttle(FGControls::ALL_ENGINES, value);
1365 // end of newauto.cxx