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