]> git.mxchange.org Git - flightgear.git/blob - src/FDM/flight.cxx
Port over remaining Point3D usage to the more type and unit safe SG* classes.
[flightgear.git] / src / FDM / flight.cxx
1 // flight.cxx -- a general interface to the various flight models
2 //
3 // Written by Curtis Olson, started May 1997.
4 //
5 // Copyright (C) 1997  Curtis L. Olson  - http://www.flightgear.org/~curt
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23 #ifdef HAVE_CONFIG_H
24 #  include "config.h"
25 #endif
26
27 #include "flight.hxx"
28
29 #include <simgear/constants.h>
30 #include <simgear/debug/logstream.hxx>
31 #include <simgear/math/SGMath.hxx>
32 #include <simgear/timing/timestamp.hxx>
33
34 #include <Scenery/scenery.hxx>
35 #include <Main/globals.hxx>
36 #include <Main/fg_props.hxx>
37 #include <FDM/groundcache.hxx>
38
39
40 static inline void assign(double* ptr, const SGVec3d& vec)
41 {
42   ptr[0] = vec[0];
43   ptr[1] = vec[1];
44   ptr[2] = vec[2];
45 }
46
47 // base_fdm_state is the internal state that is updated in integer
48 // multiples of "dt".  This leads to "jitter" with respect to the real
49 // world time, so we introduce cur_fdm_state which is extrapolated by
50 // the difference between sim time and real world time
51
52 FGInterface *cur_fdm_state = 0;
53 FGInterface base_fdm_state;
54
55 // Constructor
56 FGInterface::FGInterface()
57   : remainder(0)
58 {
59     _setup();
60 }
61
62 FGInterface::FGInterface( double dt )
63   : remainder(0)
64 {
65     _setup();
66 }
67
68 // Destructor
69 FGInterface::~FGInterface() {
70     // unbind();                   // FIXME: should be called explicitly
71 }
72
73
74 int
75 FGInterface::_calc_multiloop (double dt)
76 {
77   int hz = fgGetInt("/sim/model-hz");
78   int speedup = fgGetInt("/sim/speed-up");
79
80   dt += remainder;
81   remainder = 0;
82   double ml = dt * hz;
83   // Avoid roundoff problems by adding the roundoff itself.
84   // ... ok, two times the roundoff to have enough room.
85   int multiloop = int(floor(ml * (1.0 + 2.0*DBL_EPSILON)));
86   remainder = (ml - multiloop) / hz;
87
88   // If we artificially inflate ml above by a tiny amount to get the
89   // closest integer, then subtract the integer from the original
90   // slightly smaller value, we can get a negative remainder.
91   // Logically this should never happen, and we definitely don't want
92   // to carry a negative remainder over to the next iteration, so
93   // never let the remainder go below zero.
94   // 
95   // Note: this fixes a problem where we run 1, 3, 1, 3, 1, 3... loops
96   // of the FDM when in fact we want to run 2, 2, 2, 2, 2...
97   if ( remainder < 0 ) { remainder = 0; }
98
99   return (multiloop * speedup);
100 }
101
102
103 /**
104  * Set default values for the state of the FDM.
105  *
106  * This method is invoked by the constructors.
107  */
108 void
109 FGInterface::_setup ()
110 {
111     inited = false;
112     bound = false;
113
114     d_cg_rp_body_v = SGVec3d::zeros();
115     v_dot_local_v = SGVec3d::zeros();
116     v_dot_body_v = SGVec3d::zeros();
117     a_cg_body_v = SGVec3d::zeros();
118     a_pilot_body_v = SGVec3d::zeros();
119     n_cg_body_v = SGVec3d::zeros();
120     v_local_v = SGVec3d::zeros();
121     v_local_rel_ground_v = SGVec3d::zeros();
122     v_local_airmass_v = SGVec3d::zeros();
123     v_wind_body_v = SGVec3d::zeros();
124     omega_body_v = SGVec3d::zeros();
125     euler_rates_v = SGVec3d::zeros();
126     geocentric_rates_v = SGVec3d::zeros();
127     geodetic_position_v = SGGeod::fromRadM(0, 0, 0);
128     cartesian_position_v = SGVec3d::fromGeod(geodetic_position_v);
129     geocentric_position_v = SGGeoc::fromCart(cartesian_position_v);
130     euler_angles_v = SGVec3d::zeros();
131     
132     nlf=0;
133     v_rel_wind=v_true_kts=0;
134     v_ground_speed=v_equiv_kts=0;
135     v_calibrated_kts=0;
136     alpha=beta=0;
137     gamma_vert_rad=0;
138     density=mach_number=0;
139     static_pressure=total_pressure=0;
140     dynamic_pressure=0;
141     static_temperature=total_temperature=0;
142     sea_level_radius=earth_position_angle=0;
143     runway_altitude=0;
144     climb_rate=0;
145     altitude_agl=0;
146 }
147
148 void
149 FGInterface::init () {}
150
151 /**
152  * Initialize the state of the FDM.
153  *
154  * Subclasses of FGInterface may do their own, additional initialization,
155  * but there is some that is common to all.  Normally, they should call
156  * this before they begin their own init to make sure the basic structures
157  * are set up properly.
158  */
159 void
160 FGInterface::common_init ()
161 {
162     SG_LOG( SG_FLIGHT, SG_INFO, "Start common FDM init" );
163
164     set_inited( true );
165
166     ground_cache.set_cache_time_offset(globals->get_sim_time_sec());
167
168 //     stamp();
169 //     set_remainder( 0 );
170
171     // Set initial position
172     SG_LOG( SG_FLIGHT, SG_INFO, "...initializing position..." );
173     double lon = fgGetDouble("/sim/presets/longitude-deg")
174       * SGD_DEGREES_TO_RADIANS;
175     double lat = fgGetDouble("/sim/presets/latitude-deg")
176       * SGD_DEGREES_TO_RADIANS;
177     double alt_ft = fgGetDouble("/sim/presets/altitude-ft");
178     double alt_m = alt_ft * SG_FEET_TO_METER;
179     set_Longitude( lon );
180     set_Latitude( lat );
181     SG_LOG( SG_FLIGHT, SG_INFO, "Checking for lon = "
182             << lon*SGD_RADIANS_TO_DEGREES << "deg, lat = "
183             << lat*SGD_RADIANS_TO_DEGREES << "deg, alt = "
184             << alt_ft << "ft");
185
186     double ground_elev_m = get_groundlevel_m(lat, lon, alt_m);
187     double ground_elev_ft = ground_elev_m * SG_METER_TO_FEET;
188     _set_Runway_altitude ( ground_elev_ft );
189     if ( fgGetBool("/sim/presets/onground") || alt_ft < ground_elev_ft ) {
190         fgSetDouble("/position/altitude-ft", ground_elev_ft + 0.1);
191         set_Altitude( ground_elev_ft + 0.1);
192     } else {
193         set_Altitude( alt_ft );
194     }
195
196     // Set ground elevation
197     SG_LOG( SG_FLIGHT, SG_INFO,
198             "...initializing ground elevation to " << ground_elev_ft
199             << "ft..." );
200
201     // Set sea-level radius
202     SG_LOG( SG_FLIGHT, SG_INFO, "...initializing sea-level radius..." );
203     SG_LOG( SG_FLIGHT, SG_INFO, " lat = "
204             << fgGetDouble("/sim/presets/latitude-deg")
205             << " alt = " << get_Altitude() );
206     double slr = SGGeodesy::SGGeodToSeaLevelRadius(geodetic_position_v);
207     _set_Sea_level_radius( slr * SG_METER_TO_FEET );
208
209     // Set initial velocities
210     SG_LOG( SG_FLIGHT, SG_INFO, "...initializing velocities..." );
211     if ( !fgHasNode("/sim/presets/speed-set") ) {
212         set_V_calibrated_kts(0.0);
213     } else {
214         const string speedset = fgGetString("/sim/presets/speed-set");
215         if ( speedset == "knots" || speedset == "KNOTS" ) {
216             set_V_calibrated_kts( fgGetDouble("/sim/presets/airspeed-kt") );
217         } else if ( speedset == "mach" || speedset == "MACH" ) {
218             set_Mach_number( fgGetDouble("/sim/presets/mach") );
219         } else if ( speedset == "UVW" || speedset == "uvw" ) {
220             set_Velocities_Wind_Body(
221                                      fgGetDouble("/sim/presets/uBody-fps"),
222                                      fgGetDouble("/sim/presets/vBody-fps"),
223                                      fgGetDouble("/sim/presets/wBody-fps") );
224         } else if ( speedset == "NED" || speedset == "ned" ) {
225             set_Velocities_Local(
226                                  fgGetDouble("/sim/presets/speed-north-fps"),
227                                  fgGetDouble("/sim/presets/speed-east-fps"),
228                                  fgGetDouble("/sim/presets/speed-down-fps") );
229         } else {
230             SG_LOG( SG_FLIGHT, SG_ALERT,
231                     "Unrecognized value for /sim/presets/speed-set: "
232                     << speedset);
233             set_V_calibrated_kts( 0.0 );
234         }
235     }
236
237     // Set initial Euler angles
238     SG_LOG( SG_FLIGHT, SG_INFO, "...initializing Euler angles..." );
239     set_Euler_Angles( fgGetDouble("/sim/presets/roll-deg")
240                         * SGD_DEGREES_TO_RADIANS,
241                       fgGetDouble("/sim/presets/pitch-deg")
242                         * SGD_DEGREES_TO_RADIANS,
243                       fgGetDouble("/sim/presets/heading-deg")
244                         * SGD_DEGREES_TO_RADIANS );
245
246     SG_LOG( SG_FLIGHT, SG_INFO, "End common FDM init" );
247 }
248
249
250 /**
251  * Bind getters and setters to properties.
252  *
253  * The bind() method will be invoked after init().  Note that unlike
254  * the usual implementations of FGSubsystem::bind(), this method does
255  * not automatically pick up existing values for the properties at
256  * bind time; instead, all values are set explicitly in the init()
257  * method.
258  */
259 void
260 FGInterface::bind ()
261 {
262   bound = true;
263
264                                 // Time management (read-only)
265 //   fgTie("/fdm/time/delta_t", this,
266 //         &FGInterface::get_delta_t); // read-only
267 //   fgTie("/fdm/time/elapsed", this,
268 //         &FGInterface::get_elapsed); // read-only
269 //   fgTie("/fdm/time/remainder", this,
270 //         &FGInterface::get_remainder); // read-only
271 //   fgTie("/fdm/time/multi_loop", this,
272 //         &FGInterface::get_multi_loop); // read-only
273
274                         // Aircraft position
275   fgTie("/position/latitude-deg", this,
276         &FGInterface::get_Latitude_deg,
277         &FGInterface::set_Latitude_deg,
278         false);
279   fgSetArchivable("/position/latitude-deg");
280   fgTie("/position/longitude-deg", this,
281         &FGInterface::get_Longitude_deg,
282         &FGInterface::set_Longitude_deg,
283         false);
284   fgSetArchivable("/position/longitude-deg");
285   fgTie("/position/altitude-ft", this,
286         &FGInterface::get_Altitude,
287         &FGInterface::set_Altitude,
288         false);
289   fgSetArchivable("/position/altitude-ft");
290   fgTie("/position/altitude-agl-ft", this,
291         &FGInterface::get_Altitude_AGL); // read-only
292   fgSetArchivable("/position/ground-elev-ft");
293   fgTie("/position/ground-elev-ft", this,
294         &FGInterface::get_Runway_altitude); // read-only
295   fgSetArchivable("/position/ground-elev-m");
296   fgTie("/position/ground-elev-m", this,
297         &FGInterface::get_Runway_altitude_m); // read-only
298   fgTie("/environment/ground-elevation-m", this,
299         &FGInterface::get_Runway_altitude_m); // read-only
300   fgSetArchivable("/position/sea-level-radius-ft");
301   fgTie("/position/sea-level-radius-ft", this,
302         &FGInterface::get_Sea_level_radius); // read-only
303
304                                 // Orientation
305   fgTie("/orientation/roll-deg", this,
306         &FGInterface::get_Phi_deg,
307         &FGInterface::set_Phi_deg);
308   fgSetArchivable("/orientation/roll-deg");
309   fgTie("/orientation/pitch-deg", this,
310         &FGInterface::get_Theta_deg,
311         &FGInterface::set_Theta_deg);
312   fgSetArchivable("/orientation/pitch-deg");
313   fgTie("/orientation/heading-deg", this,
314         &FGInterface::get_Psi_deg,
315         &FGInterface::set_Psi_deg);
316   fgSetArchivable("/orientation/heading-deg");
317
318   // Body-axis "euler rates" (rotation speed, but in a funny
319   // representation).
320   fgTie("/orientation/roll-rate-degps", this,
321         &FGInterface::get_Phi_dot_degps);
322   fgTie("/orientation/pitch-rate-degps", this,
323         &FGInterface::get_Theta_dot_degps);
324   fgTie("/orientation/yaw-rate-degps", this,
325         &FGInterface::get_Psi_dot_degps);
326
327                                 // Ground speed knots
328   fgTie("/velocities/groundspeed-kt", this,
329         &FGInterface::get_V_ground_speed_kt);
330
331                                 // Calibrated airspeed
332   fgTie("/velocities/airspeed-kt", this,
333         &FGInterface::get_V_calibrated_kts,
334         &FGInterface::set_V_calibrated_kts,
335         false);
336
337                                 // Mach number
338   fgTie("/velocities/mach", this,
339         &FGInterface::get_Mach_number,
340         &FGInterface::set_Mach_number,
341         false);
342
343                                 // Local velocities
344 //   fgTie("/velocities/speed-north-fps", this,
345 //      &FGInterface::get_V_north,
346 //      &FGInterface::set_V_north);
347 //   fgSetArchivable("/velocities/speed-north-fps");
348 //   fgTie("/velocities/speed-east-fps", this,
349 //      &FGInterface::get_V_east,
350 //      &FGInterface::set_V_east);
351 //   fgSetArchivable("/velocities/speed-east-fps");
352 //   fgTie("/velocities/speed-down-fps", this,
353 //      &FGInterface::get_V_down,
354 //      &FGInterface::set_V_down);
355 //   fgSetArchivable("/velocities/speed-down-fps");
356                                 // FIXME: Temporarily read-only, until the
357                                 // incompatibilities between JSBSim and
358                                 // LaRCSim are fixed (LaRCSim adds the
359                                 // earth's rotation to the east velocity).
360   fgTie("/velocities/speed-north-fps", this,
361         &FGInterface::get_V_north);
362   fgTie("/velocities/speed-east-fps", this,
363         &FGInterface::get_V_east);
364   fgTie("/velocities/speed-down-fps", this,
365         &FGInterface::get_V_down);
366
367                                 // Relative wind
368                                 // FIXME: temporarily archivable, until
369                                 // the NED problem is fixed.
370   fgTie("/velocities/uBody-fps", this,
371         &FGInterface::get_uBody,
372         &FGInterface::set_uBody,
373         false);
374   fgSetArchivable("/velocities/uBody-fps");
375   fgTie("/velocities/vBody-fps", this,
376         &FGInterface::get_vBody,
377         &FGInterface::set_vBody,
378         false);
379   fgSetArchivable("/velocities/vBody-fps");
380   fgTie("/velocities/wBody-fps", this,
381         &FGInterface::get_wBody,
382         &FGInterface::set_wBody,
383         false);
384   fgSetArchivable("/velocities/wBody-fps");
385
386                                 // Climb and slip (read-only)
387   fgTie("/velocities/vertical-speed-fps", this,
388         &FGInterface::get_Climb_Rate,
389   &FGInterface::set_Climb_Rate ); 
390   fgTie("/velocities/glideslope", this,
391   &FGInterface::get_Gamma_vert_rad,
392   &FGInterface::set_Gamma_vert_rad );
393   fgTie("/orientation/side-slip-rad", this,
394         &FGInterface::get_Beta); // read-only
395   fgTie("/orientation/side-slip-deg", this,
396   &FGInterface::get_Beta_deg); // read-only
397   fgTie("/orientation/alpha-deg", this,
398   &FGInterface::get_Alpha_deg); // read-only
399   fgTie("/accelerations/nlf", this,
400   &FGInterface::get_Nlf); // read-only
401
402                                 // NED accelerations
403   fgTie("/accelerations/ned/north-accel-fps_sec",
404         this, &FGInterface::get_V_dot_north);
405   fgTie("/accelerations/ned/east-accel-fps_sec",
406         this, &FGInterface::get_V_dot_east);
407   fgTie("/accelerations/ned/down-accel-fps_sec",
408         this, &FGInterface::get_V_dot_down);
409
410                                 // Pilot accelerations
411   fgTie("/accelerations/pilot/x-accel-fps_sec",
412         this, &FGInterface::get_A_X_pilot);
413   fgTie("/accelerations/pilot/y-accel-fps_sec",
414         this, &FGInterface::get_A_Y_pilot);
415   fgTie("/accelerations/pilot/z-accel-fps_sec",
416         this, &FGInterface::get_A_Z_pilot);
417
418 }
419
420
421 /**
422  * Unbind any properties bound to this FDM.
423  *
424  * This method allows the FDM to release properties so that a new
425  * FDM can bind them instead.
426  */
427 void
428 FGInterface::unbind ()
429 {
430   bound = false;
431
432   // fgUntie("/fdm/time/delta_t");
433   // fgUntie("/fdm/time/elapsed");
434   // fgUntie("/fdm/time/remainder");
435   // fgUntie("/fdm/time/multi_loop");
436   fgUntie("/position/latitude-deg");
437   fgUntie("/position/longitude-deg");
438   fgUntie("/position/altitude-ft");
439   fgUntie("/position/altitude-agl-ft");
440   fgUntie("/position/ground-elev-ft");
441   fgUntie("/position/ground-elev-m");
442   fgUntie("/environment/ground-elevation-m");
443   fgUntie("/position/sea-level-radius-ft");
444   fgUntie("/orientation/roll-deg");
445   fgUntie("/orientation/pitch-deg");
446   fgUntie("/orientation/heading-deg");
447   fgUntie("/orientation/roll-rate-degps");
448   fgUntie("/orientation/pitch-rate-degps");
449   fgUntie("/orientation/yaw-rate-degps");
450   fgUntie("/orientation/side-slip-rad");
451   fgUntie("/orientation/side-slip-deg");
452   fgUntie("/orientation/alpha-deg");
453   fgUntie("/velocities/airspeed-kt");
454   fgUntie("/velocities/groundspeed-kt");
455   fgUntie("/velocities/mach");
456   fgUntie("/velocities/speed-north-fps");
457   fgUntie("/velocities/speed-east-fps");
458   fgUntie("/velocities/speed-down-fps");
459   fgUntie("/velocities/uBody-fps");
460   fgUntie("/velocities/vBody-fps");
461   fgUntie("/velocities/wBody-fps");
462   fgUntie("/velocities/vertical-speed-fps");
463   fgUntie("/velocities/glideslope");
464   fgUntie("/accelerations/nlf");
465   fgUntie("/accelerations/pilot/x-accel-fps_sec");
466   fgUntie("/accelerations/pilot/y-accel-fps_sec");
467   fgUntie("/accelerations/pilot/z-accel-fps_sec");
468   fgUntie("/accelerations/ned/north-accel-fps_sec");
469   fgUntie("/accelerations/ned/east-accel-fps_sec");
470   fgUntie("/accelerations/ned/down-accel-fps_sec");
471 }
472
473 /**
474  * Update the state of the FDM (i.e. run the equations of motion).
475  */
476 void
477 FGInterface::update (double dt)
478 {
479     SG_LOG(SG_FLIGHT, SG_ALERT, "dummy update() ... SHOULDN'T BE CALLED!");
480 }
481
482
483 void FGInterface::_updatePositionM(const SGVec3d& cartPos)
484 {
485     cartesian_position_v = cartPos;
486     geodetic_position_v = SGGeod::fromCart(cartesian_position_v);
487     geocentric_position_v = SGGeoc::fromCart(cartesian_position_v);
488     _set_Sea_level_radius( SGGeodesy::SGGeodToSeaLevelRadius(geodetic_position_v)*SG_METER_TO_FEET );
489     _update_ground_elev_at_pos();
490 }
491
492
493 void FGInterface::_updatePosition(const SGGeod& geod)
494 {
495     geodetic_position_v = geod;
496     cartesian_position_v = SGVec3d::fromGeod(geodetic_position_v);
497     geocentric_position_v = SGGeoc::fromCart(cartesian_position_v);
498
499     _set_Sea_level_radius( SGGeodesy::SGGeodToSeaLevelRadius(geodetic_position_v)*SG_METER_TO_FEET );
500     _update_ground_elev_at_pos();
501 }
502
503
504 void FGInterface::_updatePosition(const SGGeoc& geoc)
505 {
506     geocentric_position_v = geoc;
507     cartesian_position_v = SGVec3d::fromGeoc(geocentric_position_v);
508     geodetic_position_v = SGGeod::fromCart(cartesian_position_v);
509
510     _set_Sea_level_radius( SGGeodesy::SGGeodToSeaLevelRadius(geodetic_position_v)*SG_METER_TO_FEET );
511     _update_ground_elev_at_pos();
512 }
513
514
515 void FGInterface::_updateGeodeticPosition( double lat, double lon, double alt )
516 {
517     _updatePosition(SGGeod::fromRadFt(lon, lat, alt));
518 }
519
520
521 void FGInterface::_updateGeocentricPosition( double lat, double lon,
522                                              double alt )
523 {
524     _updatePosition(SGGeoc::fromRadFt(lon, lat, get_Sea_level_radius() + alt));
525 }
526
527 void FGInterface::_update_ground_elev_at_pos( void ) {
528     double groundlevel_m = get_groundlevel_m(geodetic_position_v);
529     _set_Runway_altitude( groundlevel_m * SG_METER_TO_FEET );
530 }
531
532 // Positions
533 void FGInterface::set_Latitude(double lat) {
534     geodetic_position_v.setLatitudeRad(lat);
535 }
536
537 void FGInterface::set_Longitude(double lon) {
538     geodetic_position_v.setLongitudeRad(lon);
539 }
540
541 void FGInterface::set_Altitude(double alt) {
542     geodetic_position_v.setElevationFt(alt);
543 }
544
545 void FGInterface::set_AltitudeAGL(double altagl) {
546     altitude_agl=altagl;
547 }
548
549 // Velocities
550 void FGInterface::set_V_calibrated_kts(double vc) {
551     v_calibrated_kts = vc;
552 }
553
554 void FGInterface::set_Mach_number(double mach) {
555     mach_number = mach;
556 }
557
558 void FGInterface::set_Velocities_Local( double north, 
559                                         double east, 
560                                         double down ){
561     v_local_v[0] = north;
562     v_local_v[1] = east;
563     v_local_v[2] = down;
564 }
565
566 void FGInterface::set_Velocities_Wind_Body( double u, 
567                                             double v, 
568                                             double w){
569     v_wind_body_v[0] = u;
570     v_wind_body_v[1] = v;
571     v_wind_body_v[2] = w;
572 }
573
574 // Euler angles 
575 void FGInterface::set_Euler_Angles( double phi, 
576                                     double theta, 
577                                     double psi ) {
578     euler_angles_v[0] = phi;
579     euler_angles_v[1] = theta;
580     euler_angles_v[2] = psi;                                            
581 }  
582
583 // Flight Path
584 void FGInterface::set_Climb_Rate( double roc) {
585     climb_rate = roc;
586 }
587
588 void FGInterface::set_Gamma_vert_rad( double gamma) {
589     gamma_vert_rad = gamma;
590 }
591
592 void FGInterface::set_Static_pressure(double p) { static_pressure = p; }
593 void FGInterface::set_Static_temperature(double T) { static_temperature = T; }
594 void FGInterface::set_Density(double rho) { density = rho; }
595
596 void FGInterface::set_Velocities_Local_Airmass (double wnorth, 
597                                                 double weast, 
598                                                 double wdown ) {
599     v_local_airmass_v[0] = wnorth;
600     v_local_airmass_v[1] = weast;
601     v_local_airmass_v[2] = wdown;
602 }
603
604
605 void FGInterface::_busdump(void) {
606
607     SG_LOG(SG_FLIGHT,SG_INFO,"d_cg_rp_body_v: " << d_cg_rp_body_v);
608     SG_LOG(SG_FLIGHT,SG_INFO,"v_dot_local_v: " << v_dot_local_v);
609     SG_LOG(SG_FLIGHT,SG_INFO,"v_dot_body_v: " << v_dot_body_v);
610     SG_LOG(SG_FLIGHT,SG_INFO,"a_cg_body_v: " << a_cg_body_v);
611     SG_LOG(SG_FLIGHT,SG_INFO,"a_pilot_body_v: " << a_pilot_body_v);
612     SG_LOG(SG_FLIGHT,SG_INFO,"n_cg_body_v: " << n_cg_body_v);
613     SG_LOG(SG_FLIGHT,SG_INFO,"v_local_v: " << v_local_v);
614     SG_LOG(SG_FLIGHT,SG_INFO,"v_local_rel_ground_v: " << v_local_rel_ground_v);
615     SG_LOG(SG_FLIGHT,SG_INFO,"v_local_airmass_v: " << v_local_airmass_v);
616     SG_LOG(SG_FLIGHT,SG_INFO,"v_wind_body_v: " << v_wind_body_v);
617     SG_LOG(SG_FLIGHT,SG_INFO,"omega_body_v: " << omega_body_v);
618     SG_LOG(SG_FLIGHT,SG_INFO,"euler_rates_v: " << euler_rates_v);
619     SG_LOG(SG_FLIGHT,SG_INFO,"geocentric_rates_v: " << geocentric_rates_v);
620     SG_LOG(SG_FLIGHT,SG_INFO,"geocentric_position_v: " << geocentric_position_v);
621     SG_LOG(SG_FLIGHT,SG_INFO,"geodetic_position_v: " << geodetic_position_v);
622     SG_LOG(SG_FLIGHT,SG_INFO,"euler_angles_v: " << euler_angles_v);
623
624     SG_LOG(SG_FLIGHT,SG_INFO,"nlf: " << nlf );
625     SG_LOG(SG_FLIGHT,SG_INFO,"v_rel_wind: " << v_rel_wind );
626     SG_LOG(SG_FLIGHT,SG_INFO,"v_true_kts: " << v_true_kts );
627     SG_LOG(SG_FLIGHT,SG_INFO,"v_ground_speed: " << v_ground_speed );
628     SG_LOG(SG_FLIGHT,SG_INFO,"v_equiv_kts: " << v_equiv_kts );
629     SG_LOG(SG_FLIGHT,SG_INFO,"v_calibrated_kts: " << v_calibrated_kts );
630     SG_LOG(SG_FLIGHT,SG_INFO,"alpha: " << alpha );
631     SG_LOG(SG_FLIGHT,SG_INFO,"beta: " << beta );
632     SG_LOG(SG_FLIGHT,SG_INFO,"gamma_vert_rad: " << gamma_vert_rad );
633     SG_LOG(SG_FLIGHT,SG_INFO,"density: " << density );
634     SG_LOG(SG_FLIGHT,SG_INFO,"mach_number: " << mach_number );
635     SG_LOG(SG_FLIGHT,SG_INFO,"static_pressure: " << static_pressure );
636     SG_LOG(SG_FLIGHT,SG_INFO,"total_pressure: " << total_pressure );
637     SG_LOG(SG_FLIGHT,SG_INFO,"dynamic_pressure: " << dynamic_pressure );
638     SG_LOG(SG_FLIGHT,SG_INFO,"static_temperature: " << static_temperature );
639     SG_LOG(SG_FLIGHT,SG_INFO,"total_temperature: " << total_temperature );
640     SG_LOG(SG_FLIGHT,SG_INFO,"sea_level_radius: " << sea_level_radius );
641     SG_LOG(SG_FLIGHT,SG_INFO,"earth_position_angle: " << earth_position_angle );
642     SG_LOG(SG_FLIGHT,SG_INFO,"runway_altitude: " << runway_altitude );
643     SG_LOG(SG_FLIGHT,SG_INFO,"climb_rate: " << climb_rate );
644     SG_LOG(SG_FLIGHT,SG_INFO,"altitude_agl: " << altitude_agl );
645 }
646
647 bool
648 FGInterface::prepare_ground_cache_m(double startSimTime, double endSimTime,
649                                     const double pt[3], double rad)
650 {
651   return ground_cache.prepare_ground_cache(startSimTime, endSimTime,
652                                            SGVec3d(pt), rad);
653 }
654
655 bool
656 FGInterface::prepare_ground_cache_ft(double startSimTime, double endSimTime,
657                                      const double pt[3], double rad)
658 {
659   // Convert units and do the real work.
660   SGVec3d pt_ft = SG_FEET_TO_METER*SGVec3d(pt);
661   return ground_cache.prepare_ground_cache(startSimTime, endSimTime,
662                                            pt_ft, rad*SG_FEET_TO_METER);
663 }
664
665 bool
666 FGInterface::is_valid_m(double *ref_time, double pt[3], double *rad)
667 {
668   SGVec3d _pt;
669   bool valid = ground_cache.is_valid(*ref_time, _pt, *rad);
670   assign(pt, _pt);
671   return valid;
672 }
673
674 bool FGInterface::is_valid_ft(double *ref_time, double pt[3], double *rad)
675 {
676   // Convert units and do the real work.
677   SGVec3d _pt;
678   bool found_ground = ground_cache.is_valid(*ref_time, _pt, *rad);
679   assign(pt, SG_METER_TO_FEET*_pt);
680   *rad *= SG_METER_TO_FEET;
681   return found_ground;
682 }
683
684 double
685 FGInterface::get_cat_m(double t, const double pt[3],
686                        double end[2][3], double vel[2][3])
687 {
688   SGVec3d _end[2], _vel[2];
689   double dist = ground_cache.get_cat(t, SGVec3d(pt), _end, _vel);
690   for (int k=0; k<2; ++k) {
691     assign( end[k], _end[k] );
692     assign( vel[k], _vel[k] );
693   }
694   return dist;
695 }
696
697 double
698 FGInterface::get_cat_ft(double t, const double pt[3],
699                         double end[2][3], double vel[2][3])
700 {
701   // Convert units and do the real work.
702   SGVec3d pt_m = SG_FEET_TO_METER*SGVec3d(pt);
703   SGVec3d _end[2], _vel[2];
704   double dist = ground_cache.get_cat(t, pt_m, _end, _vel);
705   for (int k=0; k<2; ++k) {
706     assign( end[k], SG_METER_TO_FEET*_end[k] );
707     assign( vel[k], SG_METER_TO_FEET*_vel[k] );
708   }
709   return dist*SG_METER_TO_FEET;
710 }
711
712 bool
713 FGInterface::get_body_m(double t, simgear::BVHNode::Id id,
714                         double bodyToWorld[16], double linearVel[3],
715                         double angularVel[3])
716 {
717   SGMatrixd _bodyToWorld;
718   SGVec3d _linearVel, _angularVel;
719   if (!ground_cache.get_body(t, _bodyToWorld, _linearVel, _angularVel, id))
720     return false;
721
722   assign(linearVel, _linearVel);
723   assign(angularVel, _angularVel);
724   for (unsigned i = 0; i < 16; ++i)
725       bodyToWorld[i] = _bodyToWorld.data()[i];
726
727   return true;
728 }
729
730 bool
731 FGInterface::get_agl_m(double t, const double pt[3], double max_altoff,
732                        double contact[3], double normal[3],
733                        double linearVel[3], double angularVel[3],
734                        SGMaterial const*& material, simgear::BVHNode::Id& id)
735 {
736   SGVec3d pt_m = SGVec3d(pt) - max_altoff*ground_cache.get_down();
737   SGVec3d _contact, _normal, _linearVel, _angularVel;
738   material = 0;
739   bool ret = ground_cache.get_agl(t, pt_m, _contact, _normal, _linearVel,
740                                   _angularVel, id, material);
741   // correct the linear velocity, since the line intersector delivers
742   // values for the start point and the get_agl function should
743   // traditionally deliver for the contact point
744   _linearVel += cross(_angularVel, _contact - pt_m);
745
746   assign(contact, _contact);
747   assign(normal, _normal);
748   assign(linearVel, _linearVel);
749   assign(angularVel, _angularVel);
750   return ret;
751 }
752
753 bool
754 FGInterface::get_agl_ft(double t, const double pt[3], double max_altoff,
755                         double contact[3], double normal[3],
756                         double linearVel[3], double angularVel[3],
757                         SGMaterial const*& material, simgear::BVHNode::Id& id)
758 {
759   // Convert units and do the real work.
760   SGVec3d pt_m = SGVec3d(pt) - max_altoff*ground_cache.get_down();
761   pt_m *= SG_FEET_TO_METER;
762   SGVec3d _contact, _normal, _linearVel, _angularVel;
763   material = 0;
764   bool ret = ground_cache.get_agl(t, pt_m, _contact, _normal, _linearVel,
765                                   _angularVel, id, material);
766   // correct the linear velocity, since the line intersector delivers
767   // values for the start point and the get_agl function should
768   // traditionally deliver for the contact point
769   _linearVel += cross(_angularVel, _contact - pt_m);
770
771   // Convert units back ...
772   assign( contact, SG_METER_TO_FEET*_contact );
773   assign( normal, _normal );
774   assign( linearVel, SG_METER_TO_FEET*_linearVel );
775   assign( angularVel, _angularVel );
776   return ret;
777 }
778
779 bool
780 FGInterface::get_nearest_m(double t, const double pt[3], double maxDist,
781                            double contact[3], double normal[3],
782                            double linearVel[3], double angularVel[3],
783                            SGMaterial const*& material,
784                            simgear::BVHNode::Id& id)
785 {
786   SGVec3d _contact, _linearVel, _angularVel;
787   if (!ground_cache.get_nearest(t, SGVec3d(pt), maxDist, _contact, _linearVel,
788                                 _angularVel, id, material))
789       return false;
790
791   assign(contact, _contact);
792   assign(linearVel, _linearVel);
793   assign(angularVel, _angularVel);
794   return true;
795 }
796
797 bool
798 FGInterface::get_nearest_ft(double t, const double pt[3], double maxDist,
799                             double contact[3], double normal[3],
800                             double linearVel[3], double angularVel[3],
801                             SGMaterial const*& material,
802                             simgear::BVHNode::Id& id)
803 {
804   SGVec3d _contact, _linearVel, _angularVel;
805   if (!ground_cache.get_nearest(t, SG_FEET_TO_METER*SGVec3d(pt),
806                                 SG_FEET_TO_METER*maxDist, _contact, _linearVel,
807                                 _angularVel, id, material))
808       return false;
809
810   assign(contact, SG_METER_TO_FEET*_contact);
811   assign(linearVel, SG_METER_TO_FEET*_linearVel);
812   assign(angularVel, _angularVel);
813   return true;
814 }
815
816 double
817 FGInterface::get_groundlevel_m(double lat, double lon, double alt)
818 {
819   return get_groundlevel_m(SGGeod::fromRadM(lon, lat, alt));
820 }
821
822 double
823 FGInterface::get_groundlevel_m(const SGGeod& geod)
824 {
825   // Compute the cartesian position of the given lat/lon/alt.
826   SGVec3d pos = SGVec3d::fromGeod(geod);
827
828   // FIXME: how to handle t - ref_time differences ???
829   SGVec3d cpos;
830   double ref_time = 0, radius;
831   // Prepare the ground cache for that position.
832   if (!is_valid_m(&ref_time, cpos.data(), &radius)) {
833     double startTime = ref_time;
834     double endTime = startTime + 1;
835     bool ok = prepare_ground_cache_m(startTime, endTime, pos.data(), 10);
836     /// This is most likely the case when the given altitude is
837     /// too low, try with a new altitude of 10000m, that should be
838     /// sufficient to find a ground level below everywhere on our planet
839     if (!ok) {
840       pos = SGVec3d::fromGeod(SGGeod::fromGeodM(geod, 10000));
841       /// If there is still no ground, return sea level radius
842       if (!prepare_ground_cache_m(startTime, endTime, pos.data(), 10))
843         return 0;
844     }
845   } else if (radius*radius <= distSqr(pos, cpos)) {
846     double startTime = ref_time;
847     double endTime = startTime + 1;
848
849     /// We reuse the old radius value, but only if it is at least 10 Meters ..
850     if (!(10 < radius)) // Well this strange compare is nan safe
851       radius = 10;
852
853     bool ok = prepare_ground_cache_m(startTime, endTime, pos.data(), radius);
854     /// This is most likely the case when the given altitude is
855     /// too low, try with a new altitude of 10000m, that should be
856     /// sufficient to find a ground level below everywhere on our planet
857     if (!ok) {
858       pos = SGVec3d::fromGeod(SGGeod::fromGeodM(geod, 10000));
859       /// If there is still no ground, return sea level radius
860       if (!prepare_ground_cache_m(startTime, endTime, pos.data(), radius))
861         return 0;
862     }
863   }
864   
865   double contact[3], normal[3], vel[3], angvel[3];
866   const SGMaterial* material;
867   simgear::BVHNode::Id id;
868   // Ignore the return value here, since it just tells us if
869   // the returns stem from the groundcache or from the coarse
870   // computations below the groundcache. The contact point is still something
871   // valid, the normals and the other returns just contain some defaults.
872   get_agl_m(ref_time, pos.data(), 2.0, contact, normal, vel, angvel,
873             material, id);
874   return SGGeod::fromCart(SGVec3d(contact)).getElevationM();
875 }
876   
877 bool
878 FGInterface::caught_wire_m(double t, const double pt[4][3])
879 {
880   SGVec3d pt_m[4];
881   for (int i=0; i<4; ++i)
882     pt_m[i] = SGVec3d(pt[i]);
883   
884   return ground_cache.caught_wire(t, pt_m);
885 }
886
887 bool
888 FGInterface::caught_wire_ft(double t, const double pt[4][3])
889 {
890   // Convert units and do the real work.
891   SGVec3d pt_m[4];
892   for (int i=0; i<4; ++i)
893     pt_m[i] = SG_FEET_TO_METER*SGVec3d(pt[i]);
894     
895   return ground_cache.caught_wire(t, pt_m);
896 }
897   
898 bool
899 FGInterface::get_wire_ends_m(double t, double end[2][3], double vel[2][3])
900 {
901   SGVec3d _end[2], _vel[2];
902   bool ret = ground_cache.get_wire_ends(t, _end, _vel);
903   for (int k=0; k<2; ++k) {
904     assign( end[k], _end[k] );
905     assign( vel[k], _vel[k] );
906   }
907   return ret;
908 }
909
910 bool
911 FGInterface::get_wire_ends_ft(double t, double end[2][3], double vel[2][3])
912 {
913   // Convert units and do the real work.
914   SGVec3d _end[2], _vel[2];
915   bool ret = ground_cache.get_wire_ends(t, _end, _vel);
916   for (int k=0; k<2; ++k) {
917     assign( end[k], SG_METER_TO_FEET*_end[k] );
918     assign( vel[k], SG_METER_TO_FEET*_vel[k] );
919   }
920   return ret;
921 }
922
923 void
924 FGInterface::release_wire(void)
925 {
926   ground_cache.release_wire();
927 }
928
929 void fgToggleFDMdataLogging(void) {
930   cur_fdm_state->ToggleDataLogging();
931 }