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>
38 #include <Cockpit/steam.hxx>
39 #include <Cockpit/radiostack.hxx>
40 #include <Controls/controls.hxx>
41 #include <FDM/flight.hxx>
42 #include <Main/globals.hxx>
43 #include <Scenery/scenery.hxx>
45 #include "newauto.hxx"
48 FGAutopilot *current_autopilot;
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 );
151 // cout << "distance = " << distance*SG_METER_TO_NM
152 // << " gndsp = " << get_ground_speed()
153 // << " time = " << eta
154 // << " major = " << major
155 // << " minor = " << minor
161 SGWayPoint wp2 = globals->get_route()->get_waypoint( 1 );
162 accum += wp2.get_distance();
164 double eta = accum * SG_METER_TO_NM / get_ground_speed();
165 if ( eta >= 100.0 ) { eta = 99.999; }
167 if ( eta < (1.0/6.0) ) {
168 // within 10 minutes, bump up to min/secs
172 minor = (int)((eta - (int)eta) * 60.0);
173 sprintf( TargetWP2Str, "%s %.2f NM ETA %d:%02d",
174 wp2.get_id().c_str(),
175 accum*SG_METER_TO_NM, major, minor );
180 for ( int i = 2; i < size; ++i ) {
181 accum += globals->get_route()->get_waypoint( i ).get_distance();
184 SGWayPoint wpn = globals->get_route()->get_waypoint( size - 1 );
186 double eta = accum * SG_METER_TO_NM / get_ground_speed();
187 if ( eta >= 100.0 ) { eta = 99.999; }
189 if ( eta < (1.0/6.0) ) {
190 // within 10 minutes, bump up to min/secs
194 minor = (int)((eta - (int)eta) * 60.0);
195 sprintf( TargetWP3Str, "%s %.2f NM ETA %d:%02d",
196 wpn.get_id().c_str(),
197 accum*SG_METER_TO_NM, major, minor );
202 void FGAutopilot::update_old_control_values() {
203 old_aileron = globals->get_controls()->get_aileron();
204 old_elevator = globals->get_controls()->get_elevator();
205 old_elevator_trim = globals->get_controls()->get_elevator_trim();
206 old_rudder = globals->get_controls()->get_rudder();
210 // Initialize autopilot subsystem
211 void FGAutopilot::init() {
212 SG_LOG( SG_AUTOPILOT, SG_INFO, "Init AutoPilot Subsystem" );
214 // Autopilot control property static get/set bindings
215 fgTie("/autopilot/locks/altitude", getAPAltitudeLock, setAPAltitudeLock);
216 fgSetArchivable("/autopilot/locks/altitude");
217 fgTie("/autopilot/settings/altitude-ft", getAPAltitude, setAPAltitude);
218 fgSetArchivable("/autopilot/settings/altitude-ft");
219 fgTie("/autopilot/locks/glide-slope", getAPGSLock, setAPGSLock);
220 fgSetDouble("/autopilot/settings/altitude-ft", 3000.0f);
221 fgSetArchivable("/autopilot/locks/glide-slope");
222 fgTie("/autopilot/locks/terrain", getAPTerrainLock, setAPTerrainLock);
223 fgSetArchivable("/autopilot/locks/terrain");
224 fgTie("/autopilot/settings/climb-rate-fpm", getAPClimb, setAPClimb, false);
225 fgSetArchivable("/autopilot/settings/climb-rate-fpm");
226 fgTie("/autopilot/locks/heading", getAPHeadingLock, setAPHeadingLock);
227 fgSetArchivable("/autopilot/locks/heading");
228 fgTie("/autopilot/settings/heading-bug-deg",
229 getAPHeadingBug, setAPHeadingBug);
230 fgSetArchivable("/autopilot/settings/heading-bug-deg");
231 fgSetDouble("/autopilot/settings/heading-bug-deg", 0.0f);
232 fgTie("/autopilot/locks/wing-leveler", getAPWingLeveler, setAPWingLeveler);
233 fgSetArchivable("/autopilot/locks/wing-leveler");
234 fgTie("/autopilot/locks/nav[0]", getAPNAV1Lock, setAPNAV1Lock);
235 fgSetArchivable("/autopilot/locks/nav[0]");
236 fgTie("/autopilot/locks/auto-throttle",
237 getAPAutoThrottleLock, setAPAutoThrottleLock);
238 fgSetArchivable("/autopilot/locks/auto-throttle");
239 fgTie("/autopilot/control-overrides/rudder",
240 getAPRudderControl, setAPRudderControl);
241 fgSetArchivable("/autopilot/control-overrides/rudder");
242 fgTie("/autopilot/control-overrides/elevator",
243 getAPElevatorControl, setAPElevatorControl);
244 fgSetArchivable("/autopilot/control-overrides/elevator");
245 fgTie("/autopilot/control-overrides/throttle",
246 getAPThrottleControl, setAPThrottleControl);
247 fgSetArchivable("/autopilot/control-overrides/throttle");
250 // bind data input property nodes...
251 latitude_node = fgGetNode("/position/latitude-deg", true);
252 longitude_node = fgGetNode("/position/longitude-deg", true);
253 altitude_node = fgGetNode("/position/altitude-ft", true);
254 altitude_agl_node = fgGetNode("/position/altitude-agl-ft", true);
255 vertical_speed_node = fgGetNode("/velocities/vertical-speed-fps", true);
256 heading_node = fgGetNode("/orientation/heading-deg", true);
257 roll_node = fgGetNode("/orientation/roll-deg", true);
258 pitch_node = fgGetNode("/orientation/pitch-deg", true);
260 // bind config property nodes...
262 = fgGetNode("/autopilot/config/target-climb-rate-fpm", true);
264 = fgGetNode("/autopilot/config/target-descent-rate-fpm", true);
265 min_climb = fgGetNode("/autopilot/config/min-climb-speed-kt", true);
266 best_climb = fgGetNode("/autopilot/config/best-climb-speed-kt", true);
268 = fgGetNode("/autopilot/config/elevator-adj-factor", true);
270 = fgGetNode("/autopilot/config/integral-contribution", true);
272 = fgGetNode("/autopilot/config/zero-pitch-throttle", true);
273 zero_pitch_trim_full_throttle
274 = fgGetNode("/autopilot/config/zero-pitch-trim-full-throttle", true);
275 current_throttle = fgGetNode("/controls/throttle");
277 // initialize config properties with defaults (in case config isn't there)
278 if ( TargetClimbRate->getFloatValue() < 1 )
279 fgSetFloat( "/autopilot/config/target-climb-rate-fpm", 500);
280 if ( TargetDescentRate->getFloatValue() < 1 )
281 fgSetFloat( "/autopilot/config/target-descent-rate-fpm", 1000 );
282 if ( min_climb->getFloatValue() < 1)
283 fgSetFloat( "/autopilot/config/min-climb-speed-kt", 70 );
284 if (best_climb->getFloatValue() < 1)
285 fgSetFloat( "/autopilot/config/best-climb-speed-kt", 120 );
286 if (elevator_adj_factor->getFloatValue() < 1)
287 fgSetFloat( "/autopilot/config/elevator-adj-factor", 5000 );
288 if ( integral_contrib->getFloatValue() < 0.0000001 )
289 fgSetFloat( "/autopilot/config/integral-contribution", 0.01 );
290 if ( zero_pitch_throttle->getFloatValue() < 0.0000001 )
291 fgSetFloat( "/autopilot/config/zero-pitch-throttle", 0.60 );
292 if ( zero_pitch_trim_full_throttle->getFloatValue() < 0.0000001 )
293 fgSetFloat( "/autopilot/config/zero-pitch-trim-full-throttle", 0.15 );
296 heading_hold = false ; // turn the heading hold off
297 altitude_hold = false ; // turn the altitude hold off
298 auto_throttle = false ; // turn the auto throttle off
299 heading_mode = DEFAULT_AP_HEADING_LOCK;
301 DGTargetHeading = fgGetDouble("/autopilot/settings/heading-bug-deg");
302 TargetHeading = fgGetDouble("/autopilot/settings/heading-bug-deg");
303 TargetAltitude = fgGetDouble("/autopilot/settings/altitude-ft") * SG_FEET_TO_METER;
305 // Initialize target location to startup location
306 old_lat = latitude_node->getDoubleValue();
307 old_lon = longitude_node->getDoubleValue();
308 // set_WayPoint( old_lon, old_lat, 0.0, "default" );
310 MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
312 alt_error_accum = 0.0;
313 climb_error_accum = 0.0;
315 MakeTargetAltitudeStr( TargetAltitude );
316 MakeTargetHeadingStr( TargetHeading );
318 // These eventually need to be read from current_aircaft somehow.
320 // the maximum roll, in Deg
323 // the deg from heading to start rolling out at, in Deg
326 // how far can I move the aleron from center.
329 // Smoothing distance for alerion control
332 // Hardwired for now should be in options
333 // 25% max control variablilty 0.5 / 2.0
334 disengage_threshold = 1.0;
336 #if !defined( USING_SLIDER_CLASS )
337 MaxRollAdjust = 2 * MaxRoll;
338 RollOutAdjust = 2 * RollOut;
339 MaxAileronAdjust = 2 * MaxAileron;
340 RollOutSmoothAdjust = 2 * RollOutSmooth;
341 #endif // !defined( USING_SLIDER_CLASS )
343 update_old_control_values();
348 // Reset the autopilot system
349 void FGAutopilot::reset() {
351 heading_hold = false ; // turn the heading hold off
352 altitude_hold = false ; // turn the altitude hold off
353 auto_throttle = false ; // turn the auto throttle off
354 heading_mode = DEFAULT_AP_HEADING_LOCK;
356 // TargetHeading = 0.0; // default direction, due north
357 MakeTargetHeadingStr( TargetHeading );
359 // TargetAltitude = 3000; // default altitude in meters
360 MakeTargetAltitudeStr( TargetAltitude );
362 alt_error_accum = 0.0;
363 climb_error_accum = 0.0;
365 update_old_control_values();
367 sprintf( NewTgtAirportId, "%s", fgGetString("/sim/startup/airport-id").c_str() );
369 MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
373 static double NormalizeDegrees( double Input ) {
374 // normalize the input to the range (-180,180]
375 // Input should not be greater than -360 to 360.
376 // Current rules send the output to an undefined state.
377 while ( Input > 180.0 ) { Input -= 360.0; }
378 while ( Input <= -180.0 ) { Input += 360.0; }
383 static double LinearExtrapolate( double x, double x1, double y1, double x2, double y2 ) {
384 // This procedure extrapolates the y value for the x posistion on a line defined by x1,y1; x2,y2
385 //assert(x1 != x2); // Divide by zero error. Cold abort for now
388 // static double y = 0.0;
389 // double dx = x2 -x1;
390 // if( (dx < -SG_EPSILON ) || ( dx > SG_EPSILON ) )
393 double m, b, y; // the constants to find in y=mx+b
396 m = ( y2 - y1 ) / ( x2 - x1 ); // calculate the m
398 b = y1 - m * x1; // calculate the b
400 y = m * x + b; // the final calculation
409 int FGAutopilot::run() {
410 // Remove the following lines when the calling funcitons start
411 // passing in the data pointer
413 // get control settings
415 double lat = latitude_node->getDoubleValue();
416 double lon = longitude_node->getDoubleValue();
417 double alt = altitude_node->getDoubleValue() * SG_FEET_TO_METER;
419 SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run() lat = " << lat <<
420 " lon = " << lon << " alt = " << alt );
422 #ifdef FG_FORCE_AUTO_DISENGAGE
423 // see if somebody else has changed them
424 if( fabs(aileron - old_aileron) > disengage_threshold ||
425 fabs(elevator - old_elevator) > disengage_threshold ||
426 fabs(elevator_trim - old_elevator_trim) >
427 disengage_threshold ||
428 fabs(rudder - old_rudder) > disengage_threshold )
430 // if controls changed externally turn autopilot off
431 waypoint_hold = false ; // turn the target hold off
432 heading_hold = false ; // turn the heading hold off
433 altitude_hold = false ; // turn the altitude hold off
434 terrain_follow = false; // turn the terrain_follow hold off
435 // auto_throttle = false; // turn the auto_throttle off
437 // stash this runs control settings
438 old_aileron = aileron;
439 old_elevator = elevator;
440 old_elevator_trim = elevator_trim;
448 if ( heading_hold == true ) {
449 if ( heading_mode == FG_DG_HEADING_LOCK ) {
450 // cout << "DG heading = " << FGSteam::get_DG_deg()
451 // << " DG error = " << FGSteam::get_DG_err() << endl;
453 TargetHeading = DGTargetHeading + FGSteam::get_DG_err();
454 while ( TargetHeading < 0.0 ) { TargetHeading += 360.0; }
455 while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
456 MakeTargetHeadingStr( TargetHeading );
457 } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
458 // we don't set a specific target heading in
459 // TC_HEADING_LOCK mode, we instead try to keep the turn
460 // coordinator zero'd
461 } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
462 // leave "true" target heading as is
463 while ( TargetHeading < 0.0 ) { TargetHeading += 360.0; }
464 while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
465 MakeTargetHeadingStr( TargetHeading );
466 } else if ( heading_mode == FG_HEADING_NAV1 ) {
467 // track the NAV1 heading needle deflection
469 // determine our current radial position relative to the
470 // navaid in "true" heading.
471 double cur_radial = current_radiostack->get_nav1_heading();
472 if ( current_radiostack->get_nav1_loc() ) {
473 // ILS localizers radials are already "true" in our
476 cur_radial += current_radiostack->get_nav1_magvar();
478 if ( current_radiostack->get_nav1_from_flag() ) {
480 while ( cur_radial >= 360.0 ) { cur_radial -= 360.0; }
483 // determine the target radial in "true" heading
484 double tgt_radial = current_radiostack->get_nav1_radial();
485 if ( current_radiostack->get_nav1_loc() ) {
486 // ILS localizers radials are already "true" in our
489 // VOR radials need to have that vor's offset added in
490 tgt_radial += current_radiostack->get_nav1_magvar();
493 // determine the heading adjustment needed.
495 current_radiostack->get_nav1_heading_needle_deflection()
496 * (current_radiostack->get_nav1_loc_dist() * SG_METER_TO_NM);
497 SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
499 // determine the target heading to fly to intercept the
501 TargetHeading = tgt_radial + adjustment;
502 while ( TargetHeading < 0.0 ) { TargetHeading += 360.0; }
503 while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
505 MakeTargetHeadingStr( TargetHeading );
506 // cout << "target course (true) = " << TargetHeading << endl;
507 } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
508 // update target heading to waypoint
510 double wp_course, wp_distance;
512 #ifdef DO_fgAP_CORRECTED_COURSE
513 // compute course made good
514 // this needs lots of special casing before use
515 double course, reverse, distance, corrected_course;
516 // need to test for iter
517 geo_inverse_wgs_84( 0, //fgAPget_altitude(),
525 #endif // DO_fgAP_CORRECTED_COURSE
527 // compute course to way_point
528 // need to test for iter
529 SGWayPoint wp = globals->get_route()->get_first();
530 wp.CourseAndDistance( lon, lat, alt,
531 &wp_course, &wp_distance );
533 #ifdef DO_fgAP_CORRECTED_COURSE
534 corrected_course = course - wp_course;
535 if( fabs(corrected_course) > 0.1 )
536 printf("fgAP: course %f wp_course %f %f %f\n",
537 course, wp_course, fabs(corrected_course),
539 #endif // DO_fgAP_CORRECTED_COURSE
541 if ( wp_distance > 100 ) {
542 // corrected_course = course - wp_course;
543 TargetHeading = NormalizeDegrees(wp_course);
545 cout << "Reached waypoint within " << wp_distance << "meters"
548 // pop off this waypoint from the list
549 if ( globals->get_route()->size() ) {
550 globals->get_route()->delete_first();
553 // see if there are more waypoints on the list
554 if ( globals->get_route()->size() ) {
556 set_HeadingMode( FG_HEADING_WAYPOINT );
559 heading_mode = FG_TRUE_HEADING_LOCK;
560 // use current heading
561 TargetHeading = heading_node->getDoubleValue();
564 MakeTargetHeadingStr( TargetHeading );
565 // Force this just in case
566 TargetDistance = wp_distance;
567 MakeTargetWPStr( wp_distance );
570 if ( heading_mode == FG_TC_HEADING_LOCK ) {
571 // drive the turn coordinator to zero
572 double turn = FGSteam::get_TC_std();
573 // cout << "turn rate = " << turn << endl;
574 double AileronSet = -turn / 2.0;
575 SG_CLAMP_RANGE( AileronSet, -1.0, 1.0 );
576 globals->get_controls()->set_aileron( AileronSet );
577 globals->get_controls()->set_rudder( AileronSet / 4.0 );
579 // steer towards the target heading
587 = NormalizeDegrees( TargetHeading
588 - heading_node->getDoubleValue() );
589 // figure out how far off we are from desired heading
591 // Now it is time to deterime how far we should be rolled.
592 SG_LOG( SG_AUTOPILOT, SG_DEBUG, "RelHeading: " << RelHeading );
595 // Check if we are further from heading than the roll out point
596 if ( fabs( RelHeading ) > RollOut ) {
597 // set Target Roll to Max in desired direction
598 if ( RelHeading < 0 ) {
599 TargetRoll = 0 - MaxRoll;
601 TargetRoll = MaxRoll;
604 // We have to calculate the Target roll
606 // This calculation engine thinks that the Target roll
607 // should be a line from (RollOut,MaxRoll) to (-RollOut,
608 // -MaxRoll) I hope this works well. If I get ambitious
609 // some day this might become a fancier curve or
612 TargetRoll = LinearExtrapolate( RelHeading, -RollOut,
617 // Target Roll has now been Found.
619 // Compare Target roll to Current Roll, Generate Rel Roll
621 SG_LOG( SG_COCKPIT, SG_BULK, "TargetRoll: " << TargetRoll );
623 RelRoll = NormalizeDegrees( TargetRoll
624 - roll_node->getDoubleValue() );
626 // Check if we are further from heading than the roll out
628 if ( fabs( RelRoll ) > RollOutSmooth ) {
629 // set Target Roll to Max in desired direction
631 AileronSet = 0 - MaxAileron;
633 AileronSet = MaxAileron;
636 AileronSet = LinearExtrapolate( RelRoll, -RollOutSmooth,
642 globals->get_controls()->set_aileron( AileronSet );
643 globals->get_controls()->set_rudder( AileronSet / 4.0 );
644 // controls.set_rudder( 0.0 );
649 if ( altitude_hold ) {
651 double speed, max_climb, error;
652 double prop_error, int_error;
653 double prop_adj, int_adj, total_adj;
655 if ( altitude_mode == FG_ALTITUDE_LOCK ) {
657 ( TargetAltitude - FGSteam::get_ALT_ft() * SG_FEET_TO_METER ) * 8.0;
658 } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
659 double x = current_radiostack->get_nav1_gs_dist();
660 double y = (altitude_node->getDoubleValue()
661 - current_radiostack->get_nav1_elev()) * SG_FEET_TO_METER;
662 double current_angle = atan2( y, x ) * SGD_RADIANS_TO_DEGREES;
663 // cout << "current angle = " << current_angle << endl;
665 double target_angle = current_radiostack->get_nav1_target_gs();
666 // cout << "target angle = " << target_angle << endl;
668 double gs_diff = target_angle - current_angle;
669 // cout << "difference from desired = " << gs_diff << endl;
671 // convert desired vertical path angle into a climb rate
672 double des_angle = current_angle - 10 * gs_diff;
673 // cout << "desired angle = " << des_angle << endl;
675 // convert to meter/min
676 // cout << "raw ground speed = " << cur_fdm_state->get_V_ground_speed() << endl;
677 double horiz_vel = cur_fdm_state->get_V_ground_speed()
678 * SG_FEET_TO_METER * 60.0;
679 // cout << "Horizontal vel = " << horiz_vel << endl;
680 climb_rate = -sin( des_angle * SGD_DEGREES_TO_RADIANS ) * horiz_vel;
681 // cout << "climb_rate = " << climb_rate << endl;
682 /* climb_error_accum += gs_diff * 2.0; */
683 /* climb_rate = gs_diff * 200.0 + climb_error_accum; */
684 } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
685 // brain dead ground hugging with no look ahead
687 ( TargetAGL - altitude_agl_node->getDoubleValue()
688 * SG_FEET_TO_METER ) * 16.0;
689 // cout << "target agl = " << TargetAGL
690 // << " current agl = " << fgAPget_agl()
691 // << " target climb rate = " << climb_rate
694 // just try to zero out rate of climb ...
700 if ( speed < min_climb->getFloatValue() ) {
702 } else if ( speed < best_climb->getFloatValue() ) {
703 max_climb = ((best_climb->getFloatValue()
704 - min_climb->getFloatValue())
705 - (best_climb->getFloatValue() - speed))
706 * fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER)
707 / (best_climb->getFloatValue() - min_climb->getFloatValue());
709 max_climb = ( speed - best_climb->getFloatValue() ) * 10.0
710 + fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
713 // this first one could be optional if we wanted to allow
714 // better climb performance assuming we have the airspeed to
717 fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER) ) {
719 = fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
722 if ( climb_rate > max_climb ) {
723 climb_rate = max_climb;
727 -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER) ) {
729 = -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER);
732 // cout << "Target climb rate = " << TargetClimbRate->getFloatValue() << endl;
733 // cout << "given our speed, modified desired climb rate = "
734 // << climb_rate * SG_METER_TO_FEET
735 // << " fpm" << endl;
736 // cout << "Current climb rate = "
737 // << vertical_speed_node->getDoubleValue() * 60 << " fpm" << endl;
739 error = vertical_speed_node->getDoubleValue() * 60
740 - climb_rate * SG_METER_TO_FEET;
742 // accumulate the error under the curve ... this really should
744 alt_error_accum += error;
746 // calculate integral error, and adjustment amount
747 int_error = alt_error_accum;
748 // printf("error = %.2f int_error = %.2f\n", error, int_error);
749 int_adj = int_error / elevator_adj_factor->getFloatValue();
751 // caclulate proportional error
753 prop_adj = prop_error / elevator_adj_factor->getDoubleValue();
755 // cout << "Error=" << error << endl;
756 // cout << "integral_error=" << int_error << endl;
757 // cout << "integral_contrib=" << integral_contrib->getFloatValue() << endl;
758 // cout << "Proportional Adj=" << prop_adj << endl;
759 // cout << "Integral Adj" << int_adj << endl;
760 total_adj = ((double) 1.0 - (double) integral_contrib->getFloatValue()) * prop_adj
761 + (double) integral_contrib->getFloatValue() * int_adj;
763 // stop on autopilot trim at 30% +/-
764 // if ( total_adj > 0.3 ) {
766 // } else if ( total_adj < -0.3 ) {
770 // adjust for throttle pitch gain
771 total_adj += ((current_throttle->getFloatValue() - zero_pitch_throttle->getFloatValue())
772 / (1 - zero_pitch_throttle->getFloatValue()))
773 * zero_pitch_trim_full_throttle->getFloatValue();
775 // cout << "Total Adj" << total_adj << endl;
777 globals->get_controls()->set_elevator_trim( total_adj );
781 if ( auto_throttle ) {
783 double prop_error, int_error;
784 double prop_adj, int_adj, total_adj;
786 error = TargetSpeed - get_speed();
788 // accumulate the error under the curve ... this really should
790 speed_error_accum += error;
791 if ( speed_error_accum > 2000.0 ) {
792 speed_error_accum = 2000.0;
794 else if ( speed_error_accum < -2000.0 ) {
795 speed_error_accum = -2000.0;
798 // calculate integral error, and adjustment amount
799 int_error = speed_error_accum;
801 // printf("error = %.2f int_error = %.2f\n", error, int_error);
802 int_adj = int_error / 200.0;
804 // caclulate proportional error
806 prop_adj = 0.5 + prop_error / 50.0;
808 total_adj = 0.9 * prop_adj + 0.1 * int_adj;
809 if ( total_adj > 1.0 ) {
812 else if ( total_adj < 0.0 ) {
816 globals->get_controls()->set_throttle( FGControls::ALL_ENGINES,
820 #ifdef THIS_CODE_IS_NOT_USED
821 if (Mode == 2) // Glide slope hold
826 // First, calculate Relative slope and normalize it
827 RelSlope = NormalizeDegrees( TargetSlope - get_pitch());
829 // Now calculate the elevator offset from current angle
830 if ( abs(RelSlope) > SlopeSmooth )
832 if ( RelSlope < 0 ) // set RelElevator to max in the correct direction
833 RelElevator = -MaxElevator;
835 RelElevator = MaxElevator;
839 RelElevator = LinearExtrapolate(RelSlope,-SlopeSmooth,-MaxElevator,SlopeSmooth,MaxElevator);
842 fgElevMove(RelElevator);
845 #endif // THIS_CODE_IS_NOT_USED
847 // stash this runs control settings
848 // update_old_control_values();
849 old_aileron = globals->get_controls()->get_aileron();
850 old_elevator = globals->get_controls()->get_elevator();
851 old_elevator_trim = globals->get_controls()->get_elevator_trim();
852 old_rudder = globals->get_controls()->get_rudder();
854 // for cross track error
859 SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run( returns )" );
865 void FGAutopilot::set_HeadingMode( fgAutoHeadingMode mode ) {
868 if ( heading_mode == FG_DG_HEADING_LOCK ) {
869 // set heading hold to current heading (as read from DG)
870 // ... no, leave target heading along ... just use the current
872 // DGTargetHeading = FGSteam::get_DG_deg();
873 } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
874 // set autopilot to hold a zero turn (as reported by the TC)
875 } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
876 // set heading hold to current heading
877 TargetHeading = heading_node->getDoubleValue();
878 } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
879 if ( globals->get_route()->size() ) {
880 double course, distance;
882 old_lat = latitude_node->getDoubleValue();
883 old_lon = longitude_node->getDoubleValue();
885 waypoint = globals->get_route()->get_first();
886 waypoint.CourseAndDistance( longitude_node->getDoubleValue(),
887 latitude_node->getDoubleValue(),
888 altitude_node->getDoubleValue()
890 &course, &distance );
891 TargetHeading = course;
892 TargetDistance = distance;
893 MakeTargetLatLonStr( waypoint.get_target_lat(),
894 waypoint.get_target_lon() );
895 MakeTargetWPStr( distance );
897 if ( waypoint.get_target_alt() > 0.0 ) {
898 TargetAltitude = waypoint.get_target_alt();
899 altitude_mode = FG_ALTITUDE_LOCK;
900 set_AltitudeEnabled( true );
901 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
904 SG_LOG( SG_COCKPIT, SG_INFO, " set_HeadingMode: ( "
905 << get_TargetLatitude() << " "
906 << get_TargetLongitude() << " ) "
909 // no more way points, default to heading lock.
910 heading_mode = FG_TC_HEADING_LOCK;
914 MakeTargetHeadingStr( TargetHeading );
915 update_old_control_values();
919 void FGAutopilot::set_AltitudeMode( fgAutoAltitudeMode mode ) {
920 altitude_mode = mode;
922 alt_error_accum = 0.0;
925 if ( altitude_mode == FG_ALTITUDE_LOCK ) {
926 if ( TargetAltitude < altitude_agl_node->getDoubleValue()
927 * SG_FEET_TO_METER ) {
930 if ( fgGetString("/sim/startup/units") == "feet" ) {
931 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
933 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
935 } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
936 climb_error_accum = 0.0;
938 } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
939 TargetAGL = altitude_agl_node->getDoubleValue() * SG_FEET_TO_METER;
941 if ( fgGetString("/sim/startup/units") == "feet" ) {
942 MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
944 MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
948 update_old_control_values();
949 SG_LOG( SG_COCKPIT, SG_INFO, " set_AltitudeMode():" );
954 static inline double get_aoa( void ) {
955 return( cur_fdm_state->get_Gamma_vert_rad() * SGD_RADIANS_TO_DEGREES );
958 static inline double fgAPget_latitude( void ) {
959 return( cur_fdm_state->get_Latitude() * SGD_RADIANS_TO_DEGREES );
962 static inline double fgAPget_longitude( void ) {
963 return( cur_fdm_state->get_Longitude() * SGD_RADIANS_TO_DEGREES );
966 static inline double fgAPget_roll( void ) {
967 return( cur_fdm_state->get_Phi() * SGD_RADIANS_TO_DEGREES );
970 static inline double get_pitch( void ) {
971 return( cur_fdm_state->get_Theta() );
974 double fgAPget_heading( void ) {
975 return( cur_fdm_state->get_Psi() * SGD_RADIANS_TO_DEGREES );
978 static inline double fgAPget_altitude( void ) {
979 return( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
982 static inline double fgAPget_climb( void ) {
983 // return in meters per minute
984 return( cur_fdm_state->get_Climb_Rate() * SG_FEET_TO_METER * 60 );
987 static inline double get_sideslip( void ) {
988 return( cur_fdm_state->get_Beta() );
991 static inline double fgAPget_agl( void ) {
994 agl = cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
995 - scenery.get_cur_elev();
1002 void FGAutopilot::AltitudeSet( double new_altitude ) {
1003 double target_alt = new_altitude;
1005 // cout << "new altitude = " << new_altitude << endl;
1007 if ( fgGetString("/sim/startup/units") == "feet" ) {
1008 target_alt = new_altitude * SG_FEET_TO_METER;
1011 if( target_alt < scenery.get_cur_elev() ) {
1012 target_alt = scenery.get_cur_elev();
1015 TargetAltitude = target_alt;
1016 altitude_mode = FG_ALTITUDE_LOCK;
1018 // cout << "TargetAltitude = " << TargetAltitude << endl;
1020 if ( fgGetString("/sim/startup/units") == "feet" ) {
1021 target_alt *= SG_METER_TO_FEET;
1023 // ApAltitudeDialogInput->setValue((float)target_alt);
1024 MakeTargetAltitudeStr( target_alt );
1026 update_old_control_values();
1030 void FGAutopilot::AltitudeAdjust( double inc )
1032 double target_alt, target_agl;
1034 if ( fgGetString("/sim/startup/units") == "feet" ) {
1035 target_alt = TargetAltitude * SG_METER_TO_FEET;
1036 target_agl = TargetAGL * SG_METER_TO_FEET;
1038 target_alt = TargetAltitude;
1039 target_agl = TargetAGL;
1042 // cout << "target_agl = " << target_agl << endl;
1043 // cout << "target_agl / inc = " << target_agl / inc << endl;
1044 // cout << "(int)(target_agl / inc) = " << (int)(target_agl / inc) << endl;
1046 if ( fabs((int)(target_alt / inc) * inc - target_alt) < SG_EPSILON ) {
1049 target_alt = ( int ) ( target_alt / inc ) * inc + inc;
1052 if ( fabs((int)(target_agl / inc) * inc - target_agl) < SG_EPSILON ) {
1055 target_agl = ( int ) ( target_agl / inc ) * inc + inc;
1058 if ( fgGetString("/sim/startup/units") == "feet" ) {
1059 target_alt *= SG_FEET_TO_METER;
1060 target_agl *= SG_FEET_TO_METER;
1063 TargetAltitude = target_alt;
1064 TargetAGL = target_agl;
1066 if ( fgGetString("/sim/startup/units") == "feet" )
1067 target_alt *= SG_METER_TO_FEET;
1068 if ( fgGetString("/sim/startup/units") == "feet" )
1069 target_agl *= SG_METER_TO_FEET;
1071 if ( altitude_mode == FG_ALTITUDE_LOCK ) {
1072 MakeTargetAltitudeStr( target_alt );
1073 } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
1074 MakeTargetAltitudeStr( target_agl );
1077 update_old_control_values();
1081 void FGAutopilot::HeadingAdjust( double inc ) {
1082 if ( heading_mode != FG_DG_HEADING_LOCK
1083 && heading_mode != FG_TRUE_HEADING_LOCK )
1085 heading_mode = FG_DG_HEADING_LOCK;
1088 if ( heading_mode == FG_DG_HEADING_LOCK ) {
1089 double target = ( int ) ( DGTargetHeading / inc ) * inc + inc;
1090 DGTargetHeading = NormalizeDegrees( target );
1092 double target = ( int ) ( TargetHeading / inc ) * inc + inc;
1093 TargetHeading = NormalizeDegrees( target );
1096 update_old_control_values();
1100 void FGAutopilot::HeadingSet( double new_heading ) {
1101 if( heading_mode == FG_TRUE_HEADING_LOCK ) {
1102 new_heading = NormalizeDegrees( new_heading );
1103 TargetHeading = new_heading;
1104 MakeTargetHeadingStr( TargetHeading );
1106 heading_mode = FG_DG_HEADING_LOCK;
1108 new_heading = NormalizeDegrees( new_heading );
1109 DGTargetHeading = new_heading;
1110 // following cast needed ambiguous plib
1111 // ApHeadingDialogInput -> setValue ((float)APData->TargetHeading );
1112 MakeTargetHeadingStr( DGTargetHeading );
1114 update_old_control_values();
1117 void FGAutopilot::AutoThrottleAdjust( double inc ) {
1118 double target = ( int ) ( TargetSpeed / inc ) * inc + inc;
1120 TargetSpeed = target;
1124 void FGAutopilot::set_AutoThrottleEnabled( bool value ) {
1125 auto_throttle = value;
1127 if ( auto_throttle == true ) {
1128 TargetSpeed = fgGetDouble("/velocities/airspeed-kt");
1129 speed_error_accum = 0.0;
1132 update_old_control_values();
1133 SG_LOG( SG_COCKPIT, SG_INFO, " fgAPSetAutoThrottle: ("
1134 << auto_throttle << ") " << TargetSpeed );