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