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