]> git.mxchange.org Git - flightgear.git/blob - src/Autopilot/newauto.cxx
Change FGSteam into a proper subsystem rather than a collection of
[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 #include <string.h>             // strcmp()
32
33 #include <simgear/constants.h>
34 #include <simgear/sg_inlines.h>
35 #include <simgear/debug/logstream.hxx>
36 #include <simgear/math/sg_geodesy.hxx>
37 #include <simgear/math/sg_random.h>
38 #include <simgear/route/route.hxx>
39
40 #include <Cockpit/steam.hxx>
41 #include <Cockpit/radiostack.hxx>
42 #include <Controls/controls.hxx>
43 #include <FDM/flight.hxx>
44 #include <Main/globals.hxx>
45 #include <Scenery/scenery.hxx>
46
47 #include "newauto.hxx"
48
49
50 /// These statics will eventually go into the class
51 /// they are just here while I am experimenting -- NHV :-)
52 // AutoPilot Gain Adjuster members
53 static double MaxRollAdjust;        // MaxRollAdjust       = 2 * APData->MaxRoll;
54 static double RollOutAdjust;        // RollOutAdjust       = 2 * APData->RollOut;
55 static double MaxAileronAdjust;     // MaxAileronAdjust    = 2 * APData->MaxAileron;
56 static double RollOutSmoothAdjust;  // RollOutSmoothAdjust = 2 * APData->RollOutSmooth;
57
58 static char NewTgtAirportId[16];
59 // static char NewTgtAirportLabel[] = "Enter New TgtAirport ID"; 
60
61 extern char *coord_format_lat(float);
62 extern char *coord_format_lon(float);
63                         
64
65 // constructor
66 FGAutopilot::FGAutopilot()
67 {
68 }
69
70 // destructor
71 FGAutopilot::~FGAutopilot() {}
72
73
74 void FGAutopilot::MakeTargetLatLonStr( double lat, double lon ) {
75     sprintf( TargetLatitudeStr , "%s", coord_format_lat(get_TargetLatitude()));
76     sprintf( TargetLongitudeStr, "%s", coord_format_lon(get_TargetLongitude()));
77     sprintf( TargetLatLonStr, "%s  %s", TargetLatitudeStr, TargetLongitudeStr );
78 }
79
80
81 void FGAutopilot::MakeTargetAltitudeStr( double altitude ) {
82     if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
83         sprintf( TargetAltitudeStr, "APAltitude  %6.0f+", altitude );
84     } else {
85         sprintf( TargetAltitudeStr, "APAltitude  %6.0f", altitude );
86     }
87 }
88
89
90 void FGAutopilot::MakeTargetHeadingStr( double bearing ) {
91     if ( bearing < 0. ) {
92         bearing += 360.;
93     } else if (bearing > 360. ) {
94         bearing -= 360.;
95     }
96     sprintf( TargetHeadingStr, "APHeading  %6.1f", bearing );
97 }
98
99
100 static inline double get_speed( void ) {
101     return( cur_fdm_state->get_V_equiv_kts() );
102 }
103
104 static inline double get_ground_speed() {
105     // starts in ft/s so we convert to kts
106     static const SGPropertyNode * speedup_node = fgGetNode("/sim/speed-up");
107
108     double ft_s = cur_fdm_state->get_V_ground_speed() 
109         * speedup_node->getIntValue();
110     double kts = ft_s * SG_FEET_TO_METER * 3600 * SG_METER_TO_NM;
111
112     return kts;
113 }
114
115
116 void FGAutopilot::MakeTargetWPStr( double distance ) {
117     static time_t last_time = 0;
118     time_t current_time = time(NULL);
119     if ( last_time == current_time ) {
120         return;
121     }
122
123     last_time = current_time;
124
125     double accum = 0.0;
126
127     int size = globals->get_route()->size();
128
129     // start by wiping the strings
130     TargetWP1Str[0] = 0;
131     TargetWP2Str[0] = 0;
132     TargetWP3Str[0] = 0;
133
134     // current route
135     if ( size > 0 ) {
136         SGWayPoint wp1 = globals->get_route()->get_waypoint( 0 );
137         accum += distance;
138         double eta = accum * SG_METER_TO_NM / get_ground_speed();
139         if ( eta >= 100.0 ) { eta = 99.999; }
140         int major, minor;
141         if ( eta < (1.0/6.0) ) {
142             // within 10 minutes, bump up to min/secs
143             eta *= 60.0;
144         }
145         major = (int)eta;
146         minor = (int)((eta - (int)eta) * 60.0);
147         sprintf( TargetWP1Str, "%s %.2f NM  ETA %d:%02d",
148                  wp1.get_id().c_str(),
149                  accum*SG_METER_TO_NM, major, minor );
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 * SG_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*SG_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 * SG_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*SG_METER_TO_NM, major, minor );
191     }
192 }
193
194
195 void FGAutopilot::update_old_control_values() {
196     old_aileron = globals->get_controls()->get_aileron();
197     old_elevator = globals->get_controls()->get_elevator();
198     old_elevator_trim = globals->get_controls()->get_elevator_trim();
199     old_rudder = globals->get_controls()->get_rudder();
200 }
201
202
203 // Initialize autopilot subsystem
204
205 void FGAutopilot::init ()
206 {
207     SG_LOG( SG_AUTOPILOT, SG_INFO, "Init AutoPilot Subsystem" );
208
209     // bind data input property nodes...
210     latitude_node = fgGetNode("/position/latitude-deg", true);
211     longitude_node = fgGetNode("/position/longitude-deg", true);
212     altitude_node = fgGetNode("/position/altitude-ft", true);
213     altitude_agl_node = fgGetNode("/position/altitude-agl-ft", true);
214     vertical_speed_node = fgGetNode("/velocities/vertical-speed-fps", true);
215     heading_node = fgGetNode("/orientation/heading-deg", true);
216     roll_node = fgGetNode("/orientation/roll-deg", true);
217     pitch_node = fgGetNode("/orientation/pitch-deg", true);
218
219
220
221     // bind config property nodes...
222     TargetClimbRate
223         = fgGetNode("/autopilot/config/target-climb-rate-fpm", true);
224     TargetDescentRate
225         = fgGetNode("/autopilot/config/target-descent-rate-fpm", true);
226     min_climb = fgGetNode("/autopilot/config/min-climb-speed-kt", true);
227     best_climb = fgGetNode("/autopilot/config/best-climb-speed-kt", true);
228     elevator_adj_factor
229         = fgGetNode("/autopilot/config/elevator-adj-factor", true);
230     integral_contrib
231         = fgGetNode("/autopilot/config/integral-contribution", true);
232     zero_pitch_throttle
233         = fgGetNode("/autopilot/config/zero-pitch-throttle", true);
234     zero_pitch_trim_full_throttle
235         = fgGetNode("/autopilot/config/zero-pitch-trim-full-throttle", true);
236     max_aileron_node = fgGetNode("/autopilot/config/max-aileron", true);
237     max_roll_node = fgGetNode("/autopilot/config/max-roll-deg", true);
238     roll_out_node = fgGetNode("/autopilot/config/roll-out-deg", true);
239     roll_out_smooth_node = fgGetNode("/autopilot/config/roll-out-smooth-deg", true);
240
241     current_throttle = fgGetNode("/controls/throttle");
242
243     // initialize config properties with defaults (in case config isn't there)
244     if ( TargetClimbRate->getFloatValue() < 1 )
245         fgSetFloat( "/autopilot/config/target-climb-rate-fpm", 500);
246     if ( TargetDescentRate->getFloatValue() < 1 )
247         fgSetFloat( "/autopilot/config/target-descent-rate-fpm", 1000 );
248     if ( min_climb->getFloatValue() < 1)
249         fgSetFloat( "/autopilot/config/min-climb-speed-kt", 70 );
250     if (best_climb->getFloatValue() < 1)
251         fgSetFloat( "/autopilot/config/best-climb-speed-kt", 120 );
252     if (elevator_adj_factor->getFloatValue() < 1)
253         fgSetFloat( "/autopilot/config/elevator-adj-factor", 5000 );
254     if ( integral_contrib->getFloatValue() < 0.0000001 )
255         fgSetFloat( "/autopilot/config/integral-contribution", 0.01 );
256     if ( zero_pitch_throttle->getFloatValue() < 0.0000001 )
257         fgSetFloat( "/autopilot/config/zero-pitch-throttle", 0.60 );
258     if ( zero_pitch_trim_full_throttle->getFloatValue() < 0.0000001 )
259         fgSetFloat( "/autopilot/config/zero-pitch-trim-full-throttle", 0.15 );
260     if ( max_aileron_node->getFloatValue() < 0.0000001 )
261         fgSetFloat( "/autopilot/config/max-aileron", 0.2 );
262     if ( max_roll_node->getFloatValue() < 0.0000001 )
263         fgSetFloat( "/autopilot/config/max-roll-deg", 20 );
264     if ( roll_out_node->getFloatValue() < 0.0000001 )
265         fgSetFloat( "/autopilot/config/roll-out-deg", 20 );
266     if ( roll_out_smooth_node->getFloatValue() < 0.0000001 )
267         fgSetFloat( "/autopilot/config/roll-out-smooth-deg", 10 );
268
269     /* set defaults */
270     heading_hold = false ;      // turn the heading hold off
271     altitude_hold = false ;     // turn the altitude hold off
272     auto_throttle = false ;     // turn the auto throttle off
273     heading_mode = DEFAULT_AP_HEADING_LOCK;
274     altitude_mode = DEFAULT_AP_ALTITUDE_LOCK;
275
276     DGTargetHeading = fgGetDouble("/autopilot/settings/heading-bug-deg");
277     TargetHeading = fgGetDouble("/autopilot/settings/heading-bug-deg");
278     TargetAltitude = fgGetDouble("/autopilot/settings/altitude-ft") * SG_FEET_TO_METER;
279
280     // Initialize target location to startup location
281     old_lat = latitude_node->getDoubleValue();
282     old_lon = longitude_node->getDoubleValue();
283     // set_WayPoint( old_lon, old_lat, 0.0, "default" );
284
285     MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
286         
287     alt_error_accum = 0.0;
288     climb_error_accum = 0.0;
289
290     MakeTargetAltitudeStr( TargetAltitude );
291     MakeTargetHeadingStr( TargetHeading );
292         
293     // These eventually need to be read from current_aircaft somehow.
294
295     // the maximum roll, in Deg
296     MaxRoll = 20;
297
298     // the deg from heading to start rolling out at, in Deg
299     RollOut = 20;
300
301     // Smoothing distance for alerion control
302     RollOutSmooth = 10;
303
304     // Hardwired for now should be in options
305     // 25% max control variablilty  0.5 / 2.0
306     disengage_threshold = 1.0;
307
308 #if !defined( USING_SLIDER_CLASS )
309     MaxRollAdjust = 2 * MaxRoll;
310     RollOutAdjust = 2 * RollOut;
311     //MaxAileronAdjust = 2 * MaxAileron;
312     RollOutSmoothAdjust = 2 * RollOutSmooth;
313 #endif  // !defined( USING_SLIDER_CLASS )
314
315     update_old_control_values();
316 };
317
318 void
319 FGAutopilot::bind ()
320 {
321     // Autopilot control property get/set bindings
322     fgTie("/autopilot/locks/altitude", this,
323           &FGAutopilot::getAPAltitudeLock, &FGAutopilot::setAPAltitudeLock);
324     fgSetArchivable("/autopilot/locks/altitude");
325     fgTie("/autopilot/settings/altitude-ft", this,
326           &FGAutopilot::getAPAltitude, &FGAutopilot::setAPAltitude);
327     fgSetArchivable("/autopilot/settings/altitude-ft");
328     fgTie("/autopilot/locks/glide-slope", this,
329           &FGAutopilot::getAPGSLock, &FGAutopilot::setAPGSLock);
330     fgSetArchivable("/autopilot/locks/glide-slope");
331     fgSetDouble("/autopilot/settings/altitude-ft", 3000.0f);
332     fgTie("/autopilot/locks/terrain", this,
333           &FGAutopilot::getAPTerrainLock, &FGAutopilot::setAPTerrainLock);
334     fgSetArchivable("/autopilot/locks/terrain");
335     fgTie("/autopilot/settings/climb-rate-fpm", this,
336           &FGAutopilot::getAPClimb, &FGAutopilot::setAPClimb, false);
337     fgSetArchivable("/autopilot/settings/climb-rate-fpm");
338     fgTie("/autopilot/locks/heading", this,
339           &FGAutopilot::getAPHeadingLock, &FGAutopilot::setAPHeadingLock);
340     fgSetArchivable("/autopilot/locks/heading");
341     fgTie("/autopilot/settings/heading-bug-deg", this,
342           &FGAutopilot::getAPHeadingBug, &FGAutopilot::setAPHeadingBug);
343     fgSetArchivable("/autopilot/settings/heading-bug-deg");
344     fgSetDouble("/autopilot/settings/heading-bug-deg", 0.0f);
345     fgTie("/autopilot/locks/wing-leveler", this,
346           &FGAutopilot::getAPWingLeveler, &FGAutopilot::setAPWingLeveler);
347     fgSetArchivable("/autopilot/locks/wing-leveler");
348     fgTie("/autopilot/locks/nav[0]", this,
349           &FGAutopilot::getAPNAV1Lock, &FGAutopilot::setAPNAV1Lock);
350     fgSetArchivable("/autopilot/locks/nav[0]");
351     fgTie("/autopilot/locks/auto-throttle", this,
352           &FGAutopilot::getAPAutoThrottleLock,
353           &FGAutopilot::setAPAutoThrottleLock);
354     fgSetArchivable("/autopilot/locks/auto-throttle");
355     fgTie("/autopilot/control-overrides/rudder", this,
356           &FGAutopilot::getAPRudderControl,
357           &FGAutopilot::setAPRudderControl);
358     fgSetArchivable("/autopilot/control-overrides/rudder");
359     fgTie("/autopilot/control-overrides/elevator", this,
360           &FGAutopilot::getAPElevatorControl,
361           &FGAutopilot::setAPElevatorControl);
362     fgSetArchivable("/autopilot/control-overrides/elevator");
363     fgTie("/autopilot/control-overrides/throttle", this,
364           &FGAutopilot::getAPThrottleControl,
365           &FGAutopilot::setAPThrottleControl);
366     fgSetArchivable("/autopilot/control-overrides/throttle");
367 }
368
369 void
370 FGAutopilot::unbind ()
371 {
372 }
373
374 // Reset the autopilot system
375 void FGAutopilot::reset() {
376
377     heading_hold = false ;      // turn the heading hold off
378     altitude_hold = false ;     // turn the altitude hold off
379     auto_throttle = false ;     // turn the auto throttle off
380     heading_mode = DEFAULT_AP_HEADING_LOCK;
381
382     // TargetHeading = 0.0;     // default direction, due north
383     MakeTargetHeadingStr( TargetHeading );                      
384         
385     // TargetAltitude = 3000;   // default altitude in meters
386     MakeTargetAltitudeStr( TargetAltitude );
387         
388     alt_error_accum = 0.0;
389     climb_error_accum = 0.0;
390         
391     update_old_control_values();
392
393     sprintf( NewTgtAirportId, "%s", fgGetString("/sim/startup/airport-id") );
394         
395     MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
396 }
397
398
399 static double NormalizeDegrees( double Input ) {
400     // normalize the input to the range (-180,180]
401     // Input should not be greater than -360 to 360.
402     // Current rules send the output to an undefined state.
403     while ( Input > 180.0 ) { Input -= 360.0; }
404     while ( Input <= -180.0 ) { Input += 360.0; }
405
406     return Input;
407 };
408
409 static double LinearExtrapolate( double x, double x1, double y1, double x2, double y2 ) {
410     // This procedure extrapolates the y value for the x posistion on a line defined by x1,y1; x2,y2
411     //assert(x1 != x2); // Divide by zero error.  Cold abort for now
412
413         // Could be
414         // static double y = 0.0;
415         // double dx = x2 -x1;
416         // if( (dx < -SG_EPSILON ) || ( dx > SG_EPSILON ) )
417         // {
418
419     double m, b, y;          // the constants to find in y=mx+b
420     // double m, b;
421
422     m = ( y2 - y1 ) / ( x2 - x1 );   // calculate the m
423
424     b = y1 - m * x1;       // calculate the b
425
426     y = m * x + b;       // the final calculation
427
428     // }
429
430     return ( y );
431
432 };
433
434
435 void
436 FGAutopilot::update (double dt)
437 {
438     // Remove the following lines when the calling funcitons start
439     // passing in the data pointer
440
441     // get control settings 
442         
443     double lat = latitude_node->getDoubleValue();
444     double lon = longitude_node->getDoubleValue();
445     double alt = altitude_node->getDoubleValue() * SG_FEET_TO_METER;
446
447     // get config settings
448     MaxAileron = max_aileron_node->getDoubleValue();
449     MaxRoll = max_roll_node->getDoubleValue();
450     RollOut = roll_out_node->getDoubleValue();
451     RollOutSmooth = roll_out_smooth_node->getDoubleValue();
452
453     SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run()  lat = " << lat <<
454             "  lon = " << lon << "  alt = " << alt );
455         
456 #ifdef FG_FORCE_AUTO_DISENGAGE
457     // see if somebody else has changed them
458     if( fabs(aileron - old_aileron) > disengage_threshold ||
459         fabs(elevator - old_elevator) > disengage_threshold ||
460         fabs(elevator_trim - old_elevator_trim) > 
461         disengage_threshold ||          
462         fabs(rudder - old_rudder) > disengage_threshold )
463     {
464         // if controls changed externally turn autopilot off
465         waypoint_hold = false ;   // turn the target hold off
466         heading_hold = false ;    // turn the heading hold off
467         altitude_hold = false ;   // turn the altitude hold off
468         terrain_follow = false;   // turn the terrain_follow hold off
469         // auto_throttle = false; // turn the auto_throttle off
470
471         // stash this runs control settings
472         old_aileron = aileron;
473         old_elevator = elevator;
474         old_elevator_trim = elevator_trim;
475         old_rudder = rudder;
476         
477         return 0;
478     }
479 #endif
480         
481     // heading hold
482     if ( heading_hold == true ) {
483         if ( heading_mode == FG_DG_HEADING_LOCK ) {
484             TargetHeading = DGTargetHeading +
485               globals->get_steam()->get_DG_err();
486             while ( TargetHeading <   0.0 ) { TargetHeading += 360.0; }
487             while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
488             MakeTargetHeadingStr( TargetHeading );
489         } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
490             // we don't set a specific target heading in
491             // TC_HEADING_LOCK mode, we instead try to keep the turn
492             // coordinator zero'd
493         } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
494             // leave "true" target heading as is
495             while ( TargetHeading <   0.0 ) { TargetHeading += 360.0; }
496             while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
497             MakeTargetHeadingStr( TargetHeading );
498         } else if ( heading_mode == FG_HEADING_NAV1 ) {
499             // track the NAV1 heading needle deflection
500
501             // determine our current radial position relative to the
502             // navaid in "true" heading.
503             double cur_radial = current_radiostack->get_nav1_heading();
504             if ( current_radiostack->get_nav1_loc() ) {
505                 // ILS localizers radials are already "true" in our
506                 // database
507             } else {
508                 cur_radial += current_radiostack->get_nav1_magvar();
509             }
510             if ( current_radiostack->get_nav1_from_flag() ) {
511                 cur_radial += 180.0;
512                 while ( cur_radial >= 360.0 ) { cur_radial -= 360.0; }
513             }
514
515             // determine the target radial in "true" heading
516             double tgt_radial = current_radiostack->get_nav1_radial();
517             if ( current_radiostack->get_nav1_loc() ) {
518                 // ILS localizers radials are already "true" in our
519                 // database
520             } else {
521                 // VOR radials need to have that vor's offset added in
522                 tgt_radial += current_radiostack->get_nav1_magvar();
523             }
524
525             // determine the heading adjustment needed.
526             double adjustment = 
527                 current_radiostack->get_nav1_heading_needle_deflection()
528                 * (current_radiostack->get_nav1_loc_dist() * SG_METER_TO_NM);
529             SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
530
531             // clamp closer when inside cone when beyond 5km...
532             if (current_radiostack->get_nav1_loc_dist() > 5000) {
533               double clamp_angle = fabs(current_radiostack->get_nav1_heading_needle_deflection()) * 3;
534               if (clamp_angle < 30)
535                 SG_CLAMP_RANGE( adjustment, -clamp_angle, clamp_angle);
536             }
537
538             // determine the target heading to fly to intercept the
539             // tgt_radial
540             TargetHeading = tgt_radial + adjustment; 
541             while ( TargetHeading <   0.0 ) { TargetHeading += 360.0; }
542             while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
543
544             MakeTargetHeadingStr( TargetHeading );
545         } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
546             // update target heading to waypoint
547
548             double wp_course, wp_distance;
549
550 #ifdef DO_fgAP_CORRECTED_COURSE
551             // compute course made good
552             // this needs lots of special casing before use
553             double course, reverse, distance, corrected_course;
554             // need to test for iter
555             geo_inverse_wgs_84( 0, //fgAPget_altitude(),
556                                 old_lat,
557                                 old_lon,
558                                 lat,
559                                 lon,
560                                 &course,
561                                 &reverse,
562                                 &distance );
563 #endif // DO_fgAP_CORRECTED_COURSE
564
565             // compute course to way_point
566             // need to test for iter
567             SGWayPoint wp = globals->get_route()->get_first();
568             wp.CourseAndDistance( lon, lat, alt, 
569                                   &wp_course, &wp_distance );
570
571 #ifdef DO_fgAP_CORRECTED_COURSE
572             corrected_course = course - wp_course;
573             if( fabs(corrected_course) > 0.1 )
574                 printf("fgAP: course %f  wp_course %f  %f  %f\n",
575                        course, wp_course, fabs(corrected_course),
576                        distance );
577 #endif // DO_fgAP_CORRECTED_COURSE
578                 
579             if ( wp_distance > 100 ) {
580                 // corrected_course = course - wp_course;
581                 TargetHeading = NormalizeDegrees(wp_course);
582             } else {
583                 // pop off this waypoint from the list
584                 if ( globals->get_route()->size() ) {
585                     globals->get_route()->delete_first();
586                 }
587
588                 // see if there are more waypoints on the list
589                 if ( globals->get_route()->size() ) {
590                     // more waypoints
591                     set_HeadingMode( FG_HEADING_WAYPOINT );
592                 } else {
593                     // end of the line
594                     heading_mode = FG_TRUE_HEADING_LOCK;
595                     // use current heading
596                     TargetHeading = heading_node->getDoubleValue();
597                 }
598             }
599             MakeTargetHeadingStr( TargetHeading );
600             // Force this just in case
601             TargetDistance = wp_distance;
602             MakeTargetWPStr( wp_distance );
603         }
604
605         if ( heading_mode == FG_TC_HEADING_LOCK ) {
606             // drive the turn coordinator to zero
607             double turn = globals->get_steam()->get_TC_std();
608             double AileronSet = -turn / 2.0;
609             SG_CLAMP_RANGE( AileronSet, -1.0, 1.0 );
610             globals->get_controls()->set_aileron( AileronSet );
611             globals->get_controls()->set_rudder( AileronSet / 4.0 );
612         } else {
613             // steer towards the target heading
614
615             double RelHeading;
616             double TargetRoll;
617             double RelRoll;
618             double AileronSet;
619
620             RelHeading
621                 = NormalizeDegrees( TargetHeading
622                                     - heading_node->getDoubleValue() );
623             // figure out how far off we are from desired heading
624
625             // Now it is time to deterime how far we should be rolled.
626             SG_LOG( SG_AUTOPILOT, SG_DEBUG,
627                     "Heading = " << heading_node->getDoubleValue() <<
628                     " TargetHeading = " << TargetHeading <<
629                     " RelHeading = " << RelHeading );
630
631             // Check if we are further from heading than the roll out point
632             if ( fabs( RelHeading ) > RollOut ) {
633                 // set Target Roll to Max in desired direction
634                 if ( RelHeading < 0 ) {
635                     TargetRoll = 0 - MaxRoll;
636                 } else {
637                     TargetRoll = MaxRoll;
638                 }
639             } else {
640                 // We have to calculate the Target roll
641
642                 // This calculation engine thinks that the Target roll
643                 // should be a line from (RollOut,MaxRoll) to (-RollOut,
644                 // -MaxRoll) I hope this works well.  If I get ambitious
645                 // some day this might become a fancier curve or
646                 // something.
647
648                 TargetRoll = LinearExtrapolate( RelHeading, -RollOut,
649                                                 -MaxRoll, RollOut,
650                                                 MaxRoll );
651             }
652
653             // Target Roll has now been Found.
654
655             // Compare Target roll to Current Roll, Generate Rel Roll
656
657             SG_LOG( SG_COCKPIT, SG_BULK, "TargetRoll: " << TargetRoll );
658
659             RelRoll = NormalizeDegrees( TargetRoll 
660                                         - roll_node->getDoubleValue() );
661
662             // Check if we are further from heading than the roll out
663             // smooth point
664             if ( fabs( RelRoll ) > RollOutSmooth ) {
665                 // set Target Roll to Max in desired direction
666                 if ( RelRoll < 0 ) {
667                 AileronSet = 0 - MaxAileron;
668                 } else {
669                     AileronSet = MaxAileron;
670                 }
671             } else {
672                 AileronSet = LinearExtrapolate( RelRoll, -RollOutSmooth,
673                                                 -MaxAileron,
674                                                 RollOutSmooth,
675                                                 MaxAileron );
676             }
677
678             globals->get_controls()->set_aileron( AileronSet );
679             globals->get_controls()->set_rudder( AileronSet / 4.0 );
680             // controls.set_rudder( 0.0 );
681         }
682     }
683
684     // altitude hold
685     if ( altitude_hold ) {
686         double climb_rate;
687         double speed, max_climb, error;
688         double prop_error, int_error;
689         double prop_adj, int_adj, total_adj;
690
691         if ( altitude_mode == FG_ALTITUDE_LOCK ) {
692             climb_rate =
693                 ( TargetAltitude -
694                   globals->get_steam()->get_ALT_ft() * SG_FEET_TO_METER ) * 8.0;
695         } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
696             double x = current_radiostack->get_nav1_gs_dist();
697             double y = (altitude_node->getDoubleValue()
698                         - current_radiostack->get_nav1_elev()) * SG_FEET_TO_METER;
699             double current_angle = atan2( y, x ) * SGD_RADIANS_TO_DEGREES;
700
701             double target_angle = current_radiostack->get_nav1_target_gs();
702
703             double gs_diff = target_angle - current_angle;
704
705             // convert desired vertical path angle into a climb rate
706             double des_angle = current_angle - 10 * gs_diff;
707
708             // convert to meter/min
709             double horiz_vel = cur_fdm_state->get_V_ground_speed()
710                 * SG_FEET_TO_METER * 60.0;
711             climb_rate = -sin( des_angle * SGD_DEGREES_TO_RADIANS ) * horiz_vel;
712             /* climb_error_accum += gs_diff * 2.0; */
713             /* climb_rate = gs_diff * 200.0 + climb_error_accum; */
714         } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
715             // brain dead ground hugging with no look ahead
716             climb_rate =
717                 ( TargetAGL - altitude_agl_node->getDoubleValue()
718                   * SG_FEET_TO_METER ) * 16.0;
719         } else {
720             // just try to zero out rate of climb ...
721             climb_rate = 0.0;
722         }
723
724         speed = get_speed();
725
726         if ( speed < min_climb->getFloatValue() ) {
727             max_climb = 0.0;
728         } else if ( speed < best_climb->getFloatValue() ) {
729             max_climb = ((best_climb->getFloatValue()
730                           - min_climb->getFloatValue())
731                          - (best_climb->getFloatValue() - speed)) 
732                 * fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER) 
733                 / (best_climb->getFloatValue() - min_climb->getFloatValue());
734         } else {                        
735             max_climb = ( speed - best_climb->getFloatValue() ) * 10.0
736                 + fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
737         }
738
739         // this first one could be optional if we wanted to allow
740         // better climb performance assuming we have the airspeed to
741         // support it.
742         if ( climb_rate >
743              fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER) ) {
744             climb_rate
745                 = fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
746         }
747
748         if ( climb_rate > max_climb ) {
749             climb_rate = max_climb;
750         }
751
752         if ( climb_rate <
753              -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER) ) {
754             climb_rate
755                 = -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER);
756         }
757
758         error = vertical_speed_node->getDoubleValue() * 60
759             - climb_rate * SG_METER_TO_FEET;
760
761         // accumulate the error under the curve ... this really should
762         // be *= delta t
763         alt_error_accum += error;
764
765         // calculate integral error, and adjustment amount
766         int_error = alt_error_accum;
767         // printf("error = %.2f  int_error = %.2f\n", error, int_error);
768         
769         // scale elev_adj_factor by speed of aircraft in relation to min climb 
770         double elev_adj_factor = elevator_adj_factor->getFloatValue();
771         elev_adj_factor *=
772           pow(float(speed / min_climb->getFloatValue()), 3.0f);
773
774         int_adj = int_error / elev_adj_factor;
775
776         // caclulate proportional error
777         prop_error = error;
778         prop_adj = prop_error / elev_adj_factor;
779
780         total_adj = ((double) 1.0 - (double) integral_contrib->getFloatValue()) * prop_adj
781             + (double) integral_contrib->getFloatValue() * int_adj;
782
783         // stop on autopilot trim at 30% +/-
784 //      if ( total_adj > 0.3 ) {
785 //           total_adj = 0.3;
786 //       } else if ( total_adj < -0.3 ) {
787 //           total_adj = -0.3;
788 //       }
789
790         // adjust for throttle pitch gain
791         total_adj += ((current_throttle->getFloatValue() - zero_pitch_throttle->getFloatValue())
792                      / (1 - zero_pitch_throttle->getFloatValue()))
793                      * zero_pitch_trim_full_throttle->getFloatValue();
794
795         globals->get_controls()->set_elevator_trim( total_adj );
796     }
797
798     // auto throttle
799     if ( auto_throttle ) {
800         double error;
801         double prop_error, int_error;
802         double prop_adj, int_adj, total_adj;
803
804         error = TargetSpeed - get_speed();
805
806         // accumulate the error under the curve ... this really should
807         // be *= delta t
808         speed_error_accum += error;
809         if ( speed_error_accum > 2000.0 ) {
810             speed_error_accum = 2000.0;
811         }
812         else if ( speed_error_accum < -2000.0 ) {
813             speed_error_accum = -2000.0;
814         }
815
816         // calculate integral error, and adjustment amount
817         int_error = speed_error_accum;
818
819         // printf("error = %.2f  int_error = %.2f\n", error, int_error);
820         int_adj = int_error / 200.0;
821
822         // caclulate proportional error
823         prop_error = error;
824         prop_adj = 0.5 + prop_error / 50.0;
825
826         total_adj = 0.9 * prop_adj + 0.1 * int_adj;
827         if ( total_adj > 1.0 ) {
828             total_adj = 1.0;
829         }
830         else if ( total_adj < 0.0 ) {
831             total_adj = 0.0;
832         }
833
834         globals->get_controls()->set_throttle( FGControls::ALL_ENGINES,
835                                                total_adj );
836     }
837
838 #ifdef THIS_CODE_IS_NOT_USED
839     if (Mode == 2) // Glide slope hold
840         {
841             double RelSlope;
842             double RelElevator;
843
844             // First, calculate Relative slope and normalize it
845             RelSlope = NormalizeDegrees( TargetSlope - get_pitch());
846
847             // Now calculate the elevator offset from current angle
848             if ( abs(RelSlope) > SlopeSmooth )
849                 {
850                     if ( RelSlope < 0 )     //  set RelElevator to max in the correct direction
851                         RelElevator = -MaxElevator;
852                     else
853                         RelElevator = MaxElevator;
854                 }
855
856             else
857                 RelElevator = LinearExtrapolate(RelSlope,-SlopeSmooth,-MaxElevator,SlopeSmooth,MaxElevator);
858
859             // set the elevator
860             fgElevMove(RelElevator);
861
862         }
863 #endif // THIS_CODE_IS_NOT_USED
864
865     // stash this runs control settings
866     //  update_old_control_values();
867     old_aileron = globals->get_controls()->get_aileron();
868     old_elevator = globals->get_controls()->get_elevator();
869     old_elevator_trim = globals->get_controls()->get_elevator_trim();
870     old_rudder = globals->get_controls()->get_rudder();
871
872     // for cross track error
873     old_lat = lat;
874     old_lon = lon;
875         
876     // Ok, we are done
877     SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run( returns )" );
878 }
879
880
881 void FGAutopilot::set_HeadingMode( fgAutoHeadingMode mode ) {
882     heading_mode = mode;
883
884     if ( heading_mode == FG_DG_HEADING_LOCK ) {
885         // set heading hold to current heading (as read from DG)
886         // ... no, leave target heading along ... just use the current
887         // heading bug value
888         //  DGTargetHeading = FGSteam::get_DG_deg();
889     } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
890         // set autopilot to hold a zero turn (as reported by the TC)
891     } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
892         // set heading hold to current heading
893         TargetHeading = heading_node->getDoubleValue();
894     } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
895         if ( globals->get_route()->size() ) {
896             double course, distance;
897
898             old_lat = latitude_node->getDoubleValue();
899             old_lon = longitude_node->getDoubleValue();
900
901             waypoint = globals->get_route()->get_first();
902             waypoint.CourseAndDistance( longitude_node->getDoubleValue(),
903                                         latitude_node->getDoubleValue(),
904                                         altitude_node->getDoubleValue()
905                                         * SG_FEET_TO_METER,
906                                         &course, &distance );
907             TargetHeading = course;
908             TargetDistance = distance;
909             MakeTargetLatLonStr( waypoint.get_target_lat(),
910                                  waypoint.get_target_lon() );
911             MakeTargetWPStr( distance );
912
913             if ( waypoint.get_target_alt() > 0.0 ) {
914                 TargetAltitude = waypoint.get_target_alt();
915                 altitude_mode = FG_ALTITUDE_LOCK;
916                 set_AltitudeEnabled( true );
917                 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
918             }
919
920             SG_LOG( SG_COCKPIT, SG_INFO, " set_HeadingMode: ( "
921                     << get_TargetLatitude()  << " "
922                     << get_TargetLongitude() << " ) "
923                     );
924         } else {
925             // no more way points, default to heading lock.
926             heading_mode = FG_TC_HEADING_LOCK;
927         }
928     }
929
930     MakeTargetHeadingStr( TargetHeading );                      
931     update_old_control_values();
932 }
933
934
935 void FGAutopilot::set_AltitudeMode( fgAutoAltitudeMode mode ) {
936     altitude_mode = mode;
937
938     alt_error_accum = 0.0;
939
940
941     if ( altitude_mode == FG_ALTITUDE_LOCK ) {
942         if ( TargetAltitude < altitude_agl_node->getDoubleValue()
943              * SG_FEET_TO_METER ) {
944         }
945
946         if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
947             MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
948         } else {
949             MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
950         }
951     } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
952         climb_error_accum = 0.0;
953
954     } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
955         TargetAGL = altitude_agl_node->getDoubleValue() * SG_FEET_TO_METER;
956
957         if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
958             MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
959         } else {
960             MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
961         }
962     }
963     
964     update_old_control_values();
965     SG_LOG( SG_COCKPIT, SG_INFO, " set_AltitudeMode():" );
966 }
967
968
969 void FGAutopilot::AltitudeSet( double new_altitude ) {
970     double target_alt = new_altitude;
971
972     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
973         target_alt = new_altitude * SG_FEET_TO_METER;
974     }
975
976     if( target_alt < globals->get_scenery()->get_cur_elev() ) {
977         target_alt = globals->get_scenery()->get_cur_elev();
978     }
979
980     TargetAltitude = target_alt;
981     altitude_mode = FG_ALTITUDE_LOCK;
982
983     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
984         target_alt *= SG_METER_TO_FEET;
985     }
986     // ApAltitudeDialogInput->setValue((float)target_alt);
987     MakeTargetAltitudeStr( target_alt );
988         
989     update_old_control_values();
990 }
991
992
993 void FGAutopilot::AltitudeAdjust( double inc )
994 {
995     double target_alt, target_agl;
996
997     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
998         target_alt = TargetAltitude * SG_METER_TO_FEET;
999         target_agl = TargetAGL * SG_METER_TO_FEET;
1000     } else {
1001         target_alt = TargetAltitude;
1002         target_agl = TargetAGL;
1003     }
1004
1005     if ( fabs((int)(target_alt / inc) * inc - target_alt) < SG_EPSILON ) {
1006         target_alt += inc;
1007     } else {
1008         target_alt = ( int ) ( target_alt / inc ) * inc + inc;
1009     }
1010
1011     if ( fabs((int)(target_agl / inc) * inc - target_agl) < SG_EPSILON ) {
1012         target_agl += inc;
1013     } else {
1014         target_agl = ( int ) ( target_agl / inc ) * inc + inc;
1015     }
1016
1017     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") ) {
1018         target_alt *= SG_FEET_TO_METER;
1019         target_agl *= SG_FEET_TO_METER;
1020     }
1021
1022     TargetAltitude = target_alt;
1023     TargetAGL = target_agl;
1024         
1025     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
1026         target_alt *= SG_METER_TO_FEET;
1027     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
1028         target_agl *= SG_METER_TO_FEET;
1029
1030     if ( altitude_mode == FG_ALTITUDE_LOCK ) {
1031         MakeTargetAltitudeStr( target_alt );
1032     } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
1033         MakeTargetAltitudeStr( target_agl );
1034     }
1035
1036     update_old_control_values();
1037 }
1038
1039
1040 void FGAutopilot::HeadingAdjust( double inc ) {
1041     if ( heading_mode != FG_DG_HEADING_LOCK
1042          && heading_mode != FG_TRUE_HEADING_LOCK )
1043     {
1044         heading_mode = FG_DG_HEADING_LOCK;
1045     }
1046
1047     if ( heading_mode == FG_DG_HEADING_LOCK ) {
1048         double target = ( int ) ( DGTargetHeading / inc ) * inc + inc;
1049         DGTargetHeading = NormalizeDegrees( target );
1050     } else {
1051         double target = ( int ) ( TargetHeading / inc ) * inc + inc;
1052         TargetHeading = NormalizeDegrees( target );
1053     }
1054
1055     update_old_control_values();
1056 }
1057
1058
1059 void FGAutopilot::HeadingSet( double new_heading ) {
1060     if( heading_mode == FG_TRUE_HEADING_LOCK ) {
1061         new_heading = NormalizeDegrees( new_heading );
1062         TargetHeading = new_heading;
1063         MakeTargetHeadingStr( TargetHeading );
1064     } else {
1065         heading_mode = FG_DG_HEADING_LOCK;
1066
1067         new_heading = NormalizeDegrees( new_heading );
1068         DGTargetHeading = new_heading;
1069         // following cast needed ambiguous plib
1070         // ApHeadingDialogInput -> setValue ((float)APData->TargetHeading );
1071         MakeTargetHeadingStr( DGTargetHeading );
1072     }
1073     update_old_control_values();
1074 }
1075
1076 void FGAutopilot::AutoThrottleAdjust( double inc ) {
1077     double target = ( int ) ( TargetSpeed / inc ) * inc + inc;
1078
1079     TargetSpeed = target;
1080 }
1081
1082
1083 void FGAutopilot::set_AutoThrottleEnabled( bool value ) {
1084     auto_throttle = value;
1085
1086     if ( auto_throttle == true ) {
1087         TargetSpeed = fgGetDouble("/velocities/airspeed-kt");
1088         speed_error_accum = 0.0;
1089     }
1090
1091     update_old_control_values();
1092     SG_LOG( SG_COCKPIT, SG_INFO, " fgAPSetAutoThrottle: ("
1093             << auto_throttle << ") " << TargetSpeed );
1094 }
1095
1096
1097
1098 \f
1099 ////////////////////////////////////////////////////////////////////////
1100 // Kludged methods for tying to properties.
1101 //
1102 // These should change eventually; they all used to be static
1103 // functions.
1104 ////////////////////////////////////////////////////////////////////////
1105
1106 /**
1107  * Get the autopilot altitude lock (true=on).
1108  */
1109 bool
1110 FGAutopilot::getAPAltitudeLock () const
1111 {
1112     return (get_AltitudeEnabled() &&
1113             get_AltitudeMode()
1114             == FGAutopilot::FG_ALTITUDE_LOCK);
1115 }
1116
1117
1118 /**
1119  * Set the autopilot altitude lock (true=on).
1120  */
1121 void
1122 FGAutopilot::setAPAltitudeLock (bool lock)
1123 {
1124   if (lock)
1125     set_AltitudeMode(FGAutopilot::FG_ALTITUDE_LOCK);
1126   if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_LOCK)
1127     set_AltitudeEnabled(lock);
1128 }
1129
1130
1131 /**
1132  * Get the autopilot target altitude in feet.
1133  */
1134 double
1135 FGAutopilot::getAPAltitude () const
1136 {
1137   return get_TargetAltitude() * SG_METER_TO_FEET;
1138 }
1139
1140
1141 /**
1142  * Set the autopilot target altitude in feet.
1143  */
1144 void
1145 FGAutopilot::setAPAltitude (double altitude)
1146 {
1147   set_TargetAltitude( altitude * SG_FEET_TO_METER );
1148 }
1149
1150 /**
1151  * Get the autopilot altitude lock (true=on).
1152  */
1153 bool
1154 FGAutopilot::getAPGSLock () const
1155 {
1156     return (get_AltitudeEnabled() &&
1157             (get_AltitudeMode()
1158              == FGAutopilot::FG_ALTITUDE_GS1));
1159 }
1160
1161
1162 /**
1163  * Set the autopilot altitude lock (true=on).
1164  */
1165 void
1166 FGAutopilot::setAPGSLock (bool lock)
1167 {
1168   if (lock)
1169     set_AltitudeMode(FGAutopilot::FG_ALTITUDE_GS1);
1170   if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_GS1)
1171     set_AltitudeEnabled(lock);
1172 }
1173
1174
1175 /**
1176  * Get the autopilot terrain lock (true=on).
1177  */
1178 bool
1179 FGAutopilot::getAPTerrainLock () const
1180 {
1181     return (get_AltitudeEnabled() &&
1182             (get_AltitudeMode()
1183              == FGAutopilot::FG_ALTITUDE_TERRAIN));
1184 }
1185
1186
1187 /**
1188  * Set the autopilot terrain lock (true=on).
1189  */
1190 void
1191 FGAutopilot::setAPTerrainLock (bool lock)
1192 {
1193   if (lock) {
1194     set_AltitudeMode(FGAutopilot::FG_ALTITUDE_TERRAIN);
1195     set_TargetAGL(fgGetFloat("/position/altitude-agl-ft") *
1196                   SG_FEET_TO_METER);
1197   }
1198   if (get_AltitudeMode() == FGAutopilot::FG_ALTITUDE_TERRAIN)
1199     set_AltitudeEnabled(lock);
1200 }
1201
1202
1203 /**
1204  * Get the autopilot target altitude in feet.
1205  */
1206 double
1207 FGAutopilot::getAPClimb () const
1208 {
1209   return get_TargetClimbRate() * SG_METER_TO_FEET;
1210 }
1211
1212
1213 /**
1214  * Set the autopilot target altitude in feet.
1215  */
1216 void
1217 FGAutopilot::setAPClimb (double rate)
1218 {
1219     set_TargetClimbRate( rate * SG_FEET_TO_METER );
1220 }
1221
1222
1223 /**
1224  * Get the autopilot heading lock (true=on).
1225  */
1226 bool
1227 FGAutopilot::getAPHeadingLock () const
1228 {
1229     return
1230       (get_HeadingEnabled() &&
1231        get_HeadingMode() == DEFAULT_AP_HEADING_LOCK);
1232 }
1233
1234
1235 /**
1236  * Set the autopilot heading lock (true=on).
1237  */
1238 void
1239 FGAutopilot::setAPHeadingLock (bool lock)
1240 {
1241   if (lock)
1242     set_HeadingMode(DEFAULT_AP_HEADING_LOCK);
1243   if (get_HeadingMode() == DEFAULT_AP_HEADING_LOCK)
1244     set_HeadingEnabled(lock);
1245 }
1246
1247
1248 /**
1249  * Get the autopilot heading bug in degrees.
1250  */
1251 double
1252 FGAutopilot::getAPHeadingBug () const
1253 {
1254   return get_DGTargetHeading();
1255 }
1256
1257
1258 /**
1259  * Set the autopilot heading bug in degrees.
1260  */
1261 void
1262 FGAutopilot::setAPHeadingBug (double heading)
1263 {
1264   set_DGTargetHeading( heading );
1265 }
1266
1267
1268 /**
1269  * Get the autopilot wing leveler lock (true=on).
1270  */
1271 bool
1272 FGAutopilot::getAPWingLeveler () const
1273 {
1274     return
1275       (get_HeadingEnabled() &&
1276        get_HeadingMode() == FGAutopilot::FG_TC_HEADING_LOCK);
1277 }
1278
1279
1280 /**
1281  * Set the autopilot wing leveler lock (true=on).
1282  */
1283 void
1284 FGAutopilot::setAPWingLeveler (bool lock)
1285 {
1286     if (lock)
1287         set_HeadingMode(FGAutopilot::FG_TC_HEADING_LOCK);
1288     if (get_HeadingMode() == FGAutopilot::FG_TC_HEADING_LOCK)
1289       set_HeadingEnabled(lock);
1290 }
1291
1292 /**
1293  * Return true if the autopilot is locked to NAV1.
1294  */
1295 bool
1296 FGAutopilot::getAPNAV1Lock () const
1297 {
1298   return
1299     (get_HeadingEnabled() &&
1300      get_HeadingMode() == FGAutopilot::FG_HEADING_NAV1);
1301 }
1302
1303
1304 /**
1305  * Set the autopilot NAV1 lock.
1306  */
1307 void
1308 FGAutopilot::setAPNAV1Lock (bool lock)
1309 {
1310   if (lock)
1311     set_HeadingMode(FGAutopilot::FG_HEADING_NAV1);
1312   if (get_HeadingMode() == FGAutopilot::FG_HEADING_NAV1)
1313     set_HeadingEnabled(lock);
1314 }
1315
1316 /**
1317  * Get the autopilot autothrottle lock.
1318  */
1319 bool
1320 FGAutopilot::getAPAutoThrottleLock () const
1321 {
1322   return get_AutoThrottleEnabled();
1323 }
1324
1325
1326 /**
1327  * Set the autothrottle lock.
1328  */
1329 void
1330 FGAutopilot::setAPAutoThrottleLock (bool lock)
1331 {
1332   set_AutoThrottleEnabled(lock);
1333 }
1334
1335
1336 // kludge
1337 double
1338 FGAutopilot::getAPRudderControl () const
1339 {
1340     if (getAPHeadingLock())
1341         return get_TargetHeading();
1342     else
1343         return globals->get_controls()->get_rudder();
1344 }
1345
1346 // kludge
1347 void
1348 FGAutopilot::setAPRudderControl (double value)
1349 {
1350     if (getAPHeadingLock()) {
1351         SG_LOG(SG_GENERAL, SG_DEBUG, "setAPRudderControl " << value );
1352         value -= get_TargetHeading();
1353         HeadingAdjust(value < 0.0 ? -1.0 : 1.0);
1354     } else {
1355         globals->get_controls()->set_rudder(value);
1356     }
1357 }
1358
1359 // kludge
1360 double
1361 FGAutopilot::getAPElevatorControl () const
1362 {
1363   if (getAPAltitudeLock())
1364       return get_TargetAltitude();
1365   else
1366     return globals->get_controls()->get_elevator();
1367 }
1368
1369 // kludge
1370 void
1371 FGAutopilot::setAPElevatorControl (double value)
1372 {
1373     if (value != 0 && getAPAltitudeLock()) {
1374         SG_LOG(SG_GENERAL, SG_DEBUG, "setAPElevatorControl " << value );
1375         value -= get_TargetAltitude();
1376         AltitudeAdjust(value < 0.0 ? 100.0 : -100.0);
1377     } else {
1378         globals->get_controls()->set_elevator(value);
1379     }
1380 }
1381
1382 // kludge
1383 double
1384 FGAutopilot::getAPThrottleControl () const
1385 {
1386   if (getAPAutoThrottleLock())
1387     return 0.0;                 // always resets
1388   else
1389     return globals->get_controls()->get_throttle(0);
1390 }
1391
1392 // kludge
1393 void
1394 FGAutopilot::setAPThrottleControl (double value)
1395 {
1396   if (getAPAutoThrottleLock())
1397     AutoThrottleAdjust(value < 0.0 ? -0.01 : 0.01);
1398   else
1399     globals->get_controls()->set_throttle(FGControls::ALL_ENGINES, value);
1400 }
1401
1402 // end of newauto.cxx
1403