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