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/debug/logstream.hxx>
34 #include <simgear/math/sg_geodesy.hxx>
35 #include <simgear/math/sg_random.h>
37 #include <Cockpit/steam.hxx>
38 #include <Cockpit/radiostack.hxx>
39 #include <Controls/controls.hxx>
40 #include <FDM/flight.hxx>
41 #include <Main/globals.hxx>
42 #include <Scenery/scenery.hxx>
44 #include "newauto.hxx"
47 FGAutopilot *current_autopilot;
50 // Climb speed constants
51 // const double min_climb = 70.0; // kts
52 // const double best_climb = 75.0; // kts
53 // const double ideal_climb_rate = 500.0 * SG_FEET_TO_METER; // fpm -> mpm
54 // const double ideal_decent_rate = 1000.0 * SG_FEET_TO_METER; // fpm -> mpm
56 /// These statics will eventually go into the class
57 /// they are just here while I am experimenting -- NHV :-)
58 // AutoPilot Gain Adjuster members
59 static double MaxRollAdjust; // MaxRollAdjust = 2 * APData->MaxRoll;
60 static double RollOutAdjust; // RollOutAdjust = 2 * APData->RollOut;
61 static double MaxAileronAdjust; // MaxAileronAdjust = 2 * APData->MaxAileron;
62 static double RollOutSmoothAdjust; // RollOutSmoothAdjust = 2 * APData->RollOutSmooth;
64 static char NewTgtAirportId[16];
65 // static char NewTgtAirportLabel[] = "Enter New TgtAirport ID";
67 extern char *coord_format_lat(float);
68 extern char *coord_format_lon(float);
72 FGAutopilot::FGAutopilot()
75 = fgGetNode("/autopilot/config/target-climb-rate-fpm", true);
77 = fgGetNode("/autopilot/config/target-descent-rate-fpm", true);
78 min_climb = fgGetNode("/autopilot/config/min-climb-speed-kt", true);
79 best_climb = fgGetNode("/autopilot/config/best-climb-speed-kt", true);
81 = fgGetNode("/autopilot/config/elevator-adj-factor", true);
83 = fgGetNode("/autopilot/config/integral-contribution", true);
84 cout << "elevadj = " << elevator_adj_factor->getFloatValue() << endl;
85 // initialize with defaults (in case config isn't there)
86 if ( TargetClimbRate->getFloatValue() < 1 )
87 fgSetFloat( "/autopilot/config/target-climb-rate-fpm", 500);
88 if ( TargetDescentRate->getFloatValue() < 1 )
89 fgSetFloat( "/autopilot/config/target-descent-rate-fpm", 1000 );
90 if ( min_climb->getFloatValue() < 1)
91 fgSetFloat( "/autopilot/config/min-climb-speed-kt", 70 );
92 if (best_climb->getFloatValue() < 1)
93 fgSetFloat( "/autopilot/config/best-climb-speed-kt", 120 );
94 if (elevator_adj_factor->getFloatValue() < 1)
95 fgSetFloat( "/autopilot/config/elevator-adj-factor", 5000 );
96 if ( integral_contrib->getFloatValue() < 0.0000001 )
97 fgSetFloat( "/autopilot/config/integral-contribution", 0.01 );
101 FGAutopilot::~FGAutopilot() {}
104 void FGAutopilot::MakeTargetLatLonStr( double lat, double lon ) {
105 sprintf( TargetLatitudeStr , "%s", coord_format_lat(get_TargetLatitude()));
106 sprintf( TargetLongitudeStr, "%s", coord_format_lon(get_TargetLongitude()));
107 sprintf( TargetLatLonStr, "%s %s", TargetLatitudeStr, TargetLongitudeStr );
111 void FGAutopilot::MakeTargetAltitudeStr( double altitude ) {
112 if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
113 sprintf( TargetAltitudeStr, "APAltitude %6.0f+", altitude );
115 sprintf( TargetAltitudeStr, "APAltitude %6.0f", altitude );
120 void FGAutopilot::MakeTargetHeadingStr( double bearing ) {
123 } else if (bearing > 360. ) {
126 sprintf( TargetHeadingStr, "APHeading %6.1f", bearing );
130 static inline double get_speed( void ) {
131 return( cur_fdm_state->get_V_equiv_kts() );
134 static inline double get_ground_speed() {
135 // starts in ft/s so we convert to kts
136 static const SGPropertyNode * speedup_node = fgGetNode("/sim/speed-up");
138 double ft_s = cur_fdm_state->get_V_ground_speed()
139 * speedup_node->getIntValue();
140 double kts = ft_s * SG_FEET_TO_METER * 3600 * SG_METER_TO_NM;
146 void FGAutopilot::MakeTargetWPStr( double distance ) {
147 static time_t last_time = 0;
148 time_t current_time = time(NULL);
149 if ( last_time == current_time ) {
153 last_time = current_time;
157 int size = globals->get_route()->size();
159 // start by wiping the strings
166 SGWayPoint wp1 = globals->get_route()->get_waypoint( 0 );
168 double eta = accum * SG_METER_TO_NM / get_ground_speed();
169 if ( eta >= 100.0 ) { eta = 99.999; }
171 if ( eta < (1.0/6.0) ) {
172 // within 10 minutes, bump up to min/secs
176 minor = (int)((eta - (int)eta) * 60.0);
177 sprintf( TargetWP1Str, "%s %.2f NM ETA %d:%02d",
178 wp1.get_id().c_str(),
179 accum*SG_METER_TO_NM, major, minor );
180 // cout << "distance = " << distance*SG_METER_TO_NM
181 // << " gndsp = " << get_ground_speed()
182 // << " time = " << eta
183 // << " major = " << major
184 // << " minor = " << minor
190 SGWayPoint wp2 = globals->get_route()->get_waypoint( 1 );
191 accum += wp2.get_distance();
193 double eta = accum * SG_METER_TO_NM / get_ground_speed();
194 if ( eta >= 100.0 ) { eta = 99.999; }
196 if ( eta < (1.0/6.0) ) {
197 // within 10 minutes, bump up to min/secs
201 minor = (int)((eta - (int)eta) * 60.0);
202 sprintf( TargetWP2Str, "%s %.2f NM ETA %d:%02d",
203 wp2.get_id().c_str(),
204 accum*SG_METER_TO_NM, major, minor );
209 for ( int i = 2; i < size; ++i ) {
210 accum += globals->get_route()->get_waypoint( i ).get_distance();
213 SGWayPoint wpn = globals->get_route()->get_waypoint( size - 1 );
215 double eta = accum * SG_METER_TO_NM / get_ground_speed();
216 if ( eta >= 100.0 ) { eta = 99.999; }
218 if ( eta < (1.0/6.0) ) {
219 // within 10 minutes, bump up to min/secs
223 minor = (int)((eta - (int)eta) * 60.0);
224 sprintf( TargetWP3Str, "%s %.2f NM ETA %d:%02d",
225 wpn.get_id().c_str(),
226 accum*SG_METER_TO_NM, major, minor );
231 void FGAutopilot::update_old_control_values() {
232 old_aileron = globals->get_controls()->get_aileron();
233 old_elevator = globals->get_controls()->get_elevator();
234 old_elevator_trim = globals->get_controls()->get_elevator_trim();
235 old_rudder = globals->get_controls()->get_rudder();
239 // Initialize autopilot subsystem
240 void FGAutopilot::init() {
241 SG_LOG( SG_AUTOPILOT, SG_INFO, "Init AutoPilot Subsystem" );
243 latitude_node = fgGetNode("/position/latitude-deg", true);
244 longitude_node = fgGetNode("/position/longitude-deg", true);
245 altitude_node = fgGetNode("/position/altitude-ft", true);
246 altitude_agl_node = fgGetNode("/position/altitude-agl-ft", true);
247 vertical_speed_node = fgGetNode("/velocities/vertical-speed-fps", true);
248 heading_node = fgGetNode("/orientation/heading-deg", true);
249 roll_node = fgGetNode("/orientation/roll-deg", true);
251 heading_hold = false ; // turn the heading hold off
252 altitude_hold = false ; // turn the altitude hold off
253 auto_throttle = false ; // turn the auto throttle off
254 heading_mode = DEFAULT_AP_HEADING_LOCK;
257 DGTargetHeading = sg_random() * 360.0;
259 // Initialize target location to startup location
260 old_lat = latitude_node->getDoubleValue();
261 old_lon = longitude_node->getDoubleValue();
262 // set_WayPoint( old_lon, old_lat, 0.0, "default" );
264 MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
266 TargetHeading = 0.0; // default direction, due north
267 TargetAltitude = 3000; // default altitude in meters
268 alt_error_accum = 0.0;
269 climb_error_accum = 0.0;
271 MakeTargetAltitudeStr( TargetAltitude );
272 MakeTargetHeadingStr( TargetHeading );
274 // These eventually need to be read from current_aircaft somehow.
276 // the maximum roll, in Deg
279 // the deg from heading to start rolling out at, in Deg
282 // how far can I move the aleron from center.
285 // Smoothing distance for alerion control
288 // Hardwired for now should be in options
289 // 25% max control variablilty 0.5 / 2.0
290 disengage_threshold = 1.0;
292 #if !defined( USING_SLIDER_CLASS )
293 MaxRollAdjust = 2 * MaxRoll;
294 RollOutAdjust = 2 * RollOut;
295 MaxAileronAdjust = 2 * MaxAileron;
296 RollOutSmoothAdjust = 2 * RollOutSmooth;
297 #endif // !defined( USING_SLIDER_CLASS )
299 update_old_control_values();
301 // Initialize GUI components of autopilot
302 // NewTgtAirportInit();
303 // fgAPAdjustInit() ;
305 // NewAltitudeInit();
309 // Reset the autopilot system
310 void FGAutopilot::reset() {
312 heading_hold = false ; // turn the heading hold off
313 altitude_hold = false ; // turn the altitude hold off
314 auto_throttle = false ; // turn the auto throttle off
315 heading_mode = DEFAULT_AP_HEADING_LOCK;
317 // TargetHeading = 0.0; // default direction, due north
318 MakeTargetHeadingStr( TargetHeading );
320 // TargetAltitude = 3000; // default altitude in meters
321 MakeTargetAltitudeStr( TargetAltitude );
323 alt_error_accum = 0.0;
324 climb_error_accum = 0.0;
326 update_old_control_values();
328 sprintf( NewTgtAirportId, "%s", fgGetString("/sim/startup/airport-id").c_str() );
330 MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
334 static double NormalizeDegrees( double Input ) {
335 // normalize the input to the range (-180,180]
336 // Input should not be greater than -360 to 360.
337 // Current rules send the output to an undefined state.
341 else if ( Input <= -180 )
342 while ( Input <= -180 )
347 static double LinearExtrapolate( double x, double x1, double y1, double x2, double y2 ) {
348 // This procedure extrapolates the y value for the x posistion on a line defined by x1,y1; x2,y2
349 //assert(x1 != x2); // Divide by zero error. Cold abort for now
352 // static double y = 0.0;
353 // double dx = x2 -x1;
354 // if( (dx < -SG_EPSILON ) || ( dx > SG_EPSILON ) )
357 double m, b, y; // the constants to find in y=mx+b
360 m = ( y2 - y1 ) / ( x2 - x1 ); // calculate the m
362 b = y1 - m * x1; // calculate the b
364 y = m * x + b; // the final calculation
373 int FGAutopilot::run() {
374 // Remove the following lines when the calling funcitons start
375 // passing in the data pointer
377 // get control settings
379 double lat = latitude_node->getDoubleValue();
380 double lon = longitude_node->getDoubleValue();
381 double alt = altitude_node->getDoubleValue() * SG_FEET_TO_METER;
383 SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run() lat = " << lat <<
384 " lon = " << lon << " alt = " << alt );
386 #ifdef FG_FORCE_AUTO_DISENGAGE
387 // see if somebody else has changed them
388 if( fabs(aileron - old_aileron) > disengage_threshold ||
389 fabs(elevator - old_elevator) > disengage_threshold ||
390 fabs(elevator_trim - old_elevator_trim) >
391 disengage_threshold ||
392 fabs(rudder - old_rudder) > disengage_threshold )
394 // if controls changed externally turn autopilot off
395 waypoint_hold = false ; // turn the target hold off
396 heading_hold = false ; // turn the heading hold off
397 altitude_hold = false ; // turn the altitude hold off
398 terrain_follow = false; // turn the terrain_follow hold off
399 // auto_throttle = false; // turn the auto_throttle off
401 // stash this runs control settings
402 old_aileron = aileron;
403 old_elevator = elevator;
404 old_elevator_trim = elevator_trim;
412 if ( heading_hold == true ) {
413 if ( heading_mode == FG_DG_HEADING_LOCK ) {
414 // cout << "DG heading = " << FGSteam::get_DG_deg()
415 // << " DG error = " << FGSteam::get_DG_err() << endl;
417 TargetHeading = DGTargetHeading + FGSteam::get_DG_err();
418 while ( TargetHeading < 0.0 ) { TargetHeading += 360.0; }
419 while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
420 MakeTargetHeadingStr( TargetHeading );
421 } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
422 // we don't set a specific target heading in
423 // TC_HEADING_LOCK mode, we instead try to keep the turn
424 // coordinator zero'd
425 } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
426 // leave "true" target heading as is
427 while ( TargetHeading < 0.0 ) { TargetHeading += 360.0; }
428 while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
429 MakeTargetHeadingStr( TargetHeading );
430 } else if ( heading_mode == FG_HEADING_NAV1 ) {
431 // track the NAV1 heading needle deflection
433 // determine our current radial position relative to the
434 // navaid in "true" heading.
435 double cur_radial = current_radiostack->get_nav1_heading();
436 if ( current_radiostack->get_nav1_loc() ) {
437 // ILS localizers radials are already "true" in our
440 cur_radial += current_radiostack->get_nav1_magvar();
442 if ( current_radiostack->get_nav1_from_flag() ) {
444 while ( cur_radial >= 360.0 ) { cur_radial -= 360.0; }
447 // determine the target radial in "true" heading
448 double tgt_radial = current_radiostack->get_nav1_radial();
449 if ( current_radiostack->get_nav1_loc() ) {
450 // ILS localizers radials are already "true" in our
453 // VOR radials need to have that vor's offset added in
454 tgt_radial += current_radiostack->get_nav1_magvar();
457 // determine the heading adjustment needed.
459 current_radiostack->get_nav1_heading_needle_deflection()
460 * (current_radiostack->get_nav1_loc_dist() * SG_METER_TO_NM);
461 if ( adjustment < -30.0 ) { adjustment = -30.0; }
462 if ( adjustment > 30.0 ) { adjustment = 30.0; }
464 // determine the target heading to fly to intercept the
466 TargetHeading = tgt_radial + adjustment;
467 while ( TargetHeading < 0.0 ) { TargetHeading += 360.0; }
468 while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
470 MakeTargetHeadingStr( TargetHeading );
471 // cout << "target course (true) = " << TargetHeading << endl;
472 } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
473 // update target heading to waypoint
475 double wp_course, wp_distance;
477 #ifdef DO_fgAP_CORRECTED_COURSE
478 // compute course made good
479 // this needs lots of special casing before use
480 double course, reverse, distance, corrected_course;
481 // need to test for iter
482 geo_inverse_wgs_84( 0, //fgAPget_altitude(),
490 #endif // DO_fgAP_CORRECTED_COURSE
492 // compute course to way_point
493 // need to test for iter
494 SGWayPoint wp = globals->get_route()->get_first();
495 wp.CourseAndDistance( lon, lat, alt,
496 &wp_course, &wp_distance );
498 #ifdef DO_fgAP_CORRECTED_COURSE
499 corrected_course = course - wp_course;
500 if( fabs(corrected_course) > 0.1 )
501 printf("fgAP: course %f wp_course %f %f %f\n",
502 course, wp_course, fabs(corrected_course),
504 #endif // DO_fgAP_CORRECTED_COURSE
506 if ( wp_distance > 100 ) {
507 // corrected_course = course - wp_course;
508 TargetHeading = NormalizeDegrees(wp_course);
510 cout << "Reached waypoint within " << wp_distance << "meters"
513 // pop off this waypoint from the list
514 if ( globals->get_route()->size() ) {
515 globals->get_route()->delete_first();
518 // see if there are more waypoints on the list
519 if ( globals->get_route()->size() ) {
521 set_HeadingMode( FG_HEADING_WAYPOINT );
524 heading_mode = FG_TRUE_HEADING_LOCK;
525 // use current heading
526 TargetHeading = heading_node->getDoubleValue();
529 MakeTargetHeadingStr( TargetHeading );
530 // Force this just in case
531 TargetDistance = wp_distance;
532 MakeTargetWPStr( wp_distance );
535 if ( heading_mode == FG_TC_HEADING_LOCK ) {
536 // drive the turn coordinator to zero
537 double turn = FGSteam::get_TC_std();
538 // cout << "turn rate = " << turn << endl;
539 double AileronSet = -turn / 2.0;
540 if ( AileronSet < -1.0 ) { AileronSet = -1.0; }
541 if ( AileronSet > 1.0 ) { AileronSet = 1.0; }
542 globals->get_controls()->set_aileron( AileronSet );
543 globals->get_controls()->set_rudder( AileronSet / 4.0 );
545 // steer towards the target heading
553 = NormalizeDegrees( TargetHeading
554 - heading_node->getDoubleValue() );
555 // figure out how far off we are from desired heading
557 // Now it is time to deterime how far we should be rolled.
558 SG_LOG( SG_AUTOPILOT, SG_DEBUG, "RelHeading: " << RelHeading );
561 // Check if we are further from heading than the roll out point
562 if ( fabs( RelHeading ) > RollOut ) {
563 // set Target Roll to Max in desired direction
564 if ( RelHeading < 0 ) {
565 TargetRoll = 0 - MaxRoll;
567 TargetRoll = MaxRoll;
570 // We have to calculate the Target roll
572 // This calculation engine thinks that the Target roll
573 // should be a line from (RollOut,MaxRoll) to (-RollOut,
574 // -MaxRoll) I hope this works well. If I get ambitious
575 // some day this might become a fancier curve or
578 TargetRoll = LinearExtrapolate( RelHeading, -RollOut,
583 // Target Roll has now been Found.
585 // Compare Target roll to Current Roll, Generate Rel Roll
587 SG_LOG( SG_COCKPIT, SG_BULK, "TargetRoll: " << TargetRoll );
589 RelRoll = NormalizeDegrees( TargetRoll
590 - roll_node->getDoubleValue() );
592 // Check if we are further from heading than the roll out
594 if ( fabs( RelRoll ) > RollOutSmooth ) {
595 // set Target Roll to Max in desired direction
597 AileronSet = 0 - MaxAileron;
599 AileronSet = MaxAileron;
602 AileronSet = LinearExtrapolate( RelRoll, -RollOutSmooth,
608 globals->get_controls()->set_aileron( AileronSet );
609 globals->get_controls()->set_rudder( AileronSet / 4.0 );
610 // controls.set_rudder( 0.0 );
615 if ( altitude_hold ) {
617 double speed, max_climb, error;
618 double prop_error, int_error;
619 double prop_adj, int_adj, total_adj;
621 if ( altitude_mode == FG_ALTITUDE_LOCK ) {
623 ( TargetAltitude - FGSteam::get_ALT_ft() * SG_FEET_TO_METER ) * 8.0;
624 } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
625 double x = current_radiostack->get_nav1_gs_dist();
626 double y = (altitude_node->getDoubleValue()
627 - current_radiostack->get_nav1_elev()) * SG_FEET_TO_METER;
628 double current_angle = atan2( y, x ) * SGD_RADIANS_TO_DEGREES;
629 // cout << "current angle = " << current_angle << endl;
631 double target_angle = current_radiostack->get_nav1_target_gs();
632 // cout << "target angle = " << target_angle << endl;
634 double gs_diff = target_angle - current_angle;
635 // cout << "difference from desired = " << gs_diff << endl;
637 // convert desired vertical path angle into a climb rate
638 double des_angle = current_angle - 10 * gs_diff;
639 // cout << "desired angle = " << des_angle << endl;
641 // convert to meter/min
642 // cout << "raw ground speed = " << cur_fdm_state->get_V_ground_speed() << endl;
643 double horiz_vel = cur_fdm_state->get_V_ground_speed()
644 * SG_FEET_TO_METER * 60.0;
645 // cout << "Horizontal vel = " << horiz_vel << endl;
646 climb_rate = -sin( des_angle * SGD_DEGREES_TO_RADIANS ) * horiz_vel;
647 // cout << "climb_rate = " << climb_rate << endl;
648 /* climb_error_accum += gs_diff * 2.0; */
649 /* climb_rate = gs_diff * 200.0 + climb_error_accum; */
650 } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
651 // brain dead ground hugging with no look ahead
653 ( TargetAGL - altitude_agl_node->getDoubleValue()
654 * SG_FEET_TO_METER ) * 16.0;
655 // cout << "target agl = " << TargetAGL
656 // << " current agl = " << fgAPget_agl()
657 // << " target climb rate = " << climb_rate
660 // just try to zero out rate of climb ...
666 if ( speed < min_climb->getFloatValue() ) {
668 } else if ( speed < best_climb->getFloatValue() ) {
669 max_climb = ((best_climb->getFloatValue()
670 - min_climb->getFloatValue())
671 - (best_climb->getFloatValue() - speed))
672 * fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER)
673 / (best_climb->getFloatValue() - min_climb->getFloatValue());
675 max_climb = ( speed - best_climb->getFloatValue() ) * 10.0
676 + fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
679 // this first one could be optional if we wanted to allow
680 // better climb performance assuming we have the airspeed to
683 fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER) ) {
685 = fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
688 if ( climb_rate > max_climb ) {
689 climb_rate = max_climb;
693 -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER) ) {
695 = -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER);
698 // cout << "Target climb rate = " << TargetClimbRate << endl;
699 // cout << "given our speed, modified desired climb rate = "
700 // << climb_rate * SG_METER_TO_FEET
701 // << " fpm" << endl;
702 // cout << "Current climb rate = "
703 // << vertical_speed_node->getDoubleValue() * 60 << " fpm" << endl;
705 error = vertical_speed_node->getDoubleValue() * 60
706 - climb_rate * SG_METER_TO_FEET;
708 // accumulate the error under the curve ... this really should
710 alt_error_accum += error;
712 // calculate integral error, and adjustment amount
713 int_error = alt_error_accum;
714 // printf("error = %.2f int_error = %.2f\n", error, int_error);
715 int_adj = int_error / elevator_adj_factor->getFloatValue();
717 // caclulate proportional error
719 prop_adj = prop_error / elevator_adj_factor->getFloatValue();
721 total_adj = (1.0 - integral_contrib->getFloatValue()) * prop_adj
722 + integral_contrib->getFloatValue() * int_adj;
723 // if ( total_adj > 0.6 ) {
725 // } else if ( total_adj < -0.2 ) {
728 if ( total_adj > 1.0 ) {
730 } else if ( total_adj < -1.0 ) {
734 globals->get_controls()->set_elevator_trim( total_adj );
738 if ( auto_throttle ) {
740 double prop_error, int_error;
741 double prop_adj, int_adj, total_adj;
743 error = TargetSpeed - get_speed();
745 // accumulate the error under the curve ... this really should
747 speed_error_accum += error;
748 if ( speed_error_accum > 2000.0 ) {
749 speed_error_accum = 2000.0;
751 else if ( speed_error_accum < -2000.0 ) {
752 speed_error_accum = -2000.0;
755 // calculate integral error, and adjustment amount
756 int_error = speed_error_accum;
758 // printf("error = %.2f int_error = %.2f\n", error, int_error);
759 int_adj = int_error / 200.0;
761 // caclulate proportional error
763 prop_adj = 0.5 + prop_error / 50.0;
765 total_adj = 0.9 * prop_adj + 0.1 * int_adj;
766 if ( total_adj > 1.0 ) {
769 else if ( total_adj < 0.0 ) {
773 globals->get_controls()->set_throttle( FGControls::ALL_ENGINES,
777 #ifdef THIS_CODE_IS_NOT_USED
778 if (Mode == 2) // Glide slope hold
783 // First, calculate Relative slope and normalize it
784 RelSlope = NormalizeDegrees( TargetSlope - get_pitch());
786 // Now calculate the elevator offset from current angle
787 if ( abs(RelSlope) > SlopeSmooth )
789 if ( RelSlope < 0 ) // set RelElevator to max in the correct direction
790 RelElevator = -MaxElevator;
792 RelElevator = MaxElevator;
796 RelElevator = LinearExtrapolate(RelSlope,-SlopeSmooth,-MaxElevator,SlopeSmooth,MaxElevator);
799 fgElevMove(RelElevator);
802 #endif // THIS_CODE_IS_NOT_USED
804 // stash this runs control settings
805 // update_old_control_values();
806 old_aileron = globals->get_controls()->get_aileron();
807 old_elevator = globals->get_controls()->get_elevator();
808 old_elevator_trim = globals->get_controls()->get_elevator_trim();
809 old_rudder = globals->get_controls()->get_rudder();
811 // for cross track error
816 SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run( returns )" );
822 void FGAutopilot::set_HeadingMode( fgAutoHeadingMode mode ) {
825 if ( heading_mode == FG_DG_HEADING_LOCK ) {
826 // set heading hold to current heading (as read from DG)
827 // ... no, leave target heading along ... just use the current
829 // DGTargetHeading = FGSteam::get_DG_deg();
830 } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
831 // set autopilot to hold a zero turn (as reported by the TC)
832 } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
833 // set heading hold to current heading
834 TargetHeading = heading_node->getDoubleValue();
835 } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
836 if ( globals->get_route()->size() ) {
837 double course, distance;
839 old_lat = latitude_node->getDoubleValue();
840 old_lon = longitude_node->getDoubleValue();
842 waypoint = globals->get_route()->get_first();
843 waypoint.CourseAndDistance( longitude_node->getDoubleValue(),
844 latitude_node->getDoubleValue(),
845 altitude_node->getDoubleValue()
847 &course, &distance );
848 TargetHeading = course;
849 TargetDistance = distance;
850 MakeTargetLatLonStr( waypoint.get_target_lat(),
851 waypoint.get_target_lon() );
852 MakeTargetWPStr( distance );
854 if ( waypoint.get_target_alt() > 0.0 ) {
855 TargetAltitude = waypoint.get_target_alt();
856 altitude_mode = FG_ALTITUDE_LOCK;
857 set_AltitudeEnabled( true );
858 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
861 SG_LOG( SG_COCKPIT, SG_INFO, " set_HeadingMode: ( "
862 << get_TargetLatitude() << " "
863 << get_TargetLongitude() << " ) "
866 // no more way points, default to heading lock.
867 heading_mode = FG_TC_HEADING_LOCK;
871 MakeTargetHeadingStr( TargetHeading );
872 update_old_control_values();
876 void FGAutopilot::set_AltitudeMode( fgAutoAltitudeMode mode ) {
877 altitude_mode = mode;
879 alt_error_accum = 0.0;
881 if ( altitude_mode == FG_ALTITUDE_LOCK ) {
882 if ( TargetAltitude < altitude_agl_node->getDoubleValue()
883 * SG_FEET_TO_METER ) {
886 if ( fgGetString("/sim/startup/units") == "feet" ) {
887 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
889 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
891 } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
892 climb_error_accum = 0.0;
894 } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
895 TargetAGL = altitude_agl_node->getDoubleValue() * SG_FEET_TO_METER;
897 if ( fgGetString("/sim/startup/units") == "feet" ) {
898 MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
900 MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
904 update_old_control_values();
905 SG_LOG( SG_COCKPIT, SG_INFO, " set_AltitudeMode():" );
910 static inline double get_aoa( void ) {
911 return( cur_fdm_state->get_Gamma_vert_rad() * SGD_RADIANS_TO_DEGREES );
914 static inline double fgAPget_latitude( void ) {
915 return( cur_fdm_state->get_Latitude() * SGD_RADIANS_TO_DEGREES );
918 static inline double fgAPget_longitude( void ) {
919 return( cur_fdm_state->get_Longitude() * SGD_RADIANS_TO_DEGREES );
922 static inline double fgAPget_roll( void ) {
923 return( cur_fdm_state->get_Phi() * SGD_RADIANS_TO_DEGREES );
926 static inline double get_pitch( void ) {
927 return( cur_fdm_state->get_Theta() );
930 double fgAPget_heading( void ) {
931 return( cur_fdm_state->get_Psi() * SGD_RADIANS_TO_DEGREES );
934 static inline double fgAPget_altitude( void ) {
935 return( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
938 static inline double fgAPget_climb( void ) {
939 // return in meters per minute
940 return( cur_fdm_state->get_Climb_Rate() * SG_FEET_TO_METER * 60 );
943 static inline double get_sideslip( void ) {
944 return( cur_fdm_state->get_Beta() );
947 static inline double fgAPget_agl( void ) {
950 agl = cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
951 - scenery.get_cur_elev();
958 void FGAutopilot::AltitudeSet( double new_altitude ) {
959 double target_alt = new_altitude;
961 // cout << "new altitude = " << new_altitude << endl;
963 if ( fgGetString("/sim/startup/units") == "feet" ) {
964 target_alt = new_altitude * SG_FEET_TO_METER;
967 if( target_alt < scenery.get_cur_elev() ) {
968 target_alt = scenery.get_cur_elev();
971 TargetAltitude = target_alt;
972 altitude_mode = FG_ALTITUDE_LOCK;
974 // cout << "TargetAltitude = " << TargetAltitude << endl;
976 if ( fgGetString("/sim/startup/units") == "feet" ) {
977 target_alt *= SG_METER_TO_FEET;
979 // ApAltitudeDialogInput->setValue((float)target_alt);
980 MakeTargetAltitudeStr( target_alt );
982 update_old_control_values();
986 void FGAutopilot::AltitudeAdjust( double inc )
988 double target_alt, target_agl;
990 if ( fgGetString("/sim/startup/units") == "feet" ) {
991 target_alt = TargetAltitude * SG_METER_TO_FEET;
992 target_agl = TargetAGL * SG_METER_TO_FEET;
994 target_alt = TargetAltitude;
995 target_agl = TargetAGL;
998 // cout << "target_agl = " << target_agl << endl;
999 // cout << "target_agl / inc = " << target_agl / inc << endl;
1000 // cout << "(int)(target_agl / inc) = " << (int)(target_agl / inc) << endl;
1002 if ( fabs((int)(target_alt / inc) * inc - target_alt) < SG_EPSILON ) {
1005 target_alt = ( int ) ( target_alt / inc ) * inc + inc;
1008 if ( fabs((int)(target_agl / inc) * inc - target_agl) < SG_EPSILON ) {
1011 target_agl = ( int ) ( target_agl / inc ) * inc + inc;
1014 if ( fgGetString("/sim/startup/units") == "feet" ) {
1015 target_alt *= SG_FEET_TO_METER;
1016 target_agl *= SG_FEET_TO_METER;
1019 TargetAltitude = target_alt;
1020 TargetAGL = target_agl;
1022 if ( fgGetString("/sim/startup/units") == "feet" )
1023 target_alt *= SG_METER_TO_FEET;
1024 if ( fgGetString("/sim/startup/units") == "feet" )
1025 target_agl *= SG_METER_TO_FEET;
1027 if ( altitude_mode == FG_ALTITUDE_LOCK ) {
1028 MakeTargetAltitudeStr( target_alt );
1029 } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
1030 MakeTargetAltitudeStr( target_agl );
1033 update_old_control_values();
1037 void FGAutopilot::HeadingAdjust( double inc ) {
1038 if ( heading_mode != FG_DG_HEADING_LOCK
1039 && heading_mode != FG_TRUE_HEADING_LOCK )
1041 heading_mode = FG_DG_HEADING_LOCK;
1044 if ( heading_mode == FG_DG_HEADING_LOCK ) {
1045 double target = ( int ) ( DGTargetHeading / inc ) * inc + inc;
1046 DGTargetHeading = NormalizeDegrees( target );
1048 double target = ( int ) ( TargetHeading / inc ) * inc + inc;
1049 TargetHeading = NormalizeDegrees( target );
1052 update_old_control_values();
1056 void FGAutopilot::HeadingSet( double new_heading ) {
1057 if( heading_mode == FG_TRUE_HEADING_LOCK ) {
1058 new_heading = NormalizeDegrees( new_heading );
1059 TargetHeading = new_heading;
1060 MakeTargetHeadingStr( TargetHeading );
1062 heading_mode = FG_DG_HEADING_LOCK;
1064 new_heading = NormalizeDegrees( new_heading );
1065 DGTargetHeading = new_heading;
1066 // following cast needed ambiguous plib
1067 // ApHeadingDialogInput -> setValue ((float)APData->TargetHeading );
1068 MakeTargetHeadingStr( DGTargetHeading );
1070 update_old_control_values();
1073 void FGAutopilot::AutoThrottleAdjust( double inc ) {
1074 double target = ( int ) ( TargetSpeed / inc ) * inc + inc;
1076 TargetSpeed = target;
1080 void FGAutopilot::set_AutoThrottleEnabled( bool value ) {
1081 auto_throttle = value;
1083 if ( auto_throttle == true ) {
1084 TargetSpeed = fgGetDouble("/velocities/airspeed-kt");
1085 speed_error_accum = 0.0;
1088 update_old_control_values();
1089 SG_LOG( SG_COCKPIT, SG_INFO, " fgAPSetAutoThrottle: ("
1090 << auto_throttle << ") " << TargetSpeed );