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