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