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