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);
244 terrain_follow_factor = fgGetNode("/autopilot/config/terrain-follow-factor", true);
246 current_throttle = fgGetNode("/controls/engines/engine/throttle");
248 // initialize config properties with defaults (in case config isn't there)
249 if ( TargetClimbRate->getFloatValue() < 1 )
250 fgSetFloat( "/autopilot/config/target-climb-rate-fpm", 500);
251 if ( TargetDescentRate->getFloatValue() < 1 )
252 fgSetFloat( "/autopilot/config/target-descent-rate-fpm", 1000 );
253 if ( min_climb->getFloatValue() < 1)
254 fgSetFloat( "/autopilot/config/min-climb-speed-kt", 70 );
255 if (best_climb->getFloatValue() < 1)
256 fgSetFloat( "/autopilot/config/best-climb-speed-kt", 120 );
257 if (elevator_adj_factor->getFloatValue() < 1)
258 fgSetFloat( "/autopilot/config/elevator-adj-factor", 5000 );
259 if ( integral_contrib->getFloatValue() < 0.0000001 )
260 fgSetFloat( "/autopilot/config/integral-contribution", 0.01 );
261 if ( zero_pitch_throttle->getFloatValue() < 0.0000001 )
262 fgSetFloat( "/autopilot/config/zero-pitch-throttle", 0.60 );
263 if ( zero_pitch_trim_full_throttle->getFloatValue() < 0.0000001 )
264 fgSetFloat( "/autopilot/config/zero-pitch-trim-full-throttle", 0.15 );
265 if ( max_aileron_node->getFloatValue() < 0.0000001 )
266 fgSetFloat( "/autopilot/config/max-aileron", 0.2 );
267 if ( max_roll_node->getFloatValue() < 0.0000001 )
268 fgSetFloat( "/autopilot/config/max-roll-deg", 20 );
269 if ( roll_out_node->getFloatValue() < 0.0000001 )
270 fgSetFloat( "/autopilot/config/roll-out-deg", 20 );
271 if ( roll_out_smooth_node->getFloatValue() < 0.0000001 )
272 fgSetFloat( "/autopilot/config/roll-out-smooth-deg", 10 );
273 if (terrain_follow_factor->getFloatValue() < 1)
274 fgSetFloat( "/autopilot/config/terrain-follow-factor", 16 );
277 heading_hold = false ; // turn the heading hold off
278 altitude_hold = false ; // turn the altitude hold off
279 auto_throttle = false ; // turn the auto throttle off
280 heading_mode = DEFAULT_AP_HEADING_LOCK;
281 altitude_mode = DEFAULT_AP_ALTITUDE_LOCK;
283 DGTargetHeading = fgGetDouble("/autopilot/settings/heading-bug-deg");
284 TargetHeading = fgGetDouble("/autopilot/settings/heading-bug-deg");
285 TargetAltitude = fgGetDouble("/autopilot/settings/altitude-ft") * SG_FEET_TO_METER;
287 // Initialize target location to startup location
288 old_lat = latitude_node->getDoubleValue();
289 old_lon = longitude_node->getDoubleValue();
290 // set_WayPoint( old_lon, old_lat, 0.0, "default" );
292 MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
294 alt_error_accum = 0.0;
295 climb_error_accum = 0.0;
297 MakeTargetAltitudeStr( TargetAltitude );
298 MakeTargetHeadingStr( TargetHeading );
300 // These eventually need to be read from current_aircaft somehow.
302 // the maximum roll, in Deg
305 // the deg from heading to start rolling out at, in Deg
308 // Smoothing distance for alerion control
311 // Hardwired for now should be in options
312 // 25% max control variablilty 0.5 / 2.0
313 disengage_threshold = 1.0;
315 // set default aileron max deflection
318 #if !defined( USING_SLIDER_CLASS )
319 MaxRollAdjust = 2 * MaxRoll;
320 RollOutAdjust = 2 * RollOut;
321 //MaxAileronAdjust = 2 * MaxAileron;
322 RollOutSmoothAdjust = 2 * RollOutSmooth;
323 #endif // !defined( USING_SLIDER_CLASS )
325 update_old_control_values();
331 // Autopilot control property get/set bindings
332 fgTie("/autopilot/locks/altitude", this,
333 &FGAutopilot::getAPAltitudeLock, &FGAutopilot::setAPAltitudeLock);
334 fgSetArchivable("/autopilot/locks/altitude");
335 fgTie("/autopilot/settings/altitude-ft", this,
336 &FGAutopilot::getAPAltitude, &FGAutopilot::setAPAltitude);
337 fgSetArchivable("/autopilot/settings/altitude-ft");
338 fgTie("/autopilot/locks/glide-slope", this,
339 &FGAutopilot::getAPGSLock, &FGAutopilot::setAPGSLock);
340 fgSetArchivable("/autopilot/locks/glide-slope");
341 fgSetDouble("/autopilot/settings/altitude-ft", 3000.0f);
342 fgTie("/autopilot/locks/terrain", this,
343 &FGAutopilot::getAPTerrainLock, &FGAutopilot::setAPTerrainLock);
344 fgSetArchivable("/autopilot/locks/terrain");
345 fgTie("/autopilot/settings/climb-rate-fpm", this,
346 &FGAutopilot::getAPClimb, &FGAutopilot::setAPClimb, false);
347 fgSetArchivable("/autopilot/settings/climb-rate-fpm");
348 fgTie("/autopilot/locks/heading", this,
349 &FGAutopilot::getAPHeadingLock, &FGAutopilot::setAPHeadingLock);
350 fgSetArchivable("/autopilot/locks/heading");
352 fgTie("/autopilot/settings/heading-bug-deg", this,
353 &FGAutopilot::getAPHeadingBug, &FGAutopilot::setAPHeadingBug);
354 fgSetArchivable("/autopilot/settings/heading-bug-deg");
355 fgSetDouble("/autopilot/settings/heading-bug-deg", 0.0f);
357 fgTie("/autopilot/settings/waypoint", this,
358 &FGAutopilot::getAPwaypoint, &FGAutopilot::setAPwaypoint);
359 fgSetArchivable("/autopilot/settings/waypoint");
360 fgSetString("/autopilot/settings/waypoint", "");
362 fgTie("/autopilot/locks/wing-leveler", this,
363 &FGAutopilot::getAPWingLeveler, &FGAutopilot::setAPWingLeveler);
364 fgSetArchivable("/autopilot/locks/wing-leveler");
365 fgTie("/autopilot/locks/nav[0]", this,
366 &FGAutopilot::getAPNAV1Lock, &FGAutopilot::setAPNAV1Lock);
367 fgSetArchivable("/autopilot/locks/nav[0]");
368 fgTie("/autopilot/locks/auto-throttle", this,
369 &FGAutopilot::getAPAutoThrottleLock,
370 &FGAutopilot::setAPAutoThrottleLock);
371 fgSetArchivable("/autopilot/locks/auto-throttle");
372 fgTie("/autopilot/control-overrides/rudder", this,
373 &FGAutopilot::getAPRudderControl,
374 &FGAutopilot::setAPRudderControl);
375 fgSetArchivable("/autopilot/control-overrides/rudder");
376 fgTie("/autopilot/control-overrides/elevator", this,
377 &FGAutopilot::getAPElevatorControl,
378 &FGAutopilot::setAPElevatorControl);
379 fgSetArchivable("/autopilot/control-overrides/elevator");
380 fgTie("/autopilot/control-overrides/throttle", this,
381 &FGAutopilot::getAPThrottleControl,
382 &FGAutopilot::setAPThrottleControl);
383 fgSetArchivable("/autopilot/control-overrides/throttle");
387 FGAutopilot::unbind ()
391 // Reset the autopilot system
392 void FGAutopilot::reset() {
394 heading_hold = false ; // turn the heading hold off
395 altitude_hold = false ; // turn the altitude hold off
396 auto_throttle = false ; // turn the auto throttle off
397 heading_mode = DEFAULT_AP_HEADING_LOCK;
399 // TargetHeading = 0.0; // default direction, due north
400 MakeTargetHeadingStr( TargetHeading );
402 // TargetAltitude = 3000; // default altitude in meters
403 MakeTargetAltitudeStr( TargetAltitude );
405 alt_error_accum = 0.0;
406 climb_error_accum = 0.0;
408 update_old_control_values();
410 sprintf( NewTgtAirportId, "%s", fgGetString("/sim/presets/airport-id") );
412 MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
416 static double NormalizeDegrees( double Input ) {
417 // normalize the input to the range (-180,180]
418 // Input should not be greater than -360 to 360.
419 // Current rules send the output to an undefined state.
420 while ( Input > 180.0 ) { Input -= 360.0; }
421 while ( Input <= -180.0 ) { Input += 360.0; }
426 static double LinearExtrapolate( double x, double x1, double y1, double x2, double y2 ) {
427 // This procedure extrapolates the y value for the x posistion on a line defined by x1,y1; x2,y2
428 //assert(x1 != x2); // Divide by zero error. Cold abort for now
431 // static double y = 0.0;
432 // double dx = x2 -x1;
433 // if( (dx < -SG_EPSILON ) || ( dx > SG_EPSILON ) )
436 double m, b, y; // the constants to find in y=mx+b
439 m = ( y2 - y1 ) / ( x2 - x1 ); // calculate the m
441 b = y1 - m * x1; // calculate the b
443 y = m * x + b; // the final calculation
453 FGAutopilot::update (double dt)
455 // Remove the following lines when the calling funcitons start
456 // passing in the data pointer
458 // get control settings
460 double lat = latitude_node->getDoubleValue();
461 double lon = longitude_node->getDoubleValue();
462 double alt = altitude_node->getDoubleValue() * SG_FEET_TO_METER;
464 // get config settings
465 MaxAileron = max_aileron_node->getDoubleValue();
466 MaxRoll = max_roll_node->getDoubleValue();
467 RollOut = roll_out_node->getDoubleValue();
468 RollOutSmooth = roll_out_smooth_node->getDoubleValue();
470 SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run() lat = " << lat <<
471 " lon = " << lon << " alt = " << alt );
473 #ifdef FG_FORCE_AUTO_DISENGAGE
474 // see if somebody else has changed them
475 if( fabs(aileron - old_aileron) > disengage_threshold ||
476 fabs(elevator - old_elevator) > disengage_threshold ||
477 fabs(elevator_trim - old_elevator_trim) >
478 disengage_threshold ||
479 fabs(rudder - old_rudder) > disengage_threshold )
481 // if controls changed externally turn autopilot off
482 waypoint_hold = false ; // turn the target hold off
483 heading_hold = false ; // turn the heading hold off
484 altitude_hold = false ; // turn the altitude hold off
485 terrain_follow = false; // turn the terrain_follow hold off
486 // auto_throttle = false; // turn the auto_throttle off
488 // stash this runs control settings
489 old_aileron = aileron;
490 old_elevator = elevator;
491 old_elevator_trim = elevator_trim;
499 if ( heading_hold == true ) {
500 if ( heading_mode == FG_DG_HEADING_LOCK ) {
501 double dg_error = heading_node->getDoubleValue()
502 - dg_heading_node->getDoubleValue();
503 TargetHeading = DGTargetHeading + dg_error;
504 // cout << "dg_error = " << dg_error << endl;
505 while ( TargetHeading < 0.0 ) { TargetHeading += 360.0; }
506 while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
507 MakeTargetHeadingStr( TargetHeading );
508 } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
509 // we don't set a specific target heading in
510 // TC_HEADING_LOCK mode, we instead try to keep the turn
511 // coordinator zero'd
512 } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
513 // leave "true" target heading as is
514 while ( TargetHeading < 0.0 ) { TargetHeading += 360.0; }
515 while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
516 MakeTargetHeadingStr( TargetHeading );
517 } else if ( heading_mode == FG_HEADING_NAV1 ) {
518 // track the NAV1 heading needle deflection
520 // determine our current radial position relative to the
521 // navaid in "true" heading.
522 double cur_radial = current_radiostack->get_navcom1()->get_nav_heading();
523 if ( current_radiostack->get_navcom1()->get_nav_loc() ) {
524 // ILS localizers radials are already "true" in our
527 cur_radial += current_radiostack->get_navcom1()->get_nav_magvar();
529 if ( current_radiostack->get_navcom1()->get_nav_from_flag() ) {
531 while ( cur_radial >= 360.0 ) { cur_radial -= 360.0; }
534 // determine the target radial in "true" heading
535 double tgt_radial = current_radiostack->get_navcom1()->get_nav_radial();
536 if ( current_radiostack->get_navcom1()->get_nav_loc() ) {
537 // ILS localizers radials are already "true" in our
540 // VOR radials need to have that vor's offset added in
541 tgt_radial += current_radiostack->get_navcom1()->get_nav_magvar();
544 // determine the heading adjustment needed.
546 current_radiostack->get_navcom1()->get_nav_heading_needle_deflection()
547 * (current_radiostack->get_navcom1()->get_nav_loc_dist() * SG_METER_TO_NM);
548 SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
550 // clamp closer when inside cone when beyond 5km...
551 if (current_radiostack->get_navcom1()->get_nav_loc_dist() > 5000) {
552 double clamp_angle = fabs(current_radiostack->get_navcom1()->get_nav_heading_needle_deflection()) * 3;
553 if (clamp_angle < 30)
554 SG_CLAMP_RANGE( adjustment, -clamp_angle, clamp_angle);
557 // determine the target heading to fly to intercept the
559 TargetHeading = tgt_radial + adjustment;
560 while ( TargetHeading < 0.0 ) { TargetHeading += 360.0; }
561 while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
563 MakeTargetHeadingStr( TargetHeading );
564 } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
565 // update target heading to waypoint
567 double wp_course, wp_distance;
569 #ifdef DO_fgAP_CORRECTED_COURSE
570 // compute course made good
571 // this needs lots of special casing before use
572 double course, reverse, distance, corrected_course;
573 // need to test for iter
574 geo_inverse_wgs_84( 0, //fgAPget_altitude(),
582 #endif // DO_fgAP_CORRECTED_COURSE
584 // compute course to way_point
585 // need to test for iter
586 SGWayPoint wp = globals->get_route()->get_first();
587 wp.CourseAndDistance( lon, lat, alt,
588 &wp_course, &wp_distance );
590 #ifdef DO_fgAP_CORRECTED_COURSE
591 corrected_course = course - wp_course;
592 if( fabs(corrected_course) > 0.1 )
593 printf("fgAP: course %f wp_course %f %f %f\n",
594 course, wp_course, fabs(corrected_course),
596 #endif // DO_fgAP_CORRECTED_COURSE
598 if ( wp_distance > 100 ) {
599 // corrected_course = course - wp_course;
600 TargetHeading = NormalizeDegrees(wp_course);
602 // pop off this waypoint from the list
603 if ( globals->get_route()->size() ) {
604 globals->get_route()->delete_first();
607 // see if there are more waypoints on the list
608 if ( globals->get_route()->size() ) {
610 set_HeadingMode( FG_HEADING_WAYPOINT );
613 heading_mode = DEFAULT_AP_HEADING_LOCK;
614 // use current heading
615 TargetHeading = heading_node->getDoubleValue();
618 MakeTargetHeadingStr( TargetHeading );
619 // Force this just in case
620 TargetDistance = wp_distance;
621 MakeTargetWPStr( wp_distance );
624 if ( heading_mode == FG_TC_HEADING_LOCK ) {
625 // drive the turn coordinator to zero
627 fgGetDouble("/instrumentation/turn-indicator/indicated-turn-rate");
628 double AileronSet = -turn / 2.0;
629 SG_CLAMP_RANGE( AileronSet, -1.0, 1.0 );
630 globals->get_controls()->set_aileron( AileronSet );
631 globals->get_controls()->set_rudder( AileronSet / 4.0 );
633 // steer towards the target heading
641 = NormalizeDegrees( TargetHeading
642 - heading_node->getDoubleValue() );
643 // figure out how far off we are from desired heading
645 // Now it is time to deterime how far we should be rolled.
646 SG_LOG( SG_AUTOPILOT, SG_DEBUG,
647 "Heading = " << heading_node->getDoubleValue() <<
648 " TargetHeading = " << TargetHeading <<
649 " RelHeading = " << RelHeading );
651 // Check if we are further from heading than the roll out point
652 if ( fabs( RelHeading ) > RollOut ) {
653 // set Target Roll to Max in desired direction
654 if ( RelHeading < 0 ) {
655 TargetRoll = 0 - MaxRoll;
657 TargetRoll = MaxRoll;
660 // We have to calculate the Target roll
662 // This calculation engine thinks that the Target roll
663 // should be a line from (RollOut,MaxRoll) to (-RollOut,
664 // -MaxRoll) I hope this works well. If I get ambitious
665 // some day this might become a fancier curve or
668 TargetRoll = LinearExtrapolate( RelHeading, -RollOut,
673 // Target Roll has now been Found.
675 // Compare Target roll to Current Roll, Generate Rel Roll
677 SG_LOG( SG_COCKPIT, SG_BULK, "TargetRoll: " << TargetRoll );
679 RelRoll = NormalizeDegrees( TargetRoll
680 - roll_node->getDoubleValue() );
682 // Check if we are further from heading than the roll out
684 if ( fabs( RelRoll ) > RollOutSmooth ) {
685 // set Target Roll to Max in desired direction
687 AileronSet = 0 - MaxAileron;
689 AileronSet = MaxAileron;
692 AileronSet = LinearExtrapolate( RelRoll, -RollOutSmooth,
698 globals->get_controls()->set_aileron( AileronSet );
699 globals->get_controls()->set_rudder( AileronSet / 4.0 );
700 // controls.set_rudder( 0.0 );
705 if ( altitude_hold ) {
707 double speed, max_climb, error;
708 double prop_error, int_error;
709 double prop_adj, int_adj, total_adj;
711 if ( altitude_mode == FG_ALTITUDE_LOCK ) {
714 fgGetDouble("/instrumentation/altimeter/indicated-altitude-ft") * SG_FEET_TO_METER ) * 8.0;
715 } else if ( altitude_mode == FG_TRUE_ALTITUDE_LOCK ) {
716 climb_rate = ( TargetAltitude - alt ) * 8.0;
717 } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
718 double x = current_radiostack->get_navcom1()->get_nav_gs_dist();
719 double y = (altitude_node->getDoubleValue()
720 - current_radiostack->get_navcom1()->get_nav_elev()) * SG_FEET_TO_METER;
721 double current_angle = atan2( y, x ) * SGD_RADIANS_TO_DEGREES;
723 double target_angle = current_radiostack->get_navcom1()->get_nav_target_gs();
725 double gs_diff = target_angle - current_angle;
727 // convert desired vertical path angle into a climb rate
728 double des_angle = current_angle - 10 * gs_diff;
730 // convert to meter/min
731 double horiz_vel = cur_fdm_state->get_V_ground_speed()
732 * SG_FEET_TO_METER * 60.0;
733 climb_rate = -sin( des_angle * SGD_DEGREES_TO_RADIANS ) * horiz_vel;
734 /* climb_error_accum += gs_diff * 2.0; */
735 /* climb_rate = gs_diff * 200.0 + climb_error_accum; */
736 } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
737 // brain dead ground hugging with no look ahead
739 ( TargetAGL - altitude_agl_node->getDoubleValue()
741 * terrain_follow_factor->getFloatValue();
743 // just try to zero out rate of climb ...
749 if ( speed < min_climb->getFloatValue() ) {
751 } else if ( speed < best_climb->getFloatValue() ) {
752 max_climb = ((best_climb->getFloatValue()
753 - min_climb->getFloatValue())
754 - (best_climb->getFloatValue() - speed))
755 * fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER)
756 / (best_climb->getFloatValue() - min_climb->getFloatValue());
758 max_climb = ( speed - best_climb->getFloatValue() ) * 10.0
759 + fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
762 // this first one could be optional if we wanted to allow
763 // better climb performance assuming we have the airspeed to
766 fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER) ) {
768 = fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
771 if ( climb_rate > max_climb ) {
772 climb_rate = max_climb;
776 -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER) ) {
778 = -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER);
781 error = vertical_speed_node->getDoubleValue() * 60
782 - climb_rate * SG_METER_TO_FEET;
784 // accumulate the error under the curve ... this really should
786 alt_error_accum += error;
788 // calculate integral error, and adjustment amount
789 int_error = alt_error_accum;
790 // printf("error = %.2f int_error = %.2f\n", error, int_error);
792 // scale elev_adj_factor by speed of aircraft in relation to min climb
793 double elev_adj_factor = elevator_adj_factor->getFloatValue();
795 pow(float(speed / min_climb->getFloatValue()), 3.0f);
797 int_adj = int_error / elev_adj_factor;
799 // caclulate proportional error
801 prop_adj = prop_error / elev_adj_factor;
803 total_adj = ((double) 1.0 - (double) integral_contrib->getFloatValue()) * prop_adj
804 + (double) integral_contrib->getFloatValue() * int_adj;
806 // stop on autopilot trim at 30% +/-
807 // if ( total_adj > 0.3 ) {
809 // } else if ( total_adj < -0.3 ) {
813 // adjust for throttle pitch gain
814 total_adj += ((current_throttle->getFloatValue() - zero_pitch_throttle->getFloatValue())
815 / (1 - zero_pitch_throttle->getFloatValue()))
816 * zero_pitch_trim_full_throttle->getFloatValue();
818 globals->get_controls()->set_elevator_trim( total_adj );
822 if ( auto_throttle ) {
824 double prop_error, int_error;
825 double prop_adj, int_adj, total_adj;
827 error = TargetSpeed - get_speed();
829 // accumulate the error under the curve ... this really should
831 speed_error_accum += error;
832 if ( speed_error_accum > 2000.0 ) {
833 speed_error_accum = 2000.0;
835 else if ( speed_error_accum < -2000.0 ) {
836 speed_error_accum = -2000.0;
839 // calculate integral error, and adjustment amount
840 int_error = speed_error_accum;
842 // printf("error = %.2f int_error = %.2f\n", error, int_error);
843 int_adj = int_error / 200.0;
845 // caclulate proportional error
847 prop_adj = 0.5 + prop_error / 50.0;
849 total_adj = 0.9 * prop_adj + 0.1 * int_adj;
850 if ( total_adj > 1.0 ) {
853 else if ( total_adj < 0.0 ) {
857 globals->get_controls()->set_throttle( FGControls::ALL_ENGINES,
861 #ifdef THIS_CODE_IS_NOT_USED
862 if (Mode == 2) // Glide slope hold
867 // First, calculate Relative slope and normalize it
868 RelSlope = NormalizeDegrees( TargetSlope - get_pitch());
870 // Now calculate the elevator offset from current angle
871 if ( abs(RelSlope) > SlopeSmooth )
873 if ( RelSlope < 0 ) // set RelElevator to max in the correct direction
874 RelElevator = -MaxElevator;
876 RelElevator = MaxElevator;
880 RelElevator = LinearExtrapolate(RelSlope,-SlopeSmooth,-MaxElevator,SlopeSmooth,MaxElevator);
883 fgElevMove(RelElevator);
886 #endif // THIS_CODE_IS_NOT_USED
888 // stash this runs control settings
889 // update_old_control_values();
890 old_aileron = globals->get_controls()->get_aileron();
891 old_elevator = globals->get_controls()->get_elevator();
892 old_elevator_trim = globals->get_controls()->get_elevator_trim();
893 old_rudder = globals->get_controls()->get_rudder();
895 // for cross track error
900 SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run( returns )" );
904 void FGAutopilot::set_HeadingMode( fgAutoHeadingMode mode ) {
907 if ( heading_mode == FG_DG_HEADING_LOCK ) {
908 // use current heading bug value
909 } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
910 // set autopilot to hold a zero turn (as reported by the TC)
911 } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
912 // set heading hold to current heading
913 TargetHeading = heading_node->getDoubleValue();
914 } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
915 if ( globals->get_route()->size() ) {
916 double course, distance;
918 old_lat = latitude_node->getDoubleValue();
919 old_lon = longitude_node->getDoubleValue();
921 waypoint = globals->get_route()->get_first();
922 waypoint.CourseAndDistance( longitude_node->getDoubleValue(),
923 latitude_node->getDoubleValue(),
924 altitude_node->getDoubleValue()
926 &course, &distance );
927 TargetHeading = course;
928 TargetDistance = distance;
929 MakeTargetLatLonStr( waypoint.get_target_lat(),
930 waypoint.get_target_lon() );
931 MakeTargetWPStr( distance );
933 if ( waypoint.get_target_alt() > 0.0 ) {
934 TargetAltitude = waypoint.get_target_alt();
935 altitude_mode = DEFAULT_AP_ALTITUDE_LOCK;
936 set_AltitudeEnabled( true );
937 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
940 SG_LOG( SG_COCKPIT, SG_INFO, " set_HeadingMode: ( "
941 << get_TargetLatitude() << " "
942 << get_TargetLongitude() << " ) "
945 // no more way points, default to heading lock.
946 heading_mode = FG_TC_HEADING_LOCK;
950 MakeTargetHeadingStr( TargetHeading );
951 update_old_control_values();
955 void FGAutopilot::set_AltitudeMode( fgAutoAltitudeMode mode ) {
956 altitude_mode = mode;
958 alt_error_accum = 0.0;
961 if ( altitude_mode == DEFAULT_AP_ALTITUDE_LOCK ) {
962 if ( TargetAltitude < altitude_agl_node->getDoubleValue()
963 * SG_FEET_TO_METER ) {
966 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
967 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
969 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
971 } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
972 climb_error_accum = 0.0;
974 } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
975 TargetAGL = altitude_agl_node->getDoubleValue() * SG_FEET_TO_METER;
977 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
978 MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
980 MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
984 update_old_control_values();
985 SG_LOG( SG_COCKPIT, SG_INFO, " set_AltitudeMode():" );
989 void FGAutopilot::AltitudeSet( double new_altitude ) {
990 double target_alt = new_altitude;
991 altitude_mode = DEFAULT_AP_ALTITUDE_LOCK;
993 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
994 target_alt = new_altitude * SG_FEET_TO_METER;
997 if( target_alt < globals->get_scenery()->get_cur_elev() ) {
998 target_alt = globals->get_scenery()->get_cur_elev();
1001 TargetAltitude = target_alt;
1003 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
1004 target_alt *= SG_METER_TO_FEET;
1006 // ApAltitudeDialogInput->setValue((float)target_alt);
1007 MakeTargetAltitudeStr( target_alt );
1009 update_old_control_values();
1013 void FGAutopilot::AltitudeAdjust( double inc )
1015 double target_alt, target_agl;
1017 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
1018 target_alt = TargetAltitude * SG_METER_TO_FEET;
1019 target_agl = TargetAGL * SG_METER_TO_FEET;
1021 target_alt = TargetAltitude;
1022 target_agl = TargetAGL;
1025 if ( fabs((int)(target_alt / inc) * inc - target_alt) < SG_EPSILON ) {
1028 target_alt = ( int ) ( target_alt / inc ) * inc + inc;
1031 if ( fabs((int)(target_agl / inc) * inc - target_agl) < SG_EPSILON ) {
1034 target_agl = ( int ) ( target_agl / inc ) * inc + inc;
1037 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
1038 target_alt *= SG_FEET_TO_METER;
1039 target_agl *= SG_FEET_TO_METER;
1042 TargetAltitude = target_alt;
1043 TargetAGL = target_agl;
1045 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
1046 target_alt *= SG_METER_TO_FEET;
1047 if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
1048 target_agl *= SG_METER_TO_FEET;
1050 if ( altitude_mode == DEFAULT_AP_ALTITUDE_LOCK ) {
1051 MakeTargetAltitudeStr( target_alt );
1052 } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
1053 MakeTargetAltitudeStr( target_agl );
1056 update_old_control_values();
1060 void FGAutopilot::HeadingAdjust( double inc ) {
1061 if ( heading_mode != FG_DG_HEADING_LOCK
1062 && heading_mode != FG_TRUE_HEADING_LOCK )
1064 heading_mode = DEFAULT_AP_HEADING_LOCK;
1067 if ( heading_mode == FG_DG_HEADING_LOCK ) {
1068 double target = ( int ) ( DGTargetHeading / inc ) * inc + inc;
1069 DGTargetHeading = NormalizeDegrees( target );
1071 double target = ( int ) ( TargetHeading / inc ) * inc + inc;
1072 TargetHeading = NormalizeDegrees( target );
1075 update_old_control_values();
1079 void FGAutopilot::HeadingSet( double new_heading ) {
1080 heading_mode = DEFAULT_AP_HEADING_LOCK;
1081 if( heading_mode == FG_TRUE_HEADING_LOCK ) {
1082 new_heading = NormalizeDegrees( new_heading );
1083 TargetHeading = new_heading;
1084 MakeTargetHeadingStr( TargetHeading );
1086 heading_mode = FG_DG_HEADING_LOCK;
1088 new_heading = NormalizeDegrees( new_heading );
1089 DGTargetHeading = new_heading;
1090 // following cast needed ambiguous plib
1091 // ApHeadingDialogInput -> setValue ((float)APData->TargetHeading );
1092 MakeTargetHeadingStr( DGTargetHeading );
1094 update_old_control_values();
1097 void FGAutopilot::AutoThrottleAdjust( double inc ) {
1098 double target = ( int ) ( TargetSpeed / inc ) * inc + inc;
1100 TargetSpeed = target;
1104 void FGAutopilot::set_AutoThrottleEnabled( bool value ) {
1105 auto_throttle = value;
1107 if ( auto_throttle == true ) {
1108 TargetSpeed = fgGetDouble("/velocities/airspeed-kt");
1109 speed_error_accum = 0.0;
1112 update_old_control_values();
1113 SG_LOG( SG_COCKPIT, SG_INFO, " fgAPSetAutoThrottle: ("
1114 << auto_throttle << ") " << TargetSpeed );
1120 ////////////////////////////////////////////////////////////////////////
1121 // Kludged methods for tying to properties.
1123 // These should change eventually; they all used to be static
1125 ////////////////////////////////////////////////////////////////////////
1128 * Get the autopilot altitude lock (true=on).
1131 FGAutopilot::getAPAltitudeLock () const
1133 return (get_AltitudeEnabled() &&
1135 == DEFAULT_AP_ALTITUDE_LOCK);
1140 * Set the autopilot altitude lock (true=on).
1143 FGAutopilot::setAPAltitudeLock (bool lock)
1146 set_AltitudeMode(DEFAULT_AP_ALTITUDE_LOCK);
1147 if (get_AltitudeMode() == DEFAULT_AP_ALTITUDE_LOCK)
1148 set_AltitudeEnabled(lock);
1153 * Get the autopilot target altitude in feet.
1156 FGAutopilot::getAPAltitude () const
1158 return get_TargetAltitude() * SG_METER_TO_FEET;
1163 * Set the autopilot target altitude in feet.
1166 FGAutopilot::setAPAltitude (double altitude)
1168 set_TargetAltitude( altitude * SG_FEET_TO_METER );
1172 * Get the autopilot altitude lock (true=on).
1175 FGAutopilot::getAPGSLock () const
1177 return (get_AltitudeEnabled() &&
1179 == FGAutopilot::FG_ALTITUDE_GS1));
1184 * Set the autopilot altitude lock (true=on).
1187 FGAutopilot::setAPGSLock (bool lock)
1190 set_AltitudeMode(FGAutopilot::FG_ALTITUDE_GS1);
1191 if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_GS1)
1192 set_AltitudeEnabled(lock);
1197 * Get the autopilot terrain lock (true=on).
1200 FGAutopilot::getAPTerrainLock () const
1202 return (get_AltitudeEnabled() &&
1204 == FGAutopilot::FG_ALTITUDE_TERRAIN));
1209 * Set the autopilot terrain lock (true=on).
1212 FGAutopilot::setAPTerrainLock (bool lock)
1215 set_AltitudeMode(FGAutopilot::FG_ALTITUDE_TERRAIN);
1216 set_TargetAGL(fgGetFloat("/position/altitude-agl-ft") *
1219 if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_TERRAIN)
1220 set_AltitudeEnabled(lock);
1225 * Get the autopilot target altitude in feet.
1228 FGAutopilot::getAPClimb () const
1230 return get_TargetClimbRate() * SG_METER_TO_FEET;
1235 * Set the autopilot target altitude in feet.
1238 FGAutopilot::setAPClimb (double rate)
1240 set_TargetClimbRate( rate * SG_FEET_TO_METER );
1245 * Get the autopilot heading lock (true=on).
1248 FGAutopilot::getAPHeadingLock () const
1251 (get_HeadingEnabled() &&
1252 get_HeadingMode() == DEFAULT_AP_HEADING_LOCK);
1257 * Set the autopilot heading lock (true=on).
1260 FGAutopilot::setAPHeadingLock (bool lock)
1263 set_HeadingMode(DEFAULT_AP_HEADING_LOCK);
1264 if (get_HeadingMode() == DEFAULT_AP_HEADING_LOCK)
1265 set_HeadingEnabled(lock);
1270 * Get the autopilot heading bug in degrees.
1273 FGAutopilot::getAPHeadingBug () const
1275 return get_DGTargetHeading();
1280 * Set the autopilot heading bug in degrees.
1283 FGAutopilot::setAPHeadingBug (double heading)
1285 set_DGTargetHeading( heading );
1290 * return blank-separated string of waypoints
1293 FGAutopilot::getAPwaypoint () const
1295 static char wplist[500];
1299 // FIXME: This can cause a possible buffer overflow, EMH
1300 if ( globals->get_route()->size() > 0 ) {
1301 WPListsize = globals->get_route()->size();
1303 for (i = 0; i < globals->get_route()->size(); i++ ) {
1304 p += sprintf(p, "%5s ",
1305 globals->get_route()->get_waypoint(i).get_id().c_str() );
1310 return "none specified";
1316 * set next waypoint (if str='0', then delete next(first) waypoint)
1319 FGAutopilot::setAPwaypoint (const char * apt)
1321 if (strcmp(apt, "0")==0)
1323 SG_LOG( SG_AUTOPILOT, SG_INFO, "delete of first wp" );
1324 if ( globals->get_route()->size() )
1325 globals->get_route()->delete_first();
1329 if ( NewWaypoint( apt ) == 0)
1330 SG_LOG( SG_AUTOPILOT, SG_INFO, "Waypoint " << apt << "not in d.b." );
1333 /* SG_LOG( SG_AUTOPILOT, SG_INFO, "GOOD!" ); */
1338 * Get the autopilot wing leveler lock (true=on).
1341 FGAutopilot::getAPWingLeveler () const
1344 (get_HeadingEnabled() &&
1345 get_HeadingMode() == FGAutopilot::FG_TC_HEADING_LOCK);
1350 * Set the autopilot wing leveler lock (true=on).
1353 FGAutopilot::setAPWingLeveler (bool lock)
1356 set_HeadingMode(FGAutopilot::FG_TC_HEADING_LOCK);
1357 if (get_HeadingMode() == FGAutopilot::FG_TC_HEADING_LOCK)
1358 set_HeadingEnabled(lock);
1362 * Return true if the autopilot is locked to NAV1.
1365 FGAutopilot::getAPNAV1Lock () const
1368 (get_HeadingEnabled() &&
1369 get_HeadingMode() == FGAutopilot::FG_HEADING_NAV1);
1374 * Set the autopilot NAV1 lock.
1377 FGAutopilot::setAPNAV1Lock (bool lock)
1380 set_HeadingMode(FGAutopilot::FG_HEADING_NAV1);
1381 if (get_HeadingMode() == FGAutopilot::FG_HEADING_NAV1)
1382 set_HeadingEnabled(lock);
1386 * Get the autopilot autothrottle lock.
1389 FGAutopilot::getAPAutoThrottleLock () const
1391 return get_AutoThrottleEnabled();
1396 * Set the autothrottle lock.
1399 FGAutopilot::setAPAutoThrottleLock (bool lock)
1401 set_AutoThrottleEnabled(lock);
1407 FGAutopilot::getAPRudderControl () const
1409 if (getAPHeadingLock())
1410 return get_TargetHeading();
1412 return globals->get_controls()->get_rudder();
1417 FGAutopilot::setAPRudderControl (double value)
1419 if (getAPHeadingLock()) {
1420 SG_LOG(SG_GENERAL, SG_DEBUG, "setAPRudderControl " << value );
1421 value -= get_TargetHeading();
1422 HeadingAdjust(value < 0.0 ? -1.0 : 1.0);
1424 globals->get_controls()->set_rudder(value);
1430 FGAutopilot::getAPElevatorControl () const
1432 if (getAPAltitudeLock())
1433 return get_TargetAltitude();
1435 return globals->get_controls()->get_elevator();
1440 FGAutopilot::setAPElevatorControl (double value)
1442 if (value != 0 && getAPAltitudeLock()) {
1443 SG_LOG(SG_GENERAL, SG_DEBUG, "setAPElevatorControl " << value );
1444 value -= get_TargetAltitude();
1445 AltitudeAdjust(value < 0.0 ? 100.0 : -100.0);
1447 globals->get_controls()->set_elevator(value);
1453 FGAutopilot::getAPThrottleControl () const
1455 if (getAPAutoThrottleLock())
1456 return 0.0; // always resets
1458 return globals->get_controls()->get_throttle(0);
1463 FGAutopilot::setAPThrottleControl (double value)
1465 if (getAPAutoThrottleLock())
1466 AutoThrottleAdjust(value < 0.0 ? -0.01 : 0.01);
1468 globals->get_controls()->set_throttle(FGControls::ALL_ENGINES, value);
1471 // end of newauto.cxx