]> git.mxchange.org Git - flightgear.git/blob - src/Autopilot/newauto.cxx
Autopilot in Nav1 heading hold mode is now driven just from needle position.
[flightgear.git] / src / Autopilot / newauto.cxx
1 // newauto.cxx -- autopilot defines and prototypes (very alpha)
2 // 
3 // Started April 1998  Copyright (C) 1998
4 //
5 // Contributions by Jeff Goeke-Smith <jgoeke@voyager.net>
6 //                  Norman Vine <nhv@cape.com>
7 //                  Curtis Olson <curt@flightgear.org>
8 //
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.
13 //
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.
18 //
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.
22 //
23 // $Id$
24
25
26 #ifdef HAVE_CONFIG_H
27 #  include <config.h>
28 #endif
29
30 #include <stdio.h>              // sprintf()
31
32 #include <simgear/constants.h>
33 #include <simgear/debug/logstream.hxx>
34 #include <simgear/math/sg_geodesy.hxx>
35
36 #include <Cockpit/steam.hxx>
37 #include <Cockpit/radiostack.hxx>
38 #include <Controls/controls.hxx>
39 #include <FDM/flight.hxx>
40 #include <Main/bfi.hxx>
41 #include <Main/globals.hxx>
42 #include <Scenery/scenery.hxx>
43
44 #include "newauto.hxx"
45
46
47 FGAutopilot *current_autopilot;
48
49
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 * FEET_TO_METER; // fpm -> mpm
54
55 /// These statics will eventually go into the class
56 /// they are just here while I am experimenting -- NHV :-)
57 // AutoPilot Gain Adjuster members
58 static double MaxRollAdjust;        // MaxRollAdjust       = 2 * APData->MaxRoll;
59 static double RollOutAdjust;        // RollOutAdjust       = 2 * APData->RollOut;
60 static double MaxAileronAdjust;     // MaxAileronAdjust    = 2 * APData->MaxAileron;
61 static double RollOutSmoothAdjust;  // RollOutSmoothAdjust = 2 * APData->RollOutSmooth;
62
63 static char NewTgtAirportId[16];
64 // static char NewTgtAirportLabel[] = "Enter New TgtAirport ID"; 
65
66 extern char *coord_format_lat(float);
67 extern char *coord_format_lon(float);
68                         
69
70 void FGAutopilot::MakeTargetLatLonStr( double lat, double lon ) {
71     sprintf( TargetLatitudeStr , "%s", coord_format_lat(get_TargetLatitude()));
72     sprintf( TargetLongitudeStr, "%s", coord_format_lon(get_TargetLongitude()));
73     sprintf( TargetLatLonStr, "%s  %s", TargetLatitudeStr, TargetLongitudeStr );
74 }
75
76
77 void FGAutopilot::MakeTargetAltitudeStr( double altitude ) {
78     if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
79         sprintf( TargetAltitudeStr, "APAltitude  %6.0f+", altitude );
80     } else {
81         sprintf( TargetAltitudeStr, "APAltitude  %6.0f", altitude );
82     }
83 }
84
85
86 void FGAutopilot::MakeTargetHeadingStr( double bearing ) {
87     if( bearing < 0. ) {
88         bearing += 360.;
89     } else if (bearing > 360. ) {
90         bearing -= 360.;
91     }
92     sprintf( TargetHeadingStr, "APHeading  %6.1f", bearing );
93 }
94
95
96 static inline double get_speed( void ) {
97     return( cur_fdm_state->get_V_equiv_kts() );
98 }
99
100 static inline double get_ground_speed() {
101     // starts in ft/s so we convert to kts
102     double ft_s = cur_fdm_state->get_V_ground_speed() 
103       * fgGetInt("/sim/speed-up"); // FIXME: inefficient
104     double kts = ft_s * FEET_TO_METER * 3600 * METER_TO_NM;
105
106     return kts;
107 }
108
109
110 void FGAutopilot::MakeTargetWPStr( double distance ) {
111     static time_t last_time = 0;
112     time_t current_time = time(NULL);
113     if ( last_time == current_time ) {
114         return;
115     }
116
117     last_time = current_time;
118
119     double accum = 0.0;
120
121     int size = globals->get_route()->size();
122
123     // start by wiping the strings
124     TargetWP1Str[0] = 0;
125     TargetWP2Str[0] = 0;
126     TargetWP3Str[0] = 0;
127
128     // current route
129     if ( size > 0 ) {
130         SGWayPoint wp1 = globals->get_route()->get_waypoint( 0 );
131         accum += distance;
132         double eta = accum * METER_TO_NM / get_ground_speed();
133         if ( eta >= 100.0 ) { eta = 99.999; }
134         int major, minor;
135         if ( eta < (1.0/6.0) ) {
136             // within 10 minutes, bump up to min/secs
137             eta *= 60.0;
138         }
139         major = (int)eta;
140         minor = (int)((eta - (int)eta) * 60.0);
141         sprintf( TargetWP1Str, "%s %.2f NM  ETA %d:%02d",
142                  wp1.get_id().c_str(),
143                  accum*METER_TO_NM, major, minor );
144         // cout << "distance = " << distance*METER_TO_NM
145         //      << "  gndsp = " << get_ground_speed() 
146         //      << "  time = " << eta
147         //      << "  major = " << major
148         //      << "  minor = " << minor
149         //      << endl;
150     }
151
152     // next route
153     if ( size > 1 ) {
154         SGWayPoint wp2 = globals->get_route()->get_waypoint( 1 );
155         accum += wp2.get_distance();
156         
157         double eta = accum * METER_TO_NM / get_ground_speed();
158         if ( eta >= 100.0 ) { eta = 99.999; }
159         int major, minor;
160         if ( eta < (1.0/6.0) ) {
161             // within 10 minutes, bump up to min/secs
162             eta *= 60.0;
163         }
164         major = (int)eta;
165         minor = (int)((eta - (int)eta) * 60.0);
166         sprintf( TargetWP2Str, "%s %.2f NM  ETA %d:%02d",
167                  wp2.get_id().c_str(),
168                  accum*METER_TO_NM, major, minor );
169     }
170
171     // next route
172     if ( size > 2 ) {
173         for ( int i = 2; i < size; ++i ) {
174             accum += globals->get_route()->get_waypoint( i ).get_distance();
175         }
176         
177         SGWayPoint wpn = globals->get_route()->get_waypoint( size - 1 );
178
179         double eta = accum * METER_TO_NM / get_ground_speed();
180         if ( eta >= 100.0 ) { eta = 99.999; }
181         int major, minor;
182         if ( eta < (1.0/6.0) ) {
183             // within 10 minutes, bump up to min/secs
184             eta *= 60.0;
185         }
186         major = (int)eta;
187         minor = (int)((eta - (int)eta) * 60.0);
188         sprintf( TargetWP3Str, "%s %.2f NM  ETA %d:%02d",
189                  wpn.get_id().c_str(),
190                  accum*METER_TO_NM, major, minor );
191     }
192 }
193
194
195 void FGAutopilot::update_old_control_values() {
196     old_aileron = controls.get_aileron();
197     old_elevator = controls.get_elevator();
198     old_elevator_trim = controls.get_elevator_trim();
199     old_rudder = controls.get_rudder();
200 }
201
202
203 // Initialize autopilot subsystem
204 void FGAutopilot::init() {
205     FG_LOG( FG_AUTOPILOT, FG_INFO, "Init AutoPilot Subsystem" );
206
207     heading_hold = false ;      // turn the heading hold off
208     altitude_hold = false ;     // turn the altitude hold off
209     auto_throttle = false ;     // turn the auto throttle off
210
211     // Initialize target location to startup location
212     old_lat = FGBFI::getLatitude();
213     old_lon = FGBFI::getLongitude();
214     // set_WayPoint( old_lon, old_lat, 0.0, "default" );
215
216     MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
217         
218     TargetHeading = 0.0;        // default direction, due north
219     TargetAltitude = 3000;      // default altitude in meters
220     alt_error_accum = 0.0;
221     climb_error_accum = 0.0;
222
223     MakeTargetAltitudeStr( 3000.0);
224     MakeTargetHeadingStr( 0.0 );
225         
226     // These eventually need to be read from current_aircaft somehow.
227
228     // the maximum roll, in Deg
229     MaxRoll = 20;
230
231     // the deg from heading to start rolling out at, in Deg
232     RollOut = 20;
233
234     // how far can I move the aleron from center.
235     MaxAileron = .2;
236
237     // Smoothing distance for alerion control
238     RollOutSmooth = 10;
239
240     // Hardwired for now should be in options
241     // 25% max control variablilty  0.5 / 2.0
242     disengage_threshold = 1.0;
243
244 #if !defined( USING_SLIDER_CLASS )
245     MaxRollAdjust = 2 * MaxRoll;
246     RollOutAdjust = 2 * RollOut;
247     MaxAileronAdjust = 2 * MaxAileron;
248     RollOutSmoothAdjust = 2 * RollOutSmooth;
249 #endif  // !defined( USING_SLIDER_CLASS )
250
251     update_old_control_values();
252         
253     // Initialize GUI components of autopilot
254     // NewTgtAirportInit();
255     // fgAPAdjustInit() ;
256     // NewHeadingInit();
257     // NewAltitudeInit();
258 };
259
260
261 // Reset the autopilot system
262 void FGAutopilot::reset() {
263
264     heading_hold = false ;      // turn the heading hold off
265     altitude_hold = false ;     // turn the altitude hold off
266     auto_throttle = false ;     // turn the auto throttle off
267
268     TargetHeading = 0.0;        // default direction, due north
269     MakeTargetHeadingStr( TargetHeading );                      
270         
271     TargetAltitude = 3000;   // default altitude in meters
272     MakeTargetAltitudeStr( TargetAltitude );
273         
274     alt_error_accum = 0.0;
275     climb_error_accum = 0.0;
276         
277     update_old_control_values();
278
279     sprintf( NewTgtAirportId, "%s", fgGetString("/sim/startup/airport-id").c_str() );
280         
281     // TargetLatitude = FGBFI::getLatitude();
282     // TargetLongitude = FGBFI::getLongitude();
283     // set_WayPoint( FGBFI::getLongitude(), FGBFI::getLatitude(), 0.0, "reset" );
284
285     MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
286 }
287
288
289 static double NormalizeDegrees( double Input ) {
290     // normalize the input to the range (-180,180]
291     // Input should not be greater than -360 to 360.
292     // Current rules send the output to an undefined state.
293     if ( Input > 180 )
294         while(Input > 180 )
295             Input -= 360;
296     else if ( Input <= -180 )
297         while ( Input <= -180 )
298             Input += 360;
299     return ( Input );
300 };
301
302 static double LinearExtrapolate( double x, double x1, double y1, double x2, double y2 ) {
303     // This procedure extrapolates the y value for the x posistion on a line defined by x1,y1; x2,y2
304     //assert(x1 != x2); // Divide by zero error.  Cold abort for now
305
306         // Could be
307         // static double y = 0.0;
308         // double dx = x2 -x1;
309         // if( (dx < -FG_EPSILON ) || ( dx > FG_EPSILON ) )
310         // {
311
312     double m, b, y;          // the constants to find in y=mx+b
313     // double m, b;
314
315     m = ( y2 - y1 ) / ( x2 - x1 );   // calculate the m
316
317     b = y1 - m * x1;       // calculate the b
318
319     y = m * x + b;       // the final calculation
320
321     // }
322
323     return ( y );
324
325 };
326
327
328 int FGAutopilot::run() {
329     // Remove the following lines when the calling funcitons start
330     // passing in the data pointer
331
332     // get control settings 
333     // double aileron = FGBFI::getAileron();
334     // double elevator = FGBFI::getElevator();
335     // double elevator_trim = FGBFI::getElevatorTrim();
336     // double rudder = FGBFI::getRudder();
337         
338     double lat = FGBFI::getLatitude();
339     double lon = FGBFI::getLongitude();
340     double alt = FGBFI::getAltitude() * FEET_TO_METER;
341
342 #ifdef FG_FORCE_AUTO_DISENGAGE
343     // see if somebody else has changed them
344     if( fabs(aileron - old_aileron) > disengage_threshold ||
345         fabs(elevator - old_elevator) > disengage_threshold ||
346         fabs(elevator_trim - old_elevator_trim) > 
347         disengage_threshold ||          
348         fabs(rudder - old_rudder) > disengage_threshold )
349     {
350         // if controls changed externally turn autopilot off
351         waypoint_hold = false ;   // turn the target hold off
352         heading_hold = false ;    // turn the heading hold off
353         altitude_hold = false ;   // turn the altitude hold off
354         terrain_follow = false;   // turn the terrain_follow hold off
355         // auto_throttle = false; // turn the auto_throttle off
356
357         // stash this runs control settings
358         old_aileron = aileron;
359         old_elevator = elevator;
360         old_elevator_trim = elevator_trim;
361         old_rudder = rudder;
362         
363         return 0;
364     }
365 #endif
366         
367     // heading hold
368     if ( heading_hold == true ) {
369         if ( heading_mode == FG_DG_HEADING_LOCK ) {
370             // cout << "DG heading = " << FGSteam::get_DG_deg()
371             //      << " DG error = " << FGSteam::get_DG_err() << endl;
372
373             TargetHeading = DGTargetHeading + FGSteam::get_DG_err();
374             while ( TargetHeading <   0.0 ) { TargetHeading += 360.0; }
375             while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
376             MakeTargetHeadingStr( TargetHeading );
377         } else if ( heading_mode == FG_HEADING_LOCK ) {
378             // leave target heading alone
379         } else if ( heading_mode == FG_HEADING_NAV1 ) {
380             // track the NAV1 heading needle deflection
381             double cur_radial = current_radiostack->get_nav1_heading() +
382                 current_radiostack->get_nav1_magvar();
383             if ( current_radiostack->get_nav1_from_flag() ) {
384                 cur_radial += 180.0;
385                 while ( cur_radial >= 360.0 ) { cur_radial -= 360.0; }
386             }
387             double adjustment = 
388                 current_radiostack->get_nav1_heading_needle_deflection()
389                 * (current_radiostack->get_nav1_loc_dist() * METER_TO_NM);
390             if ( adjustment < -30.0 ) { adjustment = -30.0; }
391             if ( adjustment >  30.0 ) { adjustment =  30.0; }
392             TargetHeading = cur_radial + adjustment; 
393             while ( TargetHeading <   0.0 ) { TargetHeading += 360.0; }
394             while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
395 #if 0
396             if ( current_radiostack->get_nav1_to_flag() ||
397                  current_radiostack->get_nav1_from_flag() ) {
398                 // We have an appropriate radial selected that the
399                 // autopilot can follow
400                 double tgt_radial;
401                 double cur_radial;
402                 if ( current_radiostack->get_nav1_loc() ) {
403                     // localizers radials are "true"
404                     tgt_radial = current_radiostack->get_nav1_radial();
405                 } else {
406                     tgt_radial = current_radiostack->get_nav1_radial() +
407                         current_radiostack->get_nav1_magvar();
408                 }
409                 cur_radial = current_radiostack->get_nav1_heading() +
410                     current_radiostack->get_nav1_magvar();
411                 if ( current_radiostack->get_nav1_from_flag() ) {
412                     cur_radial += 180.0;
413                     while ( cur_radial >= 360.0 ) { cur_radial -= 360.0; }
414                 }
415                 // cout << "target rad (true) = " << tgt_radial 
416                 //      << "  current rad (true) = " << cur_radial
417                 //      << endl;
418
419                 double diff = (tgt_radial - cur_radial);
420                 while ( diff < -180.0 ) { diff += 360.0; }
421                 while ( diff > 180.0 ) { diff -= 360.0; }
422                 
423                 diff *= (current_radiostack->get_nav1_loc_dist() * METER_TO_NM);
424                 if ( diff < -30.0 ) { diff = -30.0; }
425                 if ( diff >  30.0 ) { diff =  30.0; }
426
427                 if ( current_radiostack->get_nav1_to_flag() ) {
428                     TargetHeading = cur_radial - diff;
429                 } else if ( current_radiostack->get_nav1_from_flag() ) {
430                     TargetHeading = cur_radial + diff;
431                 }
432                 while ( TargetHeading <   0.0 ) { TargetHeading += 360.0; }
433                 while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
434             } else {
435                 // neither TO, or FROM, maintain current heading.
436                 TargetHeading = FGBFI::getHeading();
437             }
438 #endif
439             MakeTargetHeadingStr( TargetHeading );
440             // cout << "target course (true) = " << TargetHeading << endl;
441         } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
442             // update target heading to waypoint
443
444             double wp_course, wp_distance;
445
446 #ifdef DO_fgAP_CORRECTED_COURSE
447             // compute course made good
448             // this needs lots of special casing before use
449             double course, reverse, distance, corrected_course;
450             // need to test for iter
451             geo_inverse_wgs_84( 0, //fgAPget_altitude(),
452                                 old_lat,
453                                 old_lon,
454                                 lat,
455                                 lon,
456                                 &course,
457                                 &reverse,
458                                 &distance );
459 #endif // DO_fgAP_CORRECTED_COURSE
460
461             // compute course to way_point
462             // need to test for iter
463             SGWayPoint wp = globals->get_route()->get_first();
464             wp.CourseAndDistance( lon, lat, alt, 
465                                   &wp_course, &wp_distance );
466
467 #ifdef DO_fgAP_CORRECTED_COURSE
468             corrected_course = course - wp_course;
469             if( fabs(corrected_course) > 0.1 )
470                 printf("fgAP: course %f  wp_course %f  %f  %f\n",
471                        course, wp_course, fabs(corrected_course),
472                        distance );
473 #endif // DO_fgAP_CORRECTED_COURSE
474                 
475             if ( wp_distance > 100 ) {
476                 // corrected_course = course - wp_course;
477                 TargetHeading = NormalizeDegrees(wp_course);
478             } else {
479                 cout << "Reached waypoint within " << wp_distance << "meters"
480                      << endl;
481
482                 // pop off this waypoint from the list
483                 if ( globals->get_route()->size() ) {
484                     globals->get_route()->delete_first();
485                 }
486
487                 // see if there are more waypoints on the list
488                 if ( globals->get_route()->size() ) {
489                     // more waypoints
490                     set_HeadingMode( FG_HEADING_WAYPOINT );
491                 } else {
492                     // end of the line
493                     heading_mode = FG_HEADING_LOCK;
494                     // use current heading
495                     TargetHeading = FGBFI::getHeading();
496                 }
497             }
498             MakeTargetHeadingStr( TargetHeading );
499             // Force this just in case
500             TargetDistance = wp_distance;
501             MakeTargetWPStr( wp_distance );
502         }
503
504         double RelHeading;
505         double TargetRoll;
506         double RelRoll;
507         double AileronSet;
508
509         RelHeading = NormalizeDegrees( TargetHeading - FGBFI::getHeading() );
510         // figure out how far off we are from desired heading
511
512         // Now it is time to deterime how far we should be rolled.
513         FG_LOG( FG_AUTOPILOT, FG_DEBUG, "RelHeading: " << RelHeading );
514
515
516         // Check if we are further from heading than the roll out point
517         if ( fabs( RelHeading ) > RollOut ) {
518             // set Target Roll to Max in desired direction
519             if ( RelHeading < 0 ) {
520                 TargetRoll = 0 - MaxRoll;
521             } else {
522                 TargetRoll = MaxRoll;
523             }
524         } else {
525             // We have to calculate the Target roll
526
527             // This calculation engine thinks that the Target roll
528             // should be a line from (RollOut,MaxRoll) to (-RollOut,
529             // -MaxRoll) I hope this works well.  If I get ambitious
530             // some day this might become a fancier curve or
531             // something.
532
533             TargetRoll = LinearExtrapolate( RelHeading, -RollOut,
534                                             -MaxRoll, RollOut,
535                                             MaxRoll );
536         }
537
538         // Target Roll has now been Found.
539
540         // Compare Target roll to Current Roll, Generate Rel Roll
541
542         FG_LOG( FG_COCKPIT, FG_BULK, "TargetRoll: " << TargetRoll );
543
544         RelRoll = NormalizeDegrees( TargetRoll - FGBFI::getRoll() );
545
546         // Check if we are further from heading than the roll out smooth point
547         if ( fabs( RelRoll ) > RollOutSmooth ) {
548             // set Target Roll to Max in desired direction
549             if ( RelRoll < 0 ) {
550                 AileronSet = 0 - MaxAileron;
551             } else {
552                 AileronSet = MaxAileron;
553             }
554         } else {
555             AileronSet = LinearExtrapolate( RelRoll, -RollOutSmooth,
556                                             -MaxAileron,
557                                             RollOutSmooth,
558                                             MaxAileron );
559         }
560
561         controls.set_aileron( AileronSet );
562         controls.set_rudder( AileronSet / 4.0 );
563         // controls.set_rudder( 0.0 );
564     }
565
566     // altitude hold
567     if ( altitude_hold ) {
568         double speed, max_climb, error;
569         double prop_error, int_error;
570         double prop_adj, int_adj, total_adj;
571
572         if ( altitude_mode == FG_ALTITUDE_LOCK ) {
573             // normal altitude hold
574             // cout << "TargetAltitude = " << TargetAltitude
575             //      << "Altitude = " << FGBFI::getAltitude() * FEET_TO_METER
576             //      << endl;
577             TargetClimbRate =
578                 ( TargetAltitude - FGBFI::getAltitude() * FEET_TO_METER ) * 8.0;
579         } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
580             double x = current_radiostack->get_nav1_gs_dist();
581             double y = (FGBFI::getAltitude() 
582                         - current_radiostack->get_nav1_elev()) * FEET_TO_METER;
583             double current_angle = atan2( y, x ) * RAD_TO_DEG;
584             // cout << "current angle = " << current_angle << endl;
585
586             double target_angle = current_radiostack->get_nav1_target_gs();
587             // cout << "target angle = " << target_angle << endl;
588
589             double gs_diff = target_angle - current_angle;
590             // cout << "difference from desired = " << gs_diff << endl;
591
592             // convert desired vertical path angle into a climb rate
593             double des_angle = current_angle - 10 * gs_diff;
594             // cout << "desired angle = " << des_angle << endl;
595
596             // convert to meter/min
597             // cout << "raw ground speed = " << cur_fdm_state->get_V_ground_speed() << endl;
598             double horiz_vel = cur_fdm_state->get_V_ground_speed()
599                 * FEET_TO_METER * 60.0;
600             // cout << "Horizontal vel = " << horiz_vel << endl;
601             TargetClimbRate = -sin( des_angle * DEG_TO_RAD ) * horiz_vel;
602             // cout << "TargetClimbRate = " << TargetClimbRate << endl;
603             /* climb_error_accum += gs_diff * 2.0; */
604             /* TargetClimbRate = gs_diff * 200.0 + climb_error_accum; */
605         } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
606             // brain dead ground hugging with no look ahead
607             TargetClimbRate =
608                 ( TargetAGL - FGBFI::getAGL()*FEET_TO_METER ) * 16.0;
609             // cout << "target agl = " << TargetAGL 
610             //      << "  current agl = " << fgAPget_agl() 
611             //      << "  target climb rate = " << TargetClimbRate 
612             //      << endl;
613         } else {
614             // just try to zero out rate of climb ...
615             TargetClimbRate = 0.0;
616         }
617
618         speed = get_speed();
619
620         if ( speed < min_climb ) {
621             max_climb = 0.0;
622         } else if ( speed < best_climb ) {
623             max_climb = ((best_climb - min_climb) - (best_climb - speed)) 
624                 * ideal_climb_rate 
625                 / (best_climb - min_climb);
626         } else {                        
627             max_climb = ( speed - best_climb ) * 10.0 + ideal_climb_rate;
628         }
629
630         // this first one could be optional if we wanted to allow
631         // better climb performance assuming we have the airspeed to
632         // support it.
633         if ( TargetClimbRate > ideal_climb_rate ) {
634             TargetClimbRate = ideal_climb_rate;
635         }
636
637         if ( TargetClimbRate > max_climb ) {
638             TargetClimbRate = max_climb;
639         }
640
641         if ( TargetClimbRate < -ideal_climb_rate ) {
642             TargetClimbRate = -ideal_climb_rate;
643         }
644
645         error = FGBFI::getVerticalSpeed() * FEET_TO_METER - TargetClimbRate;
646         // cout << "climb rate = " << fgAPget_climb() 
647         //      << "  error = " << error << endl;
648
649         // accumulate the error under the curve ... this really should
650         // be *= delta t
651         alt_error_accum += error;
652
653         // calculate integral error, and adjustment amount
654         int_error = alt_error_accum;
655         // printf("error = %.2f  int_error = %.2f\n", error, int_error);
656         int_adj = int_error / 20000.0;
657
658         // caclulate proportional error
659         prop_error = error;
660         prop_adj = prop_error / 2000.0;
661
662         total_adj = 0.9 * prop_adj + 0.1 * int_adj;
663         // if ( total_adj > 0.6 ) {
664         //     total_adj = 0.6;
665         // } else if ( total_adj < -0.2 ) {
666         //     total_adj = -0.2;
667         // }
668         if ( total_adj > 1.0 ) {
669             total_adj = 1.0;
670         } else if ( total_adj < -1.0 ) {
671             total_adj = -1.0;
672         }
673
674         controls.set_elevator( total_adj );
675     }
676
677     // auto throttle
678     if ( auto_throttle ) {
679         double error;
680         double prop_error, int_error;
681         double prop_adj, int_adj, total_adj;
682
683         error = TargetSpeed - get_speed();
684
685         // accumulate the error under the curve ... this really should
686         // be *= delta t
687         speed_error_accum += error;
688         if ( speed_error_accum > 2000.0 ) {
689             speed_error_accum = 2000.0;
690         }
691         else if ( speed_error_accum < -2000.0 ) {
692             speed_error_accum = -2000.0;
693         }
694
695         // calculate integral error, and adjustment amount
696         int_error = speed_error_accum;
697
698         // printf("error = %.2f  int_error = %.2f\n", error, int_error);
699         int_adj = int_error / 200.0;
700
701         // caclulate proportional error
702         prop_error = error;
703         prop_adj = 0.5 + prop_error / 50.0;
704
705         total_adj = 0.9 * prop_adj + 0.1 * int_adj;
706         if ( total_adj > 1.0 ) {
707             total_adj = 1.0;
708         }
709         else if ( total_adj < 0.0 ) {
710             total_adj = 0.0;
711         }
712
713         controls.set_throttle( FGControls::ALL_ENGINES, total_adj );
714     }
715
716 #ifdef THIS_CODE_IS_NOT_USED
717     if (Mode == 2) // Glide slope hold
718         {
719             double RelSlope;
720             double RelElevator;
721
722             // First, calculate Relative slope and normalize it
723             RelSlope = NormalizeDegrees( TargetSlope - get_pitch());
724
725             // Now calculate the elevator offset from current angle
726             if ( abs(RelSlope) > SlopeSmooth )
727                 {
728                     if ( RelSlope < 0 )     //  set RelElevator to max in the correct direction
729                         RelElevator = -MaxElevator;
730                     else
731                         RelElevator = MaxElevator;
732                 }
733
734             else
735                 RelElevator = LinearExtrapolate(RelSlope,-SlopeSmooth,-MaxElevator,SlopeSmooth,MaxElevator);
736
737             // set the elevator
738             fgElevMove(RelElevator);
739
740         }
741 #endif // THIS_CODE_IS_NOT_USED
742
743     // stash this runs control settings
744     //  update_old_control_values();
745     old_aileron = controls.get_aileron();
746     old_elevator = controls.get_elevator();
747     old_elevator_trim = controls.get_elevator_trim();
748     old_rudder = controls.get_rudder();
749
750     // for cross track error
751     old_lat = lat;
752     old_lon = lon;
753         
754         // Ok, we are done
755     return 0;
756 }
757
758
759 void FGAutopilot::set_HeadingMode( fgAutoHeadingMode mode ) {
760     heading_mode = mode;
761
762     if ( heading_mode == FG_DG_HEADING_LOCK ) {
763         // set heading hold to current heading (as read from DG)
764         DGTargetHeading = FGSteam::get_DG_deg();
765     } else if ( heading_mode == FG_HEADING_LOCK ) {
766         // set heading hold to current heading
767         TargetHeading = FGBFI::getHeading();
768     } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
769         if ( globals->get_route()->size() ) {
770             double course, distance;
771
772             old_lat = FGBFI::getLatitude();
773             old_lon = FGBFI::getLongitude();
774
775             waypoint = globals->get_route()->get_first();
776             waypoint.CourseAndDistance( FGBFI::getLongitude(),
777                                         FGBFI::getLatitude(),
778                                         FGBFI::getLatitude() * FEET_TO_METER,
779                                         &course, &distance );
780             TargetHeading = course;
781             TargetDistance = distance;
782             MakeTargetLatLonStr( waypoint.get_target_lat(),
783                                  waypoint.get_target_lon() );
784             MakeTargetWPStr( distance );
785
786             if ( waypoint.get_target_alt() > 0.0 ) {
787                 TargetAltitude = waypoint.get_target_alt();
788                 altitude_mode = FG_ALTITUDE_LOCK;
789                 set_AltitudeEnabled( true );
790                 MakeTargetAltitudeStr( TargetAltitude * METER_TO_FEET );
791             }
792
793             FG_LOG( FG_COCKPIT, FG_INFO, " set_HeadingMode: ( "
794                     << get_TargetLatitude()  << " "
795                     << get_TargetLongitude() << " ) "
796                     );
797         } else {
798             // no more way points, default to heading lock.
799             heading_mode = FG_HEADING_LOCK;
800             TargetHeading = FGBFI::getHeading();
801         }
802     }
803
804     MakeTargetHeadingStr( TargetHeading );                      
805     update_old_control_values();
806 }
807
808
809 void FGAutopilot::set_AltitudeMode( fgAutoAltitudeMode mode ) {
810     altitude_mode = mode;
811
812     alt_error_accum = 0.0;
813
814     if ( altitude_mode == FG_ALTITUDE_LOCK ) {
815         // lock at current altitude
816         TargetAltitude = FGBFI::getAltitude() * FEET_TO_METER;
817
818         if ( fgGetString("/sim/startup/units") == "feet" ) {
819             MakeTargetAltitudeStr( TargetAltitude * METER_TO_FEET );
820         } else {
821             MakeTargetAltitudeStr( TargetAltitude * METER_TO_FEET );
822         }
823     } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
824         climb_error_accum = 0.0;
825
826     } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
827         TargetAGL = FGBFI::getAGL() * FEET_TO_METER;
828
829         if ( fgGetString("/sim/startup/units") == "feet" ) {
830             MakeTargetAltitudeStr( TargetAGL * METER_TO_FEET );
831         } else {
832             MakeTargetAltitudeStr( TargetAGL * METER_TO_FEET );
833         }
834     }
835     
836     update_old_control_values();
837     FG_LOG( FG_COCKPIT, FG_INFO, " set_AltitudeMode():" );
838 }
839
840
841 #if 0
842 static inline double get_aoa( void ) {
843     return( cur_fdm_state->get_Gamma_vert_rad() * RAD_TO_DEG );
844 }
845
846 static inline double fgAPget_latitude( void ) {
847     return( cur_fdm_state->get_Latitude() * RAD_TO_DEG );
848 }
849
850 static inline double fgAPget_longitude( void ) {
851     return( cur_fdm_state->get_Longitude() * RAD_TO_DEG );
852 }
853
854 static inline double fgAPget_roll( void ) {
855     return( cur_fdm_state->get_Phi() * RAD_TO_DEG );
856 }
857
858 static inline double get_pitch( void ) {
859     return( cur_fdm_state->get_Theta() );
860 }
861
862 double fgAPget_heading( void ) {
863     return( cur_fdm_state->get_Psi() * RAD_TO_DEG );
864 }
865
866 static inline double fgAPget_altitude( void ) {
867     return( cur_fdm_state->get_Altitude() * FEET_TO_METER );
868 }
869
870 static inline double fgAPget_climb( void ) {
871     // return in meters per minute
872     return( cur_fdm_state->get_Climb_Rate() * FEET_TO_METER * 60 );
873 }
874
875 static inline double get_sideslip( void ) {
876     return( cur_fdm_state->get_Beta() );
877 }
878
879 static inline double fgAPget_agl( void ) {
880     double agl;
881
882     agl = cur_fdm_state->get_Altitude() * FEET_TO_METER
883         - scenery.cur_elev;
884
885     return( agl );
886 }
887 #endif
888
889
890 void FGAutopilot::AltitudeSet( double new_altitude ) {
891     double target_alt = new_altitude;
892
893     // cout << "new altitude = " << new_altitude << endl;
894
895     if ( fgGetString("/sim/startup/units") == "feet" ) {
896         target_alt = new_altitude * FEET_TO_METER;
897     }
898
899     if( target_alt < scenery.cur_elev ) {
900         target_alt = scenery.cur_elev;
901     }
902
903     TargetAltitude = target_alt;
904     altitude_mode = FG_ALTITUDE_LOCK;
905
906     // cout << "TargetAltitude = " << TargetAltitude << endl;
907
908     if ( fgGetString("/sim/startup/units") == "feet" ) {
909         target_alt *= METER_TO_FEET;
910     }
911     // ApAltitudeDialogInput->setValue((float)target_alt);
912     MakeTargetAltitudeStr( target_alt );
913         
914     update_old_control_values();
915 }
916
917
918 void FGAutopilot::AltitudeAdjust( double inc )
919 {
920     double target_alt, target_agl;
921
922     if ( fgGetString("/sim/startup/units") == "feet" ) {
923         target_alt = TargetAltitude * METER_TO_FEET;
924         target_agl = TargetAGL * METER_TO_FEET;
925     } else {
926         target_alt = TargetAltitude;
927         target_agl = TargetAGL;
928     }
929
930     // cout << "target_agl = " << target_agl << endl;
931     // cout << "target_agl / inc = " << target_agl / inc << endl;
932     // cout << "(int)(target_agl / inc) = " << (int)(target_agl / inc) << endl;
933
934     if ( fabs((int)(target_alt / inc) * inc - target_alt) < FG_EPSILON ) {
935         target_alt += inc;
936     } else {
937         target_alt = ( int ) ( target_alt / inc ) * inc + inc;
938     }
939
940     if ( fabs((int)(target_agl / inc) * inc - target_agl) < FG_EPSILON ) {
941         target_agl += inc;
942     } else {
943         target_agl = ( int ) ( target_agl / inc ) * inc + inc;
944     }
945
946     if ( fgGetString("/sim/startup/units") == "feet" ) {
947         target_alt *= FEET_TO_METER;
948         target_agl *= FEET_TO_METER;
949     }
950
951     TargetAltitude = target_alt;
952     TargetAGL = target_agl;
953         
954     if ( fgGetString("/sim/startup/units") == "feet" )
955         target_alt *= METER_TO_FEET;
956     if ( fgGetString("/sim/startup/units") == "feet" )
957         target_agl *= METER_TO_FEET;
958
959     if ( altitude_mode == FG_ALTITUDE_LOCK ) {
960         MakeTargetAltitudeStr( target_alt );
961     } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
962         MakeTargetAltitudeStr( target_agl );
963     }
964
965     update_old_control_values();
966 }
967
968
969 void FGAutopilot::HeadingAdjust( double inc ) {
970     if ( heading_mode != FG_DG_HEADING_LOCK && heading_mode != FG_HEADING_LOCK )
971     {
972         heading_mode = FG_DG_HEADING_LOCK;
973     }
974
975     if ( heading_mode == FG_DG_HEADING_LOCK ) {
976         double target = ( int ) ( DGTargetHeading / inc ) * inc + inc;
977         DGTargetHeading = NormalizeDegrees( target );
978     } else {
979         double target = ( int ) ( TargetHeading / inc ) * inc + inc;
980         TargetHeading = NormalizeDegrees( target );
981     }
982
983     update_old_control_values();
984 }
985
986
987 void FGAutopilot::HeadingSet( double new_heading ) {
988     heading_mode = FG_HEADING_LOCK;
989         
990     new_heading = NormalizeDegrees( new_heading );
991     TargetHeading = new_heading;
992     // following cast needed ambiguous plib
993     // ApHeadingDialogInput -> setValue ((float)APData->TargetHeading );
994     MakeTargetHeadingStr( TargetHeading );                      
995     update_old_control_values();
996 }
997
998 void FGAutopilot::AutoThrottleAdjust( double inc ) {
999     double target = ( int ) ( TargetSpeed / inc ) * inc + inc;
1000
1001     TargetSpeed = target;
1002 }
1003
1004
1005 void FGAutopilot::set_AutoThrottleEnabled( bool value ) {
1006     auto_throttle = value;
1007
1008     if ( auto_throttle == true ) {
1009         TargetSpeed = FGBFI::getAirspeed();
1010         speed_error_accum = 0.0;
1011     }
1012
1013     update_old_control_values();
1014     FG_LOG( FG_COCKPIT, FG_INFO, " fgAPSetAutoThrottle: ("
1015             << auto_throttle << ") " << TargetSpeed );
1016 }