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