]> git.mxchange.org Git - flightgear.git/blob - src/Autopilot/newauto.cxx
This is the change where autopilot bindings are moved from fg_props.cxx to
[flightgear.git] / src / Autopilot / newauto.cxx
1 // newauto.cxx -- autopilot defines and prototypes (very alpha)
2 // 
3 // Started April 1998  Copyright (C) 1998
4 //
5 // Contributions by Jeff Goeke-Smith <jgoeke@voyager.net>
6 //                  Norman Vine <nhv@cape.com>
7 //                  Curtis Olson <curt@flightgear.org>
8 //
9 // This program is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU General Public License as
11 // published by the Free Software Foundation; either version 2 of the
12 // License, or (at your option) any later version.
13 //
14 // This program is distributed in the hope that it will be useful, but
15 // WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 // General Public License for more details.
18 //
19 // You should have received a copy of the GNU General Public License
20 // along with this program; if not, write to the Free Software
21 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 //
23 // $Id$
24
25
26 #ifdef HAVE_CONFIG_H
27 #  include <config.h>
28 #endif
29
30 #include <stdio.h>              // sprintf()
31
32 #include <simgear/constants.h>
33 #include <simgear/sg_inlines.h>
34 #include <simgear/debug/logstream.hxx>
35 #include <simgear/math/sg_geodesy.hxx>
36 #include <simgear/math/sg_random.h>
37
38 #include <Cockpit/steam.hxx>
39 #include <Cockpit/radiostack.hxx>
40 #include <Controls/controls.hxx>
41 #include <FDM/flight.hxx>
42 #include <Main/globals.hxx>
43 #include <Scenery/scenery.hxx>
44
45 #include "newauto.hxx"
46
47
48 FGAutopilot *current_autopilot;
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_speed( void ) {
102     return( cur_fdm_state->get_V_equiv_kts() );
103 }
104
105 static inline double get_ground_speed() {
106     // starts in ft/s so we convert to kts
107     static const SGPropertyNode * speedup_node = fgGetNode("/sim/speed-up");
108
109     double ft_s = cur_fdm_state->get_V_ground_speed() 
110         * speedup_node->getIntValue();
111     double kts = ft_s * SG_FEET_TO_METER * 3600 * SG_METER_TO_NM;
112
113     return kts;
114 }
115
116
117 void FGAutopilot::MakeTargetWPStr( double distance ) {
118     static time_t last_time = 0;
119     time_t current_time = time(NULL);
120     if ( last_time == current_time ) {
121         return;
122     }
123
124     last_time = current_time;
125
126     double accum = 0.0;
127
128     int size = globals->get_route()->size();
129
130     // start by wiping the strings
131     TargetWP1Str[0] = 0;
132     TargetWP2Str[0] = 0;
133     TargetWP3Str[0] = 0;
134
135     // current route
136     if ( size > 0 ) {
137         SGWayPoint wp1 = globals->get_route()->get_waypoint( 0 );
138         accum += distance;
139         double eta = accum * SG_METER_TO_NM / get_ground_speed();
140         if ( eta >= 100.0 ) { eta = 99.999; }
141         int major, minor;
142         if ( eta < (1.0/6.0) ) {
143             // within 10 minutes, bump up to min/secs
144             eta *= 60.0;
145         }
146         major = (int)eta;
147         minor = (int)((eta - (int)eta) * 60.0);
148         sprintf( TargetWP1Str, "%s %.2f NM  ETA %d:%02d",
149                  wp1.get_id().c_str(),
150                  accum*SG_METER_TO_NM, major, minor );
151         // cout << "distance = " << distance*SG_METER_TO_NM
152         //      << "  gndsp = " << get_ground_speed() 
153         //      << "  time = " << eta
154         //      << "  major = " << major
155         //      << "  minor = " << minor
156         //      << endl;
157     }
158
159     // next route
160     if ( size > 1 ) {
161         SGWayPoint wp2 = globals->get_route()->get_waypoint( 1 );
162         accum += wp2.get_distance();
163         
164         double eta = accum * SG_METER_TO_NM / get_ground_speed();
165         if ( eta >= 100.0 ) { eta = 99.999; }
166         int major, minor;
167         if ( eta < (1.0/6.0) ) {
168             // within 10 minutes, bump up to min/secs
169             eta *= 60.0;
170         }
171         major = (int)eta;
172         minor = (int)((eta - (int)eta) * 60.0);
173         sprintf( TargetWP2Str, "%s %.2f NM  ETA %d:%02d",
174                  wp2.get_id().c_str(),
175                  accum*SG_METER_TO_NM, major, minor );
176     }
177
178     // next route
179     if ( size > 2 ) {
180         for ( int i = 2; i < size; ++i ) {
181             accum += globals->get_route()->get_waypoint( i ).get_distance();
182         }
183         
184         SGWayPoint wpn = globals->get_route()->get_waypoint( size - 1 );
185
186         double eta = accum * SG_METER_TO_NM / get_ground_speed();
187         if ( eta >= 100.0 ) { eta = 99.999; }
188         int major, minor;
189         if ( eta < (1.0/6.0) ) {
190             // within 10 minutes, bump up to min/secs
191             eta *= 60.0;
192         }
193         major = (int)eta;
194         minor = (int)((eta - (int)eta) * 60.0);
195         sprintf( TargetWP3Str, "%s %.2f NM  ETA %d:%02d",
196                  wpn.get_id().c_str(),
197                  accum*SG_METER_TO_NM, major, minor );
198     }
199 }
200
201
202 void FGAutopilot::update_old_control_values() {
203     old_aileron = globals->get_controls()->get_aileron();
204     old_elevator = globals->get_controls()->get_elevator();
205     old_elevator_trim = globals->get_controls()->get_elevator_trim();
206     old_rudder = globals->get_controls()->get_rudder();
207 }
208
209
210 // Initialize autopilot subsystem
211 void FGAutopilot::init() {
212     SG_LOG( SG_AUTOPILOT, SG_INFO, "Init AutoPilot Subsystem" );
213
214     // Autopilot control property static get/set bindings
215     fgTie("/autopilot/locks/altitude", getAPAltitudeLock, setAPAltitudeLock);
216     fgSetArchivable("/autopilot/locks/altitude");
217     fgTie("/autopilot/settings/altitude-ft", getAPAltitude, setAPAltitude);
218     fgSetArchivable("/autopilot/settings/altitude-ft");
219     fgTie("/autopilot/locks/glide-slope", getAPGSLock, setAPGSLock);
220     fgSetDouble("/autopilot/settings/altitude-ft", 3000.0f);
221     fgSetArchivable("/autopilot/locks/glide-slope");
222     fgTie("/autopilot/locks/terrain", getAPTerrainLock, setAPTerrainLock);
223     fgSetArchivable("/autopilot/locks/terrain");
224     fgTie("/autopilot/settings/climb-rate-fpm", getAPClimb, setAPClimb, false);
225     fgSetArchivable("/autopilot/settings/climb-rate-fpm");
226     fgTie("/autopilot/locks/heading", getAPHeadingLock, setAPHeadingLock);
227     fgSetArchivable("/autopilot/locks/heading");
228     fgTie("/autopilot/settings/heading-bug-deg",
229         getAPHeadingBug, setAPHeadingBug);
230     fgSetArchivable("/autopilot/settings/heading-bug-deg");
231     fgSetDouble("/autopilot/settings/heading-bug-deg", 0.0f);
232     fgTie("/autopilot/locks/wing-leveler", getAPWingLeveler, setAPWingLeveler);
233     fgSetArchivable("/autopilot/locks/wing-leveler");
234     fgTie("/autopilot/locks/nav[0]", getAPNAV1Lock, setAPNAV1Lock);
235     fgSetArchivable("/autopilot/locks/nav[0]");
236     fgTie("/autopilot/locks/auto-throttle",
237         getAPAutoThrottleLock, setAPAutoThrottleLock);
238     fgSetArchivable("/autopilot/locks/auto-throttle");
239     fgTie("/autopilot/control-overrides/rudder",
240         getAPRudderControl, setAPRudderControl);
241     fgSetArchivable("/autopilot/control-overrides/rudder");
242     fgTie("/autopilot/control-overrides/elevator",
243         getAPElevatorControl, setAPElevatorControl);
244     fgSetArchivable("/autopilot/control-overrides/elevator");
245     fgTie("/autopilot/control-overrides/throttle",
246         getAPThrottleControl, setAPThrottleControl);
247     fgSetArchivable("/autopilot/control-overrides/throttle");
248
249
250     // bind data input property nodes...
251     latitude_node = fgGetNode("/position/latitude-deg", true);
252     longitude_node = fgGetNode("/position/longitude-deg", true);
253     altitude_node = fgGetNode("/position/altitude-ft", true);
254     altitude_agl_node = fgGetNode("/position/altitude-agl-ft", true);
255     vertical_speed_node = fgGetNode("/velocities/vertical-speed-fps", true);
256     heading_node = fgGetNode("/orientation/heading-deg", true);
257     roll_node = fgGetNode("/orientation/roll-deg", true);
258     pitch_node = fgGetNode("/orientation/pitch-deg", true);
259
260     // bind config property nodes...
261     TargetClimbRate
262         = fgGetNode("/autopilot/config/target-climb-rate-fpm", true);
263     TargetDescentRate
264         = fgGetNode("/autopilot/config/target-descent-rate-fpm", true);
265     min_climb = fgGetNode("/autopilot/config/min-climb-speed-kt", true);
266     best_climb = fgGetNode("/autopilot/config/best-climb-speed-kt", true);
267     elevator_adj_factor
268         = fgGetNode("/autopilot/config/elevator-adj-factor", true);
269     integral_contrib
270         = fgGetNode("/autopilot/config/integral-contribution", true);
271     zero_pitch_throttle
272         = fgGetNode("/autopilot/config/zero-pitch-throttle", true);
273     zero_pitch_trim_full_throttle
274         = fgGetNode("/autopilot/config/zero-pitch-trim-full-throttle", true);
275     current_throttle = fgGetNode("/controls/throttle");
276
277     // initialize config properties with defaults (in case config isn't there)
278     if ( TargetClimbRate->getFloatValue() < 1 )
279         fgSetFloat( "/autopilot/config/target-climb-rate-fpm", 500);
280     if ( TargetDescentRate->getFloatValue() < 1 )
281         fgSetFloat( "/autopilot/config/target-descent-rate-fpm", 1000 );
282     if ( min_climb->getFloatValue() < 1)
283         fgSetFloat( "/autopilot/config/min-climb-speed-kt", 70 );
284     if (best_climb->getFloatValue() < 1)
285         fgSetFloat( "/autopilot/config/best-climb-speed-kt", 120 );
286     if (elevator_adj_factor->getFloatValue() < 1)
287         fgSetFloat( "/autopilot/config/elevator-adj-factor", 5000 );
288     if ( integral_contrib->getFloatValue() < 0.0000001 )
289         fgSetFloat( "/autopilot/config/integral-contribution", 0.01 );
290     if ( zero_pitch_throttle->getFloatValue() < 0.0000001 )
291         fgSetFloat( "/autopilot/config/zero-pitch-throttle", 0.60 );
292     if ( zero_pitch_trim_full_throttle->getFloatValue() < 0.0000001 )
293         fgSetFloat( "/autopilot/config/zero-pitch-trim-full-throttle", 0.15 );
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
301     DGTargetHeading = fgGetDouble("/autopilot/settings/heading-bug-deg");
302     TargetHeading = fgGetDouble("/autopilot/settings/heading-bug-deg");
303     TargetAltitude = fgGetDouble("/autopilot/settings/altitude-ft") * SG_FEET_TO_METER;
304
305     // Initialize target location to startup location
306     old_lat = latitude_node->getDoubleValue();
307     old_lon = longitude_node->getDoubleValue();
308     // set_WayPoint( old_lon, old_lat, 0.0, "default" );
309
310     MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
311         
312     alt_error_accum = 0.0;
313     climb_error_accum = 0.0;
314
315     MakeTargetAltitudeStr( TargetAltitude );
316     MakeTargetHeadingStr( TargetHeading );
317         
318     // These eventually need to be read from current_aircaft somehow.
319
320     // the maximum roll, in Deg
321     MaxRoll = 20;
322
323     // the deg from heading to start rolling out at, in Deg
324     RollOut = 20;
325
326     // how far can I move the aleron from center.
327     MaxAileron = .2;
328
329     // Smoothing distance for alerion control
330     RollOutSmooth = 10;
331
332     // Hardwired for now should be in options
333     // 25% max control variablilty  0.5 / 2.0
334     disengage_threshold = 1.0;
335
336 #if !defined( USING_SLIDER_CLASS )
337     MaxRollAdjust = 2 * MaxRoll;
338     RollOutAdjust = 2 * RollOut;
339     MaxAileronAdjust = 2 * MaxAileron;
340     RollOutSmoothAdjust = 2 * RollOutSmooth;
341 #endif  // !defined( USING_SLIDER_CLASS )
342
343     update_old_control_values();
344         
345 };
346
347
348 // Reset the autopilot system
349 void FGAutopilot::reset() {
350
351     heading_hold = false ;      // turn the heading hold off
352     altitude_hold = false ;     // turn the altitude hold off
353     auto_throttle = false ;     // turn the auto throttle off
354     heading_mode = DEFAULT_AP_HEADING_LOCK;
355
356     // TargetHeading = 0.0;     // default direction, due north
357     MakeTargetHeadingStr( TargetHeading );                      
358         
359     // TargetAltitude = 3000;   // default altitude in meters
360     MakeTargetAltitudeStr( TargetAltitude );
361         
362     alt_error_accum = 0.0;
363     climb_error_accum = 0.0;
364         
365     update_old_control_values();
366
367     sprintf( NewTgtAirportId, "%s", fgGetString("/sim/startup/airport-id").c_str() );
368         
369     MakeTargetLatLonStr( get_TargetLatitude(), get_TargetLongitude() );
370 }
371
372
373 static double NormalizeDegrees( double Input ) {
374     // normalize the input to the range (-180,180]
375     // Input should not be greater than -360 to 360.
376     // Current rules send the output to an undefined state.
377     while ( Input > 180.0 ) { Input -= 360.0; }
378     while ( Input <= -180.0 ) { Input += 360.0; }
379
380     return Input;
381 };
382
383 static double LinearExtrapolate( double x, double x1, double y1, double x2, double y2 ) {
384     // This procedure extrapolates the y value for the x posistion on a line defined by x1,y1; x2,y2
385     //assert(x1 != x2); // Divide by zero error.  Cold abort for now
386
387         // Could be
388         // static double y = 0.0;
389         // double dx = x2 -x1;
390         // if( (dx < -SG_EPSILON ) || ( dx > SG_EPSILON ) )
391         // {
392
393     double m, b, y;          // the constants to find in y=mx+b
394     // double m, b;
395
396     m = ( y2 - y1 ) / ( x2 - x1 );   // calculate the m
397
398     b = y1 - m * x1;       // calculate the b
399
400     y = m * x + b;       // the final calculation
401
402     // }
403
404     return ( y );
405
406 };
407
408
409 int FGAutopilot::run() {
410     // Remove the following lines when the calling funcitons start
411     // passing in the data pointer
412
413     // get control settings 
414         
415     double lat = latitude_node->getDoubleValue();
416     double lon = longitude_node->getDoubleValue();
417     double alt = altitude_node->getDoubleValue() * SG_FEET_TO_METER;
418
419     SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run()  lat = " << lat <<
420             "  lon = " << lon << "  alt = " << alt );
421         
422 #ifdef FG_FORCE_AUTO_DISENGAGE
423     // see if somebody else has changed them
424     if( fabs(aileron - old_aileron) > disengage_threshold ||
425         fabs(elevator - old_elevator) > disengage_threshold ||
426         fabs(elevator_trim - old_elevator_trim) > 
427         disengage_threshold ||          
428         fabs(rudder - old_rudder) > disengage_threshold )
429     {
430         // if controls changed externally turn autopilot off
431         waypoint_hold = false ;   // turn the target hold off
432         heading_hold = false ;    // turn the heading hold off
433         altitude_hold = false ;   // turn the altitude hold off
434         terrain_follow = false;   // turn the terrain_follow hold off
435         // auto_throttle = false; // turn the auto_throttle off
436
437         // stash this runs control settings
438         old_aileron = aileron;
439         old_elevator = elevator;
440         old_elevator_trim = elevator_trim;
441         old_rudder = rudder;
442         
443         return 0;
444     }
445 #endif
446         
447     // heading hold
448     if ( heading_hold == true ) {
449         if ( heading_mode == FG_DG_HEADING_LOCK ) {
450             // cout << "DG heading = " << FGSteam::get_DG_deg()
451             //      << " DG error = " << FGSteam::get_DG_err() << endl;
452
453             TargetHeading = DGTargetHeading + FGSteam::get_DG_err();
454             while ( TargetHeading <   0.0 ) { TargetHeading += 360.0; }
455             while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
456             MakeTargetHeadingStr( TargetHeading );
457         } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
458             // we don't set a specific target heading in
459             // TC_HEADING_LOCK mode, we instead try to keep the turn
460             // coordinator zero'd
461         } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
462             // leave "true" target heading as is
463             while ( TargetHeading <   0.0 ) { TargetHeading += 360.0; }
464             while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
465             MakeTargetHeadingStr( TargetHeading );
466         } else if ( heading_mode == FG_HEADING_NAV1 ) {
467             // track the NAV1 heading needle deflection
468
469             // determine our current radial position relative to the
470             // navaid in "true" heading.
471             double cur_radial = current_radiostack->get_nav1_heading();
472             if ( current_radiostack->get_nav1_loc() ) {
473                 // ILS localizers radials are already "true" in our
474                 // database
475             } else {
476                 cur_radial += current_radiostack->get_nav1_magvar();
477             }
478             if ( current_radiostack->get_nav1_from_flag() ) {
479                 cur_radial += 180.0;
480                 while ( cur_radial >= 360.0 ) { cur_radial -= 360.0; }
481             }
482
483             // determine the target radial in "true" heading
484             double tgt_radial = current_radiostack->get_nav1_radial();
485             if ( current_radiostack->get_nav1_loc() ) {
486                 // ILS localizers radials are already "true" in our
487                 // database
488             } else {
489                 // VOR radials need to have that vor's offset added in
490                 tgt_radial += current_radiostack->get_nav1_magvar();
491             }
492
493             // determine the heading adjustment needed.
494             double adjustment = 
495                 current_radiostack->get_nav1_heading_needle_deflection()
496                 * (current_radiostack->get_nav1_loc_dist() * SG_METER_TO_NM);
497             SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
498
499             // determine the target heading to fly to intercept the
500             // tgt_radial
501             TargetHeading = tgt_radial + adjustment; 
502             while ( TargetHeading <   0.0 ) { TargetHeading += 360.0; }
503             while ( TargetHeading > 360.0 ) { TargetHeading -= 360.0; }
504
505             MakeTargetHeadingStr( TargetHeading );
506             // cout << "target course (true) = " << TargetHeading << endl;
507         } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
508             // update target heading to waypoint
509
510             double wp_course, wp_distance;
511
512 #ifdef DO_fgAP_CORRECTED_COURSE
513             // compute course made good
514             // this needs lots of special casing before use
515             double course, reverse, distance, corrected_course;
516             // need to test for iter
517             geo_inverse_wgs_84( 0, //fgAPget_altitude(),
518                                 old_lat,
519                                 old_lon,
520                                 lat,
521                                 lon,
522                                 &course,
523                                 &reverse,
524                                 &distance );
525 #endif // DO_fgAP_CORRECTED_COURSE
526
527             // compute course to way_point
528             // need to test for iter
529             SGWayPoint wp = globals->get_route()->get_first();
530             wp.CourseAndDistance( lon, lat, alt, 
531                                   &wp_course, &wp_distance );
532
533 #ifdef DO_fgAP_CORRECTED_COURSE
534             corrected_course = course - wp_course;
535             if( fabs(corrected_course) > 0.1 )
536                 printf("fgAP: course %f  wp_course %f  %f  %f\n",
537                        course, wp_course, fabs(corrected_course),
538                        distance );
539 #endif // DO_fgAP_CORRECTED_COURSE
540                 
541             if ( wp_distance > 100 ) {
542                 // corrected_course = course - wp_course;
543                 TargetHeading = NormalizeDegrees(wp_course);
544             } else {
545                 cout << "Reached waypoint within " << wp_distance << "meters"
546                      << endl;
547
548                 // pop off this waypoint from the list
549                 if ( globals->get_route()->size() ) {
550                     globals->get_route()->delete_first();
551                 }
552
553                 // see if there are more waypoints on the list
554                 if ( globals->get_route()->size() ) {
555                     // more waypoints
556                     set_HeadingMode( FG_HEADING_WAYPOINT );
557                 } else {
558                     // end of the line
559                     heading_mode = FG_TRUE_HEADING_LOCK;
560                     // use current heading
561                     TargetHeading = heading_node->getDoubleValue();
562                 }
563             }
564             MakeTargetHeadingStr( TargetHeading );
565             // Force this just in case
566             TargetDistance = wp_distance;
567             MakeTargetWPStr( wp_distance );
568         }
569
570         if ( heading_mode == FG_TC_HEADING_LOCK ) {
571             // drive the turn coordinator to zero
572             double turn = FGSteam::get_TC_std();
573             // cout << "turn rate = " << turn << endl;
574             double AileronSet = -turn / 2.0;
575             SG_CLAMP_RANGE( AileronSet, -1.0, 1.0 );
576             globals->get_controls()->set_aileron( AileronSet );
577             globals->get_controls()->set_rudder( AileronSet / 4.0 );
578         } else {
579             // steer towards the target heading
580
581             double RelHeading;
582             double TargetRoll;
583             double RelRoll;
584             double AileronSet;
585
586             RelHeading
587                 = NormalizeDegrees( TargetHeading
588                                     - heading_node->getDoubleValue() );
589             // figure out how far off we are from desired heading
590
591             // Now it is time to deterime how far we should be rolled.
592             SG_LOG( SG_AUTOPILOT, SG_DEBUG, "RelHeading: " << RelHeading );
593
594
595             // Check if we are further from heading than the roll out point
596             if ( fabs( RelHeading ) > RollOut ) {
597                 // set Target Roll to Max in desired direction
598                 if ( RelHeading < 0 ) {
599                     TargetRoll = 0 - MaxRoll;
600                 } else {
601                     TargetRoll = MaxRoll;
602                 }
603             } else {
604                 // We have to calculate the Target roll
605
606                 // This calculation engine thinks that the Target roll
607                 // should be a line from (RollOut,MaxRoll) to (-RollOut,
608                 // -MaxRoll) I hope this works well.  If I get ambitious
609                 // some day this might become a fancier curve or
610                 // something.
611
612                 TargetRoll = LinearExtrapolate( RelHeading, -RollOut,
613                                                 -MaxRoll, RollOut,
614                                                 MaxRoll );
615             }
616
617             // Target Roll has now been Found.
618
619             // Compare Target roll to Current Roll, Generate Rel Roll
620
621             SG_LOG( SG_COCKPIT, SG_BULK, "TargetRoll: " << TargetRoll );
622
623             RelRoll = NormalizeDegrees( TargetRoll 
624                                         - roll_node->getDoubleValue() );
625
626             // Check if we are further from heading than the roll out
627             // smooth point
628             if ( fabs( RelRoll ) > RollOutSmooth ) {
629                 // set Target Roll to Max in desired direction
630                 if ( RelRoll < 0 ) {
631                 AileronSet = 0 - MaxAileron;
632                 } else {
633                     AileronSet = MaxAileron;
634                 }
635             } else {
636                 AileronSet = LinearExtrapolate( RelRoll, -RollOutSmooth,
637                                                 -MaxAileron,
638                                                 RollOutSmooth,
639                                                 MaxAileron );
640             }
641
642             globals->get_controls()->set_aileron( AileronSet );
643             globals->get_controls()->set_rudder( AileronSet / 4.0 );
644             // controls.set_rudder( 0.0 );
645         }
646     }
647
648     // altitude hold
649     if ( altitude_hold ) {
650         double climb_rate;
651         double speed, max_climb, error;
652         double prop_error, int_error;
653         double prop_adj, int_adj, total_adj;
654
655         if ( altitude_mode == FG_ALTITUDE_LOCK ) {
656             climb_rate =
657                 ( TargetAltitude - FGSteam::get_ALT_ft() * SG_FEET_TO_METER ) * 8.0;
658         } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
659             double x = current_radiostack->get_nav1_gs_dist();
660             double y = (altitude_node->getDoubleValue()
661                         - current_radiostack->get_nav1_elev()) * SG_FEET_TO_METER;
662             double current_angle = atan2( y, x ) * SGD_RADIANS_TO_DEGREES;
663             // cout << "current angle = " << current_angle << endl;
664
665             double target_angle = current_radiostack->get_nav1_target_gs();
666             // cout << "target angle = " << target_angle << endl;
667
668             double gs_diff = target_angle - current_angle;
669             // cout << "difference from desired = " << gs_diff << endl;
670
671             // convert desired vertical path angle into a climb rate
672             double des_angle = current_angle - 10 * gs_diff;
673             // cout << "desired angle = " << des_angle << endl;
674
675             // convert to meter/min
676             // cout << "raw ground speed = " << cur_fdm_state->get_V_ground_speed() << endl;
677             double horiz_vel = cur_fdm_state->get_V_ground_speed()
678                 * SG_FEET_TO_METER * 60.0;
679             // cout << "Horizontal vel = " << horiz_vel << endl;
680             climb_rate = -sin( des_angle * SGD_DEGREES_TO_RADIANS ) * horiz_vel;
681             // cout << "climb_rate = " << climb_rate << endl;
682             /* climb_error_accum += gs_diff * 2.0; */
683             /* climb_rate = gs_diff * 200.0 + climb_error_accum; */
684         } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
685             // brain dead ground hugging with no look ahead
686             climb_rate =
687                 ( TargetAGL - altitude_agl_node->getDoubleValue()
688                   * SG_FEET_TO_METER ) * 16.0;
689             // cout << "target agl = " << TargetAGL 
690             //      << "  current agl = " << fgAPget_agl() 
691             //      << "  target climb rate = " << climb_rate 
692             //      << endl;
693         } else {
694             // just try to zero out rate of climb ...
695             climb_rate = 0.0;
696         }
697
698         speed = get_speed();
699
700         if ( speed < min_climb->getFloatValue() ) {
701             max_climb = 0.0;
702         } else if ( speed < best_climb->getFloatValue() ) {
703             max_climb = ((best_climb->getFloatValue()
704                           - min_climb->getFloatValue())
705                          - (best_climb->getFloatValue() - speed)) 
706                 * fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER) 
707                 / (best_climb->getFloatValue() - min_climb->getFloatValue());
708         } else {                        
709             max_climb = ( speed - best_climb->getFloatValue() ) * 10.0
710                 + fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
711         }
712
713         // this first one could be optional if we wanted to allow
714         // better climb performance assuming we have the airspeed to
715         // support it.
716         if ( climb_rate >
717              fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER) ) {
718             climb_rate
719                 = fabs(TargetClimbRate->getFloatValue() * SG_FEET_TO_METER);
720         }
721
722         if ( climb_rate > max_climb ) {
723             climb_rate = max_climb;
724         }
725
726         if ( climb_rate <
727              -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER) ) {
728             climb_rate
729                 = -fabs(TargetDescentRate->getFloatValue() * SG_FEET_TO_METER);
730         }
731
732         // cout << "Target climb rate = " << TargetClimbRate->getFloatValue() << endl;
733         // cout << "given our speed, modified desired climb rate = "
734         //      << climb_rate * SG_METER_TO_FEET 
735         //      << " fpm" << endl;
736         // cout << "Current climb rate = "
737         //      << vertical_speed_node->getDoubleValue() * 60 << " fpm" << endl;
738
739         error = vertical_speed_node->getDoubleValue() * 60
740             - climb_rate * SG_METER_TO_FEET;
741
742         // accumulate the error under the curve ... this really should
743         // be *= delta t
744         alt_error_accum += error;
745
746         // calculate integral error, and adjustment amount
747         int_error = alt_error_accum;
748         // printf("error = %.2f  int_error = %.2f\n", error, int_error);
749         int_adj = int_error / elevator_adj_factor->getFloatValue();
750
751         // caclulate proportional error
752         prop_error = error;
753         prop_adj = prop_error / elevator_adj_factor->getDoubleValue();
754
755         // cout << "Error=" << error << endl;
756         // cout << "integral_error=" << int_error << endl;
757         // cout << "integral_contrib=" << integral_contrib->getFloatValue() << endl;
758         // cout << "Proportional Adj=" << prop_adj << endl;
759         // cout << "Integral Adj" << int_adj << endl;
760         total_adj = ((double) 1.0 - (double) integral_contrib->getFloatValue()) * prop_adj
761             + (double) integral_contrib->getFloatValue() * int_adj;
762
763         // stop on autopilot trim at 30% +/-
764 //      if ( total_adj > 0.3 ) {
765 //           total_adj = 0.3;
766 //       } else if ( total_adj < -0.3 ) {
767 //           total_adj = -0.3;
768 //       }
769
770         // adjust for throttle pitch gain
771         total_adj += ((current_throttle->getFloatValue() - zero_pitch_throttle->getFloatValue())
772                      / (1 - zero_pitch_throttle->getFloatValue()))
773                      * zero_pitch_trim_full_throttle->getFloatValue();
774
775         // cout << "Total Adj" << total_adj << endl;
776
777         globals->get_controls()->set_elevator_trim( total_adj );
778     }
779
780     // auto throttle
781     if ( auto_throttle ) {
782         double error;
783         double prop_error, int_error;
784         double prop_adj, int_adj, total_adj;
785
786         error = TargetSpeed - get_speed();
787
788         // accumulate the error under the curve ... this really should
789         // be *= delta t
790         speed_error_accum += error;
791         if ( speed_error_accum > 2000.0 ) {
792             speed_error_accum = 2000.0;
793         }
794         else if ( speed_error_accum < -2000.0 ) {
795             speed_error_accum = -2000.0;
796         }
797
798         // calculate integral error, and adjustment amount
799         int_error = speed_error_accum;
800
801         // printf("error = %.2f  int_error = %.2f\n", error, int_error);
802         int_adj = int_error / 200.0;
803
804         // caclulate proportional error
805         prop_error = error;
806         prop_adj = 0.5 + prop_error / 50.0;
807
808         total_adj = 0.9 * prop_adj + 0.1 * int_adj;
809         if ( total_adj > 1.0 ) {
810             total_adj = 1.0;
811         }
812         else if ( total_adj < 0.0 ) {
813             total_adj = 0.0;
814         }
815
816         globals->get_controls()->set_throttle( FGControls::ALL_ENGINES,
817                                                total_adj );
818     }
819
820 #ifdef THIS_CODE_IS_NOT_USED
821     if (Mode == 2) // Glide slope hold
822         {
823             double RelSlope;
824             double RelElevator;
825
826             // First, calculate Relative slope and normalize it
827             RelSlope = NormalizeDegrees( TargetSlope - get_pitch());
828
829             // Now calculate the elevator offset from current angle
830             if ( abs(RelSlope) > SlopeSmooth )
831                 {
832                     if ( RelSlope < 0 )     //  set RelElevator to max in the correct direction
833                         RelElevator = -MaxElevator;
834                     else
835                         RelElevator = MaxElevator;
836                 }
837
838             else
839                 RelElevator = LinearExtrapolate(RelSlope,-SlopeSmooth,-MaxElevator,SlopeSmooth,MaxElevator);
840
841             // set the elevator
842             fgElevMove(RelElevator);
843
844         }
845 #endif // THIS_CODE_IS_NOT_USED
846
847     // stash this runs control settings
848     //  update_old_control_values();
849     old_aileron = globals->get_controls()->get_aileron();
850     old_elevator = globals->get_controls()->get_elevator();
851     old_elevator_trim = globals->get_controls()->get_elevator_trim();
852     old_rudder = globals->get_controls()->get_rudder();
853
854     // for cross track error
855     old_lat = lat;
856     old_lon = lon;
857         
858     // Ok, we are done
859     SG_LOG( SG_ALL, SG_DEBUG, "FGAutopilot::run( returns )" );
860
861     return 0;
862 }
863
864
865 void FGAutopilot::set_HeadingMode( fgAutoHeadingMode mode ) {
866     heading_mode = mode;
867
868     if ( heading_mode == FG_DG_HEADING_LOCK ) {
869         // set heading hold to current heading (as read from DG)
870         // ... no, leave target heading along ... just use the current
871         // heading bug value
872         //  DGTargetHeading = FGSteam::get_DG_deg();
873     } else if ( heading_mode == FG_TC_HEADING_LOCK ) {
874         // set autopilot to hold a zero turn (as reported by the TC)
875     } else if ( heading_mode == FG_TRUE_HEADING_LOCK ) {
876         // set heading hold to current heading
877         TargetHeading = heading_node->getDoubleValue();
878     } else if ( heading_mode == FG_HEADING_WAYPOINT ) {
879         if ( globals->get_route()->size() ) {
880             double course, distance;
881
882             old_lat = latitude_node->getDoubleValue();
883             old_lon = longitude_node->getDoubleValue();
884
885             waypoint = globals->get_route()->get_first();
886             waypoint.CourseAndDistance( longitude_node->getDoubleValue(),
887                                         latitude_node->getDoubleValue(),
888                                         altitude_node->getDoubleValue()
889                                         * SG_FEET_TO_METER,
890                                         &course, &distance );
891             TargetHeading = course;
892             TargetDistance = distance;
893             MakeTargetLatLonStr( waypoint.get_target_lat(),
894                                  waypoint.get_target_lon() );
895             MakeTargetWPStr( distance );
896
897             if ( waypoint.get_target_alt() > 0.0 ) {
898                 TargetAltitude = waypoint.get_target_alt();
899                 altitude_mode = FG_ALTITUDE_LOCK;
900                 set_AltitudeEnabled( true );
901                 MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
902             }
903
904             SG_LOG( SG_COCKPIT, SG_INFO, " set_HeadingMode: ( "
905                     << get_TargetLatitude()  << " "
906                     << get_TargetLongitude() << " ) "
907                     );
908         } else {
909             // no more way points, default to heading lock.
910             heading_mode = FG_TC_HEADING_LOCK;
911         }
912     }
913
914     MakeTargetHeadingStr( TargetHeading );                      
915     update_old_control_values();
916 }
917
918
919 void FGAutopilot::set_AltitudeMode( fgAutoAltitudeMode mode ) {
920     altitude_mode = mode;
921
922     alt_error_accum = 0.0;
923
924
925     if ( altitude_mode == FG_ALTITUDE_LOCK ) {
926         if ( TargetAltitude < altitude_agl_node->getDoubleValue()
927              * SG_FEET_TO_METER ) {
928         }
929
930         if ( fgGetString("/sim/startup/units") == "feet" ) {
931             MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
932         } else {
933             MakeTargetAltitudeStr( TargetAltitude * SG_METER_TO_FEET );
934         }
935     } else if ( altitude_mode == FG_ALTITUDE_GS1 ) {
936         climb_error_accum = 0.0;
937
938     } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
939         TargetAGL = altitude_agl_node->getDoubleValue() * SG_FEET_TO_METER;
940
941         if ( fgGetString("/sim/startup/units") == "feet" ) {
942             MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
943         } else {
944             MakeTargetAltitudeStr( TargetAGL * SG_METER_TO_FEET );
945         }
946     }
947     
948     update_old_control_values();
949     SG_LOG( SG_COCKPIT, SG_INFO, " set_AltitudeMode():" );
950 }
951
952
953 #if 0
954 static inline double get_aoa( void ) {
955     return( cur_fdm_state->get_Gamma_vert_rad() * SGD_RADIANS_TO_DEGREES );
956 }
957
958 static inline double fgAPget_latitude( void ) {
959     return( cur_fdm_state->get_Latitude() * SGD_RADIANS_TO_DEGREES );
960 }
961
962 static inline double fgAPget_longitude( void ) {
963     return( cur_fdm_state->get_Longitude() * SGD_RADIANS_TO_DEGREES );
964 }
965
966 static inline double fgAPget_roll( void ) {
967     return( cur_fdm_state->get_Phi() * SGD_RADIANS_TO_DEGREES );
968 }
969
970 static inline double get_pitch( void ) {
971     return( cur_fdm_state->get_Theta() );
972 }
973
974 double fgAPget_heading( void ) {
975     return( cur_fdm_state->get_Psi() * SGD_RADIANS_TO_DEGREES );
976 }
977
978 static inline double fgAPget_altitude( void ) {
979     return( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
980 }
981
982 static inline double fgAPget_climb( void ) {
983     // return in meters per minute
984     return( cur_fdm_state->get_Climb_Rate() * SG_FEET_TO_METER * 60 );
985 }
986
987 static inline double get_sideslip( void ) {
988     return( cur_fdm_state->get_Beta() );
989 }
990
991 static inline double fgAPget_agl( void ) {
992     double agl;
993
994     agl = cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
995         - scenery.get_cur_elev();
996
997     return( agl );
998 }
999 #endif
1000
1001
1002 void FGAutopilot::AltitudeSet( double new_altitude ) {
1003     double target_alt = new_altitude;
1004
1005     // cout << "new altitude = " << new_altitude << endl;
1006
1007     if ( fgGetString("/sim/startup/units") == "feet" ) {
1008         target_alt = new_altitude * SG_FEET_TO_METER;
1009     }
1010
1011     if( target_alt < scenery.get_cur_elev() ) {
1012         target_alt = scenery.get_cur_elev();
1013     }
1014
1015     TargetAltitude = target_alt;
1016     altitude_mode = FG_ALTITUDE_LOCK;
1017
1018     // cout << "TargetAltitude = " << TargetAltitude << endl;
1019
1020     if ( fgGetString("/sim/startup/units") == "feet" ) {
1021         target_alt *= SG_METER_TO_FEET;
1022     }
1023     // ApAltitudeDialogInput->setValue((float)target_alt);
1024     MakeTargetAltitudeStr( target_alt );
1025         
1026     update_old_control_values();
1027 }
1028
1029
1030 void FGAutopilot::AltitudeAdjust( double inc )
1031 {
1032     double target_alt, target_agl;
1033
1034     if ( fgGetString("/sim/startup/units") == "feet" ) {
1035         target_alt = TargetAltitude * SG_METER_TO_FEET;
1036         target_agl = TargetAGL * SG_METER_TO_FEET;
1037     } else {
1038         target_alt = TargetAltitude;
1039         target_agl = TargetAGL;
1040     }
1041
1042     // cout << "target_agl = " << target_agl << endl;
1043     // cout << "target_agl / inc = " << target_agl / inc << endl;
1044     // cout << "(int)(target_agl / inc) = " << (int)(target_agl / inc) << endl;
1045
1046     if ( fabs((int)(target_alt / inc) * inc - target_alt) < SG_EPSILON ) {
1047         target_alt += inc;
1048     } else {
1049         target_alt = ( int ) ( target_alt / inc ) * inc + inc;
1050     }
1051
1052     if ( fabs((int)(target_agl / inc) * inc - target_agl) < SG_EPSILON ) {
1053         target_agl += inc;
1054     } else {
1055         target_agl = ( int ) ( target_agl / inc ) * inc + inc;
1056     }
1057
1058     if ( fgGetString("/sim/startup/units") == "feet" ) {
1059         target_alt *= SG_FEET_TO_METER;
1060         target_agl *= SG_FEET_TO_METER;
1061     }
1062
1063     TargetAltitude = target_alt;
1064     TargetAGL = target_agl;
1065         
1066     if ( fgGetString("/sim/startup/units") == "feet" )
1067         target_alt *= SG_METER_TO_FEET;
1068     if ( fgGetString("/sim/startup/units") == "feet" )
1069         target_agl *= SG_METER_TO_FEET;
1070
1071     if ( altitude_mode == FG_ALTITUDE_LOCK ) {
1072         MakeTargetAltitudeStr( target_alt );
1073     } else if ( altitude_mode == FG_ALTITUDE_TERRAIN ) {
1074         MakeTargetAltitudeStr( target_agl );
1075     }
1076
1077     update_old_control_values();
1078 }
1079
1080
1081 void FGAutopilot::HeadingAdjust( double inc ) {
1082     if ( heading_mode != FG_DG_HEADING_LOCK
1083          && heading_mode != FG_TRUE_HEADING_LOCK )
1084     {
1085         heading_mode = FG_DG_HEADING_LOCK;
1086     }
1087
1088     if ( heading_mode == FG_DG_HEADING_LOCK ) {
1089         double target = ( int ) ( DGTargetHeading / inc ) * inc + inc;
1090         DGTargetHeading = NormalizeDegrees( target );
1091     } else {
1092         double target = ( int ) ( TargetHeading / inc ) * inc + inc;
1093         TargetHeading = NormalizeDegrees( target );
1094     }
1095
1096     update_old_control_values();
1097 }
1098
1099
1100 void FGAutopilot::HeadingSet( double new_heading ) {
1101     if( heading_mode == FG_TRUE_HEADING_LOCK ) {
1102         new_heading = NormalizeDegrees( new_heading );
1103         TargetHeading = new_heading;
1104         MakeTargetHeadingStr( TargetHeading );
1105     } else {
1106         heading_mode = FG_DG_HEADING_LOCK;
1107
1108         new_heading = NormalizeDegrees( new_heading );
1109         DGTargetHeading = new_heading;
1110         // following cast needed ambiguous plib
1111         // ApHeadingDialogInput -> setValue ((float)APData->TargetHeading );
1112         MakeTargetHeadingStr( DGTargetHeading );
1113     }
1114     update_old_control_values();
1115 }
1116
1117 void FGAutopilot::AutoThrottleAdjust( double inc ) {
1118     double target = ( int ) ( TargetSpeed / inc ) * inc + inc;
1119
1120     TargetSpeed = target;
1121 }
1122
1123
1124 void FGAutopilot::set_AutoThrottleEnabled( bool value ) {
1125     auto_throttle = value;
1126
1127     if ( auto_throttle == true ) {
1128         TargetSpeed = fgGetDouble("/velocities/airspeed-kt");
1129         speed_error_accum = 0.0;
1130     }
1131
1132     update_old_control_values();
1133     SG_LOG( SG_COCKPIT, SG_INFO, " fgAPSetAutoThrottle: ("
1134             << auto_throttle << ") " << TargetSpeed );
1135 }