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