]> git.mxchange.org Git - flightgear.git/blob - src/FDM/JSBSim/JSBSim.cxx
Merge branch 'next' of D:\Git_New\flightgear into next
[flightgear.git] / src / FDM / JSBSim / JSBSim.cxx
1 // JSBsim.cxx -- interface to the JSBsim flight model
2 //
3 // Written by Curtis Olson, started February 1999.
4 //
5 // Copyright (C) 1999  Curtis L. Olson  - curt@flightgear.org
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU Lesser 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 // Lesser General Public License for more details.
16 //
17 // You should have received a copy of the GNU Lesser General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 // $Id: JSBSim.cxx,v 1.64 2010/10/31 04:49:25 jberndt Exp $
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29 #include <simgear/sg_inlines.h>
30
31 #include <stdio.h>    //    size_t
32 #include <string>
33
34 #include <simgear/constants.h>
35 #include <simgear/debug/logstream.hxx>
36 #include <simgear/math/sg_geodesy.hxx>
37 #include <simgear/misc/sg_path.hxx>
38 #include <simgear/structure/commands.hxx>
39
40 #include <FDM/flight.hxx>
41
42 #include <Aircraft/controls.hxx>
43 #include <Main/globals.hxx>
44 #include <Main/fg_props.hxx>
45
46 #include "JSBSim.hxx"
47 #include <FDM/JSBSim/FGFDMExec.h>
48 #include <FDM/JSBSim/FGJSBBase.h>
49 #include <FDM/JSBSim/initialization/FGInitialCondition.h>
50 #include <FDM/JSBSim/initialization/FGTrim.h>
51 #include <FDM/JSBSim/models/FGModel.h>
52 #include <FDM/JSBSim/models/FGAircraft.h>
53 #include <FDM/JSBSim/models/FGFCS.h>
54 #include <FDM/JSBSim/models/FGPropagate.h>
55 #include <FDM/JSBSim/models/FGAuxiliary.h>
56 #include <FDM/JSBSim/models/FGInertial.h>
57 #include <FDM/JSBSim/models/FGAtmosphere.h>
58 #include <FDM/JSBSim/models/FGMassBalance.h>
59 #include <FDM/JSBSim/models/FGAerodynamics.h>
60 #include <FDM/JSBSim/models/FGLGear.h>
61 #include <FDM/JSBSim/models/FGGroundReactions.h>
62 #include <FDM/JSBSim/models/FGPropulsion.h>
63 #include <FDM/JSBSim/models/propulsion/FGEngine.h>
64 #include <FDM/JSBSim/models/propulsion/FGPiston.h>
65 #include <FDM/JSBSim/models/propulsion/FGTurbine.h>
66 #include <FDM/JSBSim/models/propulsion/FGTurboProp.h>
67 #include <FDM/JSBSim/models/propulsion/FGRocket.h>
68 #include <FDM/JSBSim/models/propulsion/FGElectric.h>
69 #include <FDM/JSBSim/models/propulsion/FGNozzle.h>
70 #include <FDM/JSBSim/models/propulsion/FGPropeller.h>
71 #include <FDM/JSBSim/models/propulsion/FGRotor.h>
72 #include <FDM/JSBSim/models/propulsion/FGTank.h>
73 #include <FDM/JSBSim/input_output/FGPropertyManager.h>
74 #include <FDM/JSBSim/input_output/FGGroundCallback.h>
75
76 using namespace JSBSim;
77
78 static inline double
79 FMAX (double a, double b)
80 {
81   return a > b ? a : b;
82 }
83
84 class FGFSGroundCallback : public FGGroundCallback {
85 public:
86   FGFSGroundCallback(FGJSBsim* ifc) : mInterface(ifc) {}
87   virtual ~FGFSGroundCallback() {}
88
89   /** Get the altitude above sea level dependent on the location. */
90   virtual double GetAltitude(const FGLocation& l) const {
91     double pt[3] = { SG_FEET_TO_METER*l(eX),
92                      SG_FEET_TO_METER*l(eY),
93                      SG_FEET_TO_METER*l(eZ) };
94     double lat, lon, alt;
95     sgCartToGeod( pt, &lat, &lon, &alt);
96     return alt * SG_METER_TO_FEET;
97   }
98
99   /** Compute the altitude above ground. */
100   virtual double GetAGLevel(double t, const FGLocation& l,
101                             FGLocation& cont, FGColumnVector3& n,
102                             FGColumnVector3& v, FGColumnVector3& w) const {
103     double loc_cart[3] = { l(eX), l(eY), l(eZ) };
104     double contact[3], normal[3], vel[3], angularVel[3], agl = 0;
105     mInterface->get_agl_ft(t, loc_cart, SG_METER_TO_FEET*2, contact, normal,
106                            vel, angularVel, &agl);
107     n = FGColumnVector3( normal[0], normal[1], normal[2] );
108     v = FGColumnVector3( vel[0], vel[1], vel[2] );
109     w = FGColumnVector3( angularVel[0], angularVel[1], angularVel[2] );
110     cont = FGColumnVector3( contact[0], contact[1], contact[2] );
111     return agl;
112   }
113 private:
114   FGJSBsim* mInterface;
115 };
116
117 // FG uses a squared normalized magnitude for turbulence
118 // this lookup table maps fg's severity levels 
119 // none(0), light(1/3), moderate(2/3) and severe(3/3)
120 // to the POE table indexes 0, 3, 4 and 7
121 class FGTurbulenceSeverityTable : public FGTable {
122 public:
123   FGTurbulenceSeverityTable() : FGTable(4) {
124     *this << (0.0/9.0) << 0.0;
125     *this << (1.0/9.0) << 3.0;
126     *this << (4.0/9.0) << 4.0;
127     *this << (9.0/9.0) << 7.0;
128   }
129 };
130
131 /******************************************************************************/
132 std::map<std::string,int> FGJSBsim::TURBULENCE_TYPE_NAMES;
133
134 static FGTurbulenceSeverityTable TurbulenceSeverityTable;
135
136 FGJSBsim::FGJSBsim( double dt )
137   : FGInterface(dt), got_wire(false)
138 {
139     bool result;
140     if( TURBULENCE_TYPE_NAMES.empty() ) {
141         TURBULENCE_TYPE_NAMES["ttNone"]     = FGAtmosphere::ttNone;
142         TURBULENCE_TYPE_NAMES["ttStandard"] = FGAtmosphere::ttStandard;
143         TURBULENCE_TYPE_NAMES["ttBerndt"]   = FGAtmosphere::ttBerndt;
144         TURBULENCE_TYPE_NAMES["ttCulp"]     = FGAtmosphere::ttCulp;
145         TURBULENCE_TYPE_NAMES["ttMilspec"]  = FGAtmosphere::ttMilspec;
146         TURBULENCE_TYPE_NAMES["ttTustin"]   = FGAtmosphere::ttTustin;
147     }
148
149                                 // Set up the debugging level
150                                 // FIXME: this will not respond to
151                                 // runtime changes
152
153                                 // if flight is excluded, don't bother
154     if ((logbuf::get_log_classes() & SG_FLIGHT) != 0) {
155
156                                 // do a rough-and-ready mapping to
157                                 // the levels documented in FGFDMExec.h
158         switch (logbuf::get_log_priority()) {
159         case SG_BULK:
160             FGJSBBase::debug_lvl = 0x1f;
161             break;
162         case SG_DEBUG:
163             FGJSBBase::debug_lvl = 0x0f;
164         case SG_INFO:
165             FGJSBBase::debug_lvl = 0x01;
166             break;
167         case SG_WARN:
168         case SG_ALERT:
169             FGJSBBase::debug_lvl = 0x00;
170             break;
171         }
172     }
173
174     fdmex = new FGFDMExec( (FGPropertyManager*)globals->get_props() );
175
176     // Register ground callback.
177     fdmex->SetGroundCallback( new FGFSGroundCallback(this) );
178
179     Atmosphere      = fdmex->GetAtmosphere();
180     FCS             = fdmex->GetFCS();
181     MassBalance     = fdmex->GetMassBalance();
182     Propulsion      = fdmex->GetPropulsion();
183     Aircraft        = fdmex->GetAircraft();
184     Propagate       = fdmex->GetPropagate();
185     Auxiliary       = fdmex->GetAuxiliary();
186     Inertial        = fdmex->GetInertial();
187     Aerodynamics    = fdmex->GetAerodynamics();
188     GroundReactions = fdmex->GetGroundReactions();
189
190     fgic=fdmex->GetIC();
191     needTrim=true;
192
193     SGPath aircraft_path( fgGetString("/sim/aircraft-dir") );
194
195     SGPath engine_path( fgGetString("/sim/aircraft-dir") );
196     engine_path.append( "Engine" );
197
198     SGPath systems_path( fgGetString("/sim/aircraft-dir") );
199     systems_path.append( "Systems" );
200
201 // deprecate sim-time-sec for simulation/sim-time-sec
202 // remove alias with increased configuration file version number (2.1 or later)
203     SGPropertyNode * node = fgGetNode("/fdm/jsbsim/simulation/sim-time-sec");
204     fgGetNode("/fdm/jsbsim/sim-time-sec", true)->alias( node );
205 // end of sim-time-sec deprecation patch
206
207     fdmex->Setdt( dt );
208
209     result = fdmex->LoadModel( aircraft_path.str(),
210                                engine_path.str(),
211                                systems_path.str(),
212                                fgGetString("/sim/aero"), false );
213
214     if (result) {
215       SG_LOG( SG_FLIGHT, SG_INFO, "  loaded aero.");
216     } else {
217       SG_LOG( SG_FLIGHT, SG_INFO,
218               "  aero does not exist (you may have mis-typed the name).");
219       throw(-1);
220     }
221
222     SG_LOG( SG_FLIGHT, SG_INFO, "" );
223     SG_LOG( SG_FLIGHT, SG_INFO, "" );
224     SG_LOG( SG_FLIGHT, SG_INFO, "After loading aero definition file ..." );
225
226     int Neng = Propulsion->GetNumEngines();
227     SG_LOG( SG_FLIGHT, SG_INFO, "num engines = " << Neng );
228
229     if ( GroundReactions->GetNumGearUnits() <= 0 ) {
230         SG_LOG( SG_FLIGHT, SG_ALERT, "num gear units = "
231                 << GroundReactions->GetNumGearUnits() );
232         SG_LOG( SG_FLIGHT, SG_ALERT, "This is a very bad thing because with 0 gear units, the ground trimming");
233         SG_LOG( SG_FLIGHT, SG_ALERT, "routine (coming up later in the code) will core dump.");
234         SG_LOG( SG_FLIGHT, SG_ALERT, "Halting the sim now, and hoping a solution will present itself soon!");
235         exit(-1);
236     }
237
238     init_gear();
239
240     // Set initial fuel levels if provided.
241     for (unsigned int i = 0; i < Propulsion->GetNumTanks(); i++) {
242       double d;
243       SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
244       FGTank* tank = Propulsion->GetTank(i);
245
246       d = node->getNode( "density-ppg", true )->getDoubleValue();
247       if( d > 0.0 ) {
248         tank->SetDensity( d );
249       } else {
250         node->getNode( "density-ppg", true )->setDoubleValue( SG_MAX2<double>(tank->GetDensity(), 0.1) );
251       }
252
253       d = node->getNode( "level-lbs", true )->getDoubleValue();
254       if( d > 0.0 ) {
255         tank->SetContents( d );
256       } else {
257         node->getNode( "level-lbs", true )->setDoubleValue( tank->GetContents() );
258       }
259       /* Capacity is read-only in FGTank and can't be overwritten from FlightGear */
260       node->getNode("capacity-gal_us", true )->setDoubleValue( tank->GetCapacityGallons() );
261     }
262     Propulsion->SetFuelFreeze((fgGetNode("/sim/freeze/fuel",true))->getBoolValue());
263
264     fgSetDouble("/fdm/trim/pitch-trim", FCS->GetPitchTrimCmd());
265     fgSetDouble("/fdm/trim/throttle",   FCS->GetThrottleCmd(0));
266     fgSetDouble("/fdm/trim/aileron",    FCS->GetDaCmd());
267     fgSetDouble("/fdm/trim/rudder",     FCS->GetDrCmd());
268
269     startup_trim = fgGetNode("/sim/presets/trim", true);
270
271     trimmed = fgGetNode("/fdm/trim/trimmed", true);
272     trimmed->setBoolValue(false);
273
274     pitch_trim = fgGetNode("/fdm/trim/pitch-trim", true );
275     throttle_trim = fgGetNode("/fdm/trim/throttle", true );
276     aileron_trim = fgGetNode("/fdm/trim/aileron", true );
277     rudder_trim = fgGetNode("/fdm/trim/rudder", true );
278
279     stall_warning = fgGetNode("/sim/alarms/stall-warning",true);
280     stall_warning->setDoubleValue(0);
281
282
283     flap_pos_pct=fgGetNode("/surface-positions/flap-pos-norm",true);
284     elevator_pos_pct=fgGetNode("/surface-positions/elevator-pos-norm",true);
285     left_aileron_pos_pct
286         =fgGetNode("/surface-positions/left-aileron-pos-norm",true);
287     right_aileron_pos_pct
288         =fgGetNode("/surface-positions/right-aileron-pos-norm",true);
289     rudder_pos_pct=fgGetNode("/surface-positions/rudder-pos-norm",true);
290     speedbrake_pos_pct
291         =fgGetNode("/surface-positions/speedbrake-pos-norm",true);
292     spoilers_pos_pct=fgGetNode("/surface-positions/spoilers-pos-norm",true);
293     tailhook_pos_pct=fgGetNode("/gear/tailhook/position-norm",true);
294     wing_fold_pos_pct=fgGetNode("surface-positions/wing-fold-pos-norm",true);
295
296     elevator_pos_pct->setDoubleValue(0);
297     left_aileron_pos_pct->setDoubleValue(0);
298     right_aileron_pos_pct->setDoubleValue(0);
299     rudder_pos_pct->setDoubleValue(0);
300     flap_pos_pct->setDoubleValue(0);
301     speedbrake_pos_pct->setDoubleValue(0);
302     spoilers_pos_pct->setDoubleValue(0);
303
304     ab_brake_engaged = fgGetNode("/autopilot/autobrake/engaged", true);
305     ab_brake_left_pct = fgGetNode("/autopilot/autobrake/brake-left-output", true);
306     ab_brake_right_pct = fgGetNode("/autopilot/autobrake/brake-right-output", true);
307     
308     temperature = fgGetNode("/environment/temperature-degc",true);
309     pressure = fgGetNode("/environment/pressure-inhg",true);
310     density = fgGetNode("/environment/density-slugft3",true);
311     ground_wind = fgGetNode("/environment/config/boundary/entry[0]/wind-speed-kt",true);
312     turbulence_gain = fgGetNode("/environment/turbulence/magnitude-norm",true);
313     turbulence_rate = fgGetNode("/environment/turbulence/rate-hz",true);
314     turbulence_model = fgGetNode("/environment/params/jsbsim-turbulence-model",true);
315
316     wind_from_north= fgGetNode("/environment/wind-from-north-fps",true);
317     wind_from_east = fgGetNode("/environment/wind-from-east-fps" ,true);
318     wind_from_down = fgGetNode("/environment/wind-from-down-fps" ,true);
319
320     slaved = fgGetNode("/sim/slaved/enabled", true);
321
322     for (unsigned int i = 0; i < Propulsion->GetNumEngines(); i++) {
323       SGPropertyNode * node = fgGetNode("engines/engine", i, true);
324       Propulsion->GetEngine(i)->GetThruster()->SetRPM(node->getDoubleValue("rpm") /
325                      Propulsion->GetEngine(i)->GetThruster()->GetGearRatio());
326     }
327
328     hook_root_struct = FGColumnVector3(
329         fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-offset-x-in", 196),
330         fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-offset-y-in", 0),
331         fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-offset-z-in", -16));
332     last_hook_tip[0] = 0; last_hook_tip[1] = 0; last_hook_tip[2] = 0;
333     last_hook_root[0] = 0; last_hook_root[1] = 0; last_hook_root[2] = 0;
334
335     crashed = false;
336 }
337
338 /******************************************************************************/
339 FGJSBsim::~FGJSBsim(void)
340 {
341   delete fdmex;
342 }
343
344 /******************************************************************************/
345
346 // Initialize the JSBsim flight model, dt is the time increment for
347 // each subsequent iteration through the EOM
348
349 void FGJSBsim::init()
350 {
351     SG_LOG( SG_FLIGHT, SG_INFO, "Starting and initializing JSBsim" );
352
353     // Explicitly call the superclass's
354     // init method first.
355
356     if (fgGetBool("/environment/params/control-fdm-atmosphere")) {
357       Atmosphere->UseExternal();
358       Atmosphere->SetExTemperature(
359                   9.0/5.0*(temperature->getDoubleValue()+273.15) );
360       Atmosphere->SetExPressure(pressure->getDoubleValue()*70.726566);
361       Atmosphere->SetExDensity(density->getDoubleValue());
362       // initialize to no turbulence, these values get set in the update loop
363       Atmosphere->SetTurbType(FGAtmosphere::ttNone);
364       Atmosphere->SetTurbGain(0.0);
365       Atmosphere->SetTurbRate(0.0);
366       Atmosphere->SetWindspeed20ft(0.0);
367       Atmosphere->SetProbabilityOfExceedence(0.0);
368     } else {
369       Atmosphere->UseInternal();
370     }
371
372     fgic->SetWindNEDFpsIC( -wind_from_north->getDoubleValue(),
373                            -wind_from_east->getDoubleValue(),
374                            -wind_from_down->getDoubleValue() );
375
376     //Atmosphere->SetExTemperature(get_Static_temperature());
377     //Atmosphere->SetExPressure(get_Static_pressure());
378     //Atmosphere->SetExDensity(get_Density());
379     SG_LOG(SG_FLIGHT,SG_INFO,"T,p,rho: " << fdmex->GetAtmosphere()->GetTemperature()
380      << ", " << fdmex->GetAtmosphere()->GetPressure()
381      << ", " << fdmex->GetAtmosphere()->GetDensity() );
382
383 // deprecate egt_degf for egt-degf to have consistent naming
384 // TODO: remove this by end of 2011
385     for (unsigned int i=0; i < Propulsion->GetNumEngines(); i++) {
386       SGPropertyNode * node = fgGetNode("engines/engine", i, true);
387       SGPropertyNode * egtn = node->getNode( "egt_degf" );
388       if( egtn != NULL ) {
389         SG_LOG(SG_FLIGHT,SG_ALERT,
390                "Aircraft uses deprecated node egt_degf. Please upgrade to egt-degf");
391         node->getNode("egt-degf", true)->alias( egtn );
392       }
393     }
394 // end of egt_degf deprecation patch
395
396     FCS->SetDfPos( ofNorm, globals->get_controls()->get_flaps() );
397
398     common_init();
399
400     copy_to_JSBsim();
401     fdmex->RunIC();     //loop JSBSim once w/o integrating
402     if (fgGetBool("/sim/presets/running")) {
403       Propulsion->InitRunning(-1);
404       for (unsigned int i = 0; i < Propulsion->GetNumEngines(); i++) {
405         FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
406         globals->get_controls()->set_magnetos(i, eng->GetMagnetos());
407         globals->get_controls()->set_mixture(i, FCS->GetMixtureCmd(i));
408       }
409     }
410     copy_from_JSBsim(); //update the bus
411
412     SG_LOG( SG_FLIGHT, SG_INFO, "  Initialized JSBSim with:" );
413
414     switch(fgic->GetSpeedSet()) {
415     case setned:
416         SG_LOG(SG_FLIGHT,SG_INFO, "  Vn,Ve,Vd= "
417                << Propagate->GetVel(FGJSBBase::eNorth) << ", "
418                << Propagate->GetVel(FGJSBBase::eEast) << ", "
419                << Propagate->GetVel(FGJSBBase::eDown) << " ft/s");
420     break;
421     case setuvw:
422         SG_LOG(SG_FLIGHT,SG_INFO, "  U,V,W= "
423                << Propagate->GetUVW(1) << ", "
424                << Propagate->GetUVW(2) << ", "
425                << Propagate->GetUVW(3) << " ft/s");
426     break;
427     case setmach:
428         SG_LOG(SG_FLIGHT,SG_INFO, "  Mach: "
429                << Auxiliary->GetMach() );
430     break;
431     case setvc:
432     default:
433         SG_LOG(SG_FLIGHT,SG_INFO, "  Indicated Airspeed: "
434                << Auxiliary->GetVcalibratedKTS() << " knots" );
435     break;
436     }
437
438     stall_warning->setDoubleValue(0);
439
440     SG_LOG( SG_FLIGHT, SG_INFO, "  Bank Angle: "
441             << Propagate->GetEuler(FGJSBBase::ePhi)*RADTODEG << " deg" );
442     SG_LOG( SG_FLIGHT, SG_INFO, "  Pitch Angle: "
443             << Propagate->GetEuler(FGJSBBase::eTht)*RADTODEG << " deg" );
444     SG_LOG( SG_FLIGHT, SG_INFO, "  True Heading: "
445             << Propagate->GetEuler(FGJSBBase::ePsi)*RADTODEG << " deg" );
446     SG_LOG( SG_FLIGHT, SG_INFO, "  Latitude: "
447             << Propagate->GetLocation().GetLatitudeDeg() << " deg" );
448     SG_LOG( SG_FLIGHT, SG_INFO, "  Longitude: "
449             << Propagate->GetLocation().GetLongitudeDeg() << " deg" );
450     SG_LOG( SG_FLIGHT, SG_INFO, "  Altitude: "
451             << Propagate->GetAltitudeASL() << " feet" );
452     SG_LOG( SG_FLIGHT, SG_INFO, "  loaded initial conditions" );
453
454     SG_LOG( SG_FLIGHT, SG_INFO, "  set dt" );
455
456     SG_LOG( SG_FLIGHT, SG_INFO, "Finished initializing JSBSim" );
457
458     SG_LOG( SG_FLIGHT, SG_INFO, "FGControls::get_gear_down()= " <<
459                                   globals->get_controls()->get_gear_down() );
460 }
461
462 /******************************************************************************/
463
464 void FGJSBsim::unbind()
465 {
466   fdmex->Unbind();
467   FGInterface::unbind();
468 }
469
470 /******************************************************************************/
471
472 // Run an iteration of the EOM (equations of motion)
473
474 void FGJSBsim::update( double dt )
475 {
476     if(crashed) {
477       if(!fgGetBool("/sim/crashed"))
478         fgSetBool("/sim/crashed", true);
479       return;
480     }
481
482     if (is_suspended())
483       return;
484
485     int multiloop = _calc_multiloop(dt);
486
487     int i;
488
489     // Compute the radius of the aircraft. That is the radius of a ball
490     // where all gear units are in. At the moment it is at least 10ft ...
491     double acrad = 10.0;
492     int n_gears = GroundReactions->GetNumGearUnits();
493     for (i=0; i<n_gears; ++i) {
494       FGColumnVector3 bl = GroundReactions->GetGearUnit(i)->GetBodyLocation();
495       double r = bl.Magnitude();
496       if (acrad < r)
497         acrad = r;
498     }
499
500     // Compute the potential movement of this aircraft and query for the
501     // ground in this area.
502     double groundCacheRadius = acrad + 2*dt*Propagate->GetUVW().Magnitude();
503     double alt, slr, lat, lon;
504     FGLocation cart = Auxiliary->GetLocationVRP();
505     if ( needTrim && startup_trim->getBoolValue() ) {
506       alt = fgic->GetAltitudeASLFtIC();
507       slr = fgic->GetSeaLevelRadiusFtIC();
508       lat = fgic->GetLatitudeDegIC() * SGD_DEGREES_TO_RADIANS;
509       lon = fgic->GetLongitudeDegIC() * SGD_DEGREES_TO_RADIANS;
510       cart = FGLocation(lon, lat, alt+slr);
511     }
512     double cart_pos[3] = { cart(1), cart(2), cart(3) };
513     double t0 = fdmex->GetSimTime();
514     bool cache_ok = prepare_ground_cache_ft( t0, t0 + dt, cart_pos,
515                                              groundCacheRadius );
516     if (!cache_ok) {
517       SG_LOG(SG_FLIGHT, SG_WARN,
518              "FGInterface is being called without scenery below the aircraft!");
519
520       alt = fgic->GetAltitudeASLFtIC();
521       SG_LOG(SG_FLIGHT, SG_WARN, "altitude         = " << alt);
522
523       slr = fgic->GetSeaLevelRadiusFtIC();
524       SG_LOG(SG_FLIGHT, SG_WARN, "sea level radius = " << slr);
525
526       lat = fgic->GetLatitudeDegIC() * SGD_DEGREES_TO_RADIANS;
527       SG_LOG(SG_FLIGHT, SG_WARN, "latitude         = " << lat);
528
529       lon = fgic->GetLongitudeDegIC() * SGD_DEGREES_TO_RADIANS;
530       SG_LOG(SG_FLIGHT, SG_WARN, "longitude        = " << lon);
531       //return;
532     }
533
534     copy_to_JSBsim();
535
536     trimmed->setBoolValue(false);
537
538     if ( needTrim ) {
539       if ( startup_trim->getBoolValue() ) {
540         double contact[3], d[3], vel[3], agl;
541         get_agl_ft(fdmex->GetSimTime(), cart_pos, SG_METER_TO_FEET*2, contact,
542                    d, vel, d, &agl);
543         double terrain_alt = sqrt(contact[0]*contact[0] + contact[1]*contact[1]
544              + contact[2]*contact[2]) - fgic->GetSeaLevelRadiusFtIC();
545
546         SG_LOG(SG_FLIGHT, SG_INFO,
547           "Ready to trim, terrain elevation is: "
548             << terrain_alt * SG_METER_TO_FEET );
549
550         if (fgGetBool("/sim/presets/onground")) {
551           FGColumnVector3 gndVelNED = cart.GetTec2l()
552                                     * FGColumnVector3(vel[0], vel[1], vel[2]);
553           fgic->SetVNorthFpsIC(gndVelNED(1));
554           fgic->SetVEastFpsIC(gndVelNED(2));
555           fgic->SetVDownFpsIC(gndVelNED(3));
556         }
557         fgic->SetTerrainElevationFtIC( terrain_alt );
558         do_trim();
559       } else {
560         fdmex->RunIC();  //apply any changes made through the set_ functions
561       }
562       needTrim = false;
563     }
564
565     for ( i=0; i < multiloop; i++ ) {
566       fdmex->Run();
567       update_external_forces(fdmex->GetSimTime() + i * fdmex->GetDeltaT());      
568     }
569
570     FGJSBBase::Message* msg;
571     while ((msg = fdmex->ProcessNextMessage()) != NULL) {
572 //      msg = fdmex->ProcessNextMessage();
573       switch (msg->type) {
574       case FGJSBBase::Message::eText:
575         if (msg->text == "Crash Detected: Simulation FREEZE.")
576           crashed = true;
577         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text );
578         break;
579       case FGJSBBase::Message::eBool:
580         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->bVal );
581         break;
582       case FGJSBBase::Message::eInteger:
583         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->iVal );
584         break;
585       case FGJSBBase::Message::eDouble:
586         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->dVal );
587         break;
588       default:
589         SG_LOG( SG_FLIGHT, SG_INFO, "Unrecognized message type." );
590         break;
591       }
592     }
593
594     // translate JSBsim back to FG structure so that the
595     // autopilot (and the rest of the sim can use the updated values
596     copy_from_JSBsim();
597 }
598
599 /******************************************************************************/
600
601 void FGJSBsim::suspend()
602 {
603   fdmex->Hold();
604   SGSubsystem::suspend();
605 }
606
607 /******************************************************************************/
608
609 void FGJSBsim::resume()
610 {
611   fdmex->Resume();
612   SGSubsystem::resume();
613 }
614
615 /******************************************************************************/
616
617 // Convert from the FGInterface struct to the JSBsim generic_ struct
618
619 bool FGJSBsim::copy_to_JSBsim()
620 {
621     unsigned int i;
622
623     // copy control positions into the JSBsim structure
624
625     FCS->SetDaCmd( globals->get_controls()->get_aileron());
626     FCS->SetRollTrimCmd( globals->get_controls()->get_aileron_trim() );
627     FCS->SetDeCmd( globals->get_controls()->get_elevator());
628     FCS->SetPitchTrimCmd( globals->get_controls()->get_elevator_trim() );
629     FCS->SetDrCmd( -globals->get_controls()->get_rudder() );
630     FCS->SetYawTrimCmd( -globals->get_controls()->get_rudder_trim() );
631     FCS->SetDsCmd( globals->get_controls()->get_rudder() );
632     FCS->SetDfCmd( globals->get_controls()->get_flaps() );
633     FCS->SetDsbCmd( globals->get_controls()->get_speedbrake() );
634     FCS->SetDspCmd( globals->get_controls()->get_spoilers() );
635
636         // Parking brake sets minimum braking
637         // level for mains.
638     double parking_brake = globals->get_controls()->get_brake_parking();
639     double left_brake = globals->get_controls()->get_brake_left();
640     double right_brake = globals->get_controls()->get_brake_right();
641     
642     if (ab_brake_engaged->getBoolValue()) {
643       left_brake = ab_brake_left_pct->getDoubleValue();
644       right_brake = ab_brake_right_pct->getDoubleValue(); 
645     }
646     
647     FCS->SetLBrake(FMAX(left_brake, parking_brake));
648     FCS->SetRBrake(FMAX(right_brake, parking_brake));
649     
650     
651     FCS->SetCBrake( 0.0 );
652     // FCS->SetCBrake( globals->get_controls()->get_brake(2) );
653
654     FCS->SetGearCmd( globals->get_controls()->get_gear_down());
655     for (i = 0; i < Propulsion->GetNumEngines(); i++) {
656       SGPropertyNode * node = fgGetNode("engines/engine", i, true);
657
658       FCS->SetThrottleCmd(i, globals->get_controls()->get_throttle(i));
659       FCS->SetMixtureCmd(i, globals->get_controls()->get_mixture(i));
660       FCS->SetPropAdvanceCmd(i, globals->get_controls()->get_prop_advance(i));
661       FCS->SetFeatherCmd(i, globals->get_controls()->get_feather(i));
662
663       switch (Propulsion->GetEngine(i)->GetType()) {
664       case FGEngine::etPiston:
665         { // FGPiston code block
666         FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
667         eng->SetMagnetos( globals->get_controls()->get_magnetos(i) );
668         break;
669         } // end FGPiston code block
670       case FGEngine::etTurbine:
671         { // FGTurbine code block
672         FGTurbine* eng = (FGTurbine*)Propulsion->GetEngine(i);
673         eng->SetAugmentation( globals->get_controls()->get_augmentation(i) );
674         eng->SetReverse( globals->get_controls()->get_reverser(i) );
675         //eng->SetInjection( globals->get_controls()->get_water_injection(i) );
676         eng->SetCutoff( globals->get_controls()->get_cutoff(i) );
677         eng->SetIgnition( globals->get_controls()->get_ignition(i) );
678         break;
679         } // end FGTurbine code block
680       case FGEngine::etRocket:
681         { // FGRocket code block
682 //        FGRocket* eng = (FGRocket*)Propulsion->GetEngine(i);
683         break;
684         } // end FGRocket code block
685       case FGEngine::etTurboprop:
686         { // FGTurboProp code block
687         FGTurboProp* eng = (FGTurboProp*)Propulsion->GetEngine(i);
688         eng->SetReverse( globals->get_controls()->get_reverser(i) );
689         eng->SetCutoff( globals->get_controls()->get_cutoff(i) );
690         eng->SetIgnition( globals->get_controls()->get_ignition(i) );
691
692         eng->SetGeneratorPower( globals->get_controls()->get_generator_breaker(i) );
693         eng->SetCondition( globals->get_controls()->get_condition(i) );
694         break;
695         } // end FGTurboProp code block
696       default:
697         break;
698       }
699
700       { // FGEngine code block
701       FGEngine* eng = Propulsion->GetEngine(i);
702
703       eng->SetStarter( globals->get_controls()->get_starter(i) );
704       eng->SetRunning( node->getBoolValue("running") );
705       } // end FGEngine code block
706     }
707
708
709     Propagate->SetSeaLevelRadius( get_Sea_level_radius() );
710
711     Atmosphere->SetExTemperature(
712                   9.0/5.0*(temperature->getDoubleValue()+273.15) );
713     Atmosphere->SetExPressure(pressure->getDoubleValue()*70.726566);
714     Atmosphere->SetExDensity(density->getDoubleValue());
715
716     Atmosphere->SetTurbType((FGAtmosphere::tType)TURBULENCE_TYPE_NAMES[turbulence_model->getStringValue()]);
717     switch( Atmosphere->GetTurbType() ) {
718         case FGAtmosphere::ttStandard:
719         case FGAtmosphere::ttCulp:
720         case FGAtmosphere::ttBerndt: {
721             double tmp = turbulence_gain->getDoubleValue();
722             Atmosphere->SetTurbGain(tmp * tmp * 100.0);
723             Atmosphere->SetTurbRate(turbulence_rate->getDoubleValue());
724             break;
725         }
726         case FGAtmosphere::ttMilspec:
727         case FGAtmosphere::ttTustin: {
728             // milspec turbulence: 3=light, 4=moderate, 6=severe turbulence
729             // turbulence_gain normalized: 0: none, 1/3: light, 2/3: moderate, 3/3: severe
730             double tmp = turbulence_gain->getDoubleValue();
731             Atmosphere->SetProbabilityOfExceedence(
732               SGMiscd::roundToInt(TurbulenceSeverityTable.GetValue( tmp ) )
733             );
734             Atmosphere->SetWindspeed20ft(ground_wind->getDoubleValue());
735             break;
736         }
737
738         default:
739             break;
740     }
741
742     Atmosphere->SetWindNED( -wind_from_north->getDoubleValue(),
743                             -wind_from_east->getDoubleValue(),
744                             -wind_from_down->getDoubleValue() );
745 //    SG_LOG(SG_FLIGHT,SG_INFO, "Wind NED: "
746 //                  << get_V_north_airmass() << ", "
747 //                  << get_V_east_airmass()  << ", "
748 //                  << get_V_down_airmass() );
749
750     for (i = 0; i < Propulsion->GetNumTanks(); i++) {
751       SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
752       FGTank * tank = Propulsion->GetTank(i);
753       double fuelDensity = node->getDoubleValue("density-ppg");
754
755       if (fuelDensity < 0.1)
756         fuelDensity = 6.0; // Use average fuel value
757
758       tank->SetDensity(fuelDensity);
759       tank->SetContents(node->getDoubleValue("level-lbs"));
760     }
761
762     Propulsion->SetFuelFreeze((fgGetNode("/sim/freeze/fuel",true))->getBoolValue());
763     fdmex->SetChild(slaved->getBoolValue());
764
765     return true;
766 }
767
768 /******************************************************************************/
769
770 // Convert from the JSBsim generic_ struct to the FGInterface struct
771
772 bool FGJSBsim::copy_from_JSBsim()
773 {
774     unsigned int i, j;
775 /*
776     _set_Inertias( MassBalance->GetMass(),
777                    MassBalance->GetIxx(),
778                    MassBalance->GetIyy(),
779                    MassBalance->GetIzz(),
780                    MassBalance->GetIxz() );
781 */
782     _set_CG_Position( MassBalance->GetXYZcg(1),
783                       MassBalance->GetXYZcg(2),
784                       MassBalance->GetXYZcg(3) );
785
786     _set_Accels_Body( Aircraft->GetBodyAccel(1),
787                       Aircraft->GetBodyAccel(2),
788                       Aircraft->GetBodyAccel(3) );
789
790     _set_Accels_CG_Body_N ( Aircraft->GetNcg(1),
791                             Aircraft->GetNcg(2),
792                             Aircraft->GetNcg(3) );
793
794     _set_Accels_Pilot_Body( Auxiliary->GetPilotAccel(1),
795                             Auxiliary->GetPilotAccel(2),
796                             Auxiliary->GetPilotAccel(3) );
797
798     _set_Nlf( Aircraft->GetNlf() );
799
800     // Velocities
801
802     _set_Velocities_Local( Propagate->GetVel(FGJSBBase::eNorth),
803                            Propagate->GetVel(FGJSBBase::eEast),
804                            Propagate->GetVel(FGJSBBase::eDown) );
805
806     _set_Velocities_Wind_Body( Propagate->GetUVW(1),
807                                Propagate->GetUVW(2),
808                                Propagate->GetUVW(3) );
809
810     // Make the HUD work ...
811     _set_Velocities_Ground( Propagate->GetVel(FGJSBBase::eNorth),
812                             Propagate->GetVel(FGJSBBase::eEast),
813                             -Propagate->GetVel(FGJSBBase::eDown) );
814
815     _set_V_rel_wind( Auxiliary->GetVt() );
816
817     _set_V_equiv_kts( Auxiliary->GetVequivalentKTS() );
818
819     _set_V_calibrated_kts( Auxiliary->GetVcalibratedKTS() );
820
821     _set_V_ground_speed( Auxiliary->GetVground() );
822
823     _set_Omega_Body( Propagate->GetPQR(FGJSBBase::eP),
824                      Propagate->GetPQR(FGJSBBase::eQ),
825                      Propagate->GetPQR(FGJSBBase::eR) );
826
827     _set_Euler_Rates( Auxiliary->GetEulerRates(FGJSBBase::ePhi),
828                       Auxiliary->GetEulerRates(FGJSBBase::eTht),
829                       Auxiliary->GetEulerRates(FGJSBBase::ePsi) );
830
831     _set_Mach_number( Auxiliary->GetMach() );
832
833     // Positions of Visual Reference Point
834     FGLocation l = Auxiliary->GetLocationVRP();
835     _updateGeocentricPosition( l.GetLatitude(), l.GetLongitude(),
836                                l.GetRadius() - get_Sea_level_radius() );
837
838     _set_Altitude_AGL( Propagate->GetDistanceAGL() );
839     {
840       double loc_cart[3] = { l(FGJSBBase::eX), l(FGJSBBase::eY), l(FGJSBBase::eZ) };
841       double contact[3], d[3], sd, t;
842       is_valid_m(&t, d, &sd);
843       get_agl_ft(t, loc_cart, SG_METER_TO_FEET*2, contact, d, d, d, &sd);
844       double rwrad
845         = FGColumnVector3( contact[0], contact[1], contact[2] ).Magnitude();
846       _set_Runway_altitude( rwrad - get_Sea_level_radius() );
847     }
848
849     _set_Euler_Angles( Propagate->GetEuler(FGJSBBase::ePhi),
850                        Propagate->GetEuler(FGJSBBase::eTht),
851                        Propagate->GetEuler(FGJSBBase::ePsi) );
852
853     _set_Alpha( Auxiliary->Getalpha() );
854     _set_Beta( Auxiliary->Getbeta() );
855
856
857     _set_Gamma_vert_rad( Auxiliary->GetGamma() );
858
859     _set_Earth_position_angle( Inertial->GetEarthPositionAngle() );
860
861     _set_Climb_Rate( Propagate->Gethdot() );
862
863     const FGMatrix33& Tl2b = Propagate->GetTl2b();
864     for ( i = 1; i <= 3; i++ ) {
865         for ( j = 1; j <= 3; j++ ) {
866             _set_T_Local_to_Body( i, j, Tl2b(i,j) );
867         }
868     }
869
870     // Copy the engine values from JSBSim.
871     for ( i=0; i < Propulsion->GetNumEngines(); i++ ) {
872       SGPropertyNode * node = fgGetNode("engines/engine", i, true);
873       SGPropertyNode * tnode = node->getChild("thruster", 0, true);
874       FGThruster * thruster = Propulsion->GetEngine(i)->GetThruster();
875
876       switch (Propulsion->GetEngine(i)->GetType()) {
877       case FGEngine::etPiston:
878         { // FGPiston code block
879         FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
880         node->setDoubleValue("egt-degf", eng->getExhaustGasTemp_degF());
881         node->setDoubleValue("oil-temperature-degf", eng->getOilTemp_degF());
882         node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
883         node->setDoubleValue("mp-osi", eng->getManifoldPressure_inHg());
884         // NOTE: mp-osi is not in ounces per square inch.
885         // This error is left for reasons of backwards compatibility with
886         // existing FlightGear sound and instrument configurations.
887         node->setDoubleValue("mp-inhg", eng->getManifoldPressure_inHg());
888         node->setDoubleValue("cht-degf", eng->getCylinderHeadTemp_degF());
889         node->setDoubleValue("rpm", eng->getRPM());
890         } // end FGPiston code block
891         break;
892       case FGEngine::etRocket:
893         { // FGRocket code block
894 //        FGRocket* eng = (FGRocket*)Propulsion->GetEngine(i);
895         } // end FGRocket code block
896         break;
897       case FGEngine::etTurbine:
898         { // FGTurbine code block
899         FGTurbine* eng = (FGTurbine*)Propulsion->GetEngine(i);
900         node->setDoubleValue("n1", eng->GetN1());
901         node->setDoubleValue("n2", eng->GetN2());
902         node->setDoubleValue("egt-degf", 32 + eng->GetEGT()*9/5);
903         node->setBoolValue("augmentation", eng->GetAugmentation());
904         node->setBoolValue("water-injection", eng->GetInjection());
905         node->setBoolValue("ignition", eng->GetIgnition() != 0);
906         node->setDoubleValue("nozzle-pos-norm", eng->GetNozzle());
907         node->setDoubleValue("inlet-pos-norm", eng->GetInlet());
908         node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
909         node->setBoolValue("reversed", eng->GetReversed());
910         node->setBoolValue("cutoff", eng->GetCutoff());
911         node->setDoubleValue("epr", eng->GetEPR());
912         globals->get_controls()->set_reverser(i, eng->GetReversed() );
913         globals->get_controls()->set_cutoff(i, eng->GetCutoff() );
914         globals->get_controls()->set_water_injection(i, eng->GetInjection() );
915         globals->get_controls()->set_augmentation(i, eng->GetAugmentation() );
916         } // end FGTurbine code block
917         break;
918       case FGEngine::etTurboprop:
919         { // FGTurboProp code block
920         FGTurboProp* eng = (FGTurboProp*)Propulsion->GetEngine(i);
921         node->setDoubleValue("n1", eng->GetN1());
922         //node->setDoubleValue("n2", eng->GetN2());
923         node->setDoubleValue("itt_degf", 32 + eng->GetITT()*9/5);
924         node->setBoolValue("ignition", eng->GetIgnition() != 0);
925         node->setDoubleValue("nozzle-pos-norm", eng->GetNozzle());
926         node->setDoubleValue("inlet-pos-norm", eng->GetInlet());
927         node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
928         node->setBoolValue("reversed", eng->GetReversed());
929         node->setBoolValue("cutoff", eng->GetCutoff());
930         node->setBoolValue("starting", eng->GetEngStarting());
931         node->setBoolValue("generator-power", eng->GetGeneratorPower());
932         node->setBoolValue("damaged", eng->GetCondition() != 0);
933         node->setBoolValue("ielu-intervent", eng->GetIeluIntervent());
934         node->setDoubleValue("oil-temperature-degf", eng->getOilTemp_degF());
935 //        node->setBoolValue("onfire", eng->GetFire());
936         globals->get_controls()->set_reverser(i, eng->GetReversed() );
937         globals->get_controls()->set_cutoff(i, eng->GetCutoff() );
938         } // end FGTurboProp code block
939         break;
940       case FGEngine::etElectric:
941         { // FGElectric code block
942         FGElectric* eng = (FGElectric*)Propulsion->GetEngine(i);
943         node->setDoubleValue("rpm", eng->getRPM());
944         } // end FGElectric code block
945         break;
946       case FGEngine::etUnknown:
947         break;
948       }
949
950       { // FGEngine code block
951       FGEngine* eng = Propulsion->GetEngine(i);
952       node->setDoubleValue("fuel-flow-gph", eng->getFuelFlow_gph());
953       node->setDoubleValue("thrust_lb", thruster->GetThrust());
954       node->setDoubleValue("fuel-flow_pph", eng->getFuelFlow_pph());
955       node->setBoolValue("running", eng->GetRunning());
956       node->setBoolValue("starter", eng->GetStarter());
957       node->setBoolValue("cranking", eng->GetCranking());
958       globals->get_controls()->set_starter(i, eng->GetStarter() );
959       } // end FGEngine code block
960
961       switch (thruster->GetType()) {
962       case FGThruster::ttNozzle:
963         { // FGNozzle code block
964 //        FGNozzle* noz = (FGNozzle*)thruster;
965         } // end FGNozzle code block
966         break;
967       case FGThruster::ttPropeller:
968         { // FGPropeller code block
969         FGPropeller* prop = (FGPropeller*)thruster;
970         tnode->setDoubleValue("rpm", thruster->GetRPM());
971         tnode->setDoubleValue("pitch", prop->GetPitch());
972         tnode->setDoubleValue("torque", prop->GetTorque());
973         tnode->setBoolValue("feathered", prop->GetFeather());
974         } // end FGPropeller code block
975         break;
976       case FGThruster::ttRotor:
977         { // FGRotor code block
978 //        FGRotor* rotor = (FGRotor*)thruster;
979         } // end FGRotor code block
980         break;
981       case FGThruster::ttDirect:
982         { // Direct code block
983         } // end Direct code block
984         break;
985       }
986
987     }
988
989     // Copy the fuel levels from JSBSim if fuel
990     // freeze not enabled.
991     if ( ! Propulsion->GetFuelFreeze() ) {
992       for (i = 0; i < Propulsion->GetNumTanks(); i++) {
993         SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
994         FGTank* tank = Propulsion->GetTank(i);
995         double contents = tank->GetContents();
996         double temp = tank->GetTemperature_degC();
997         double fuelDensity = tank->GetDensity();
998
999         if (fuelDensity < 0.1)
1000           fuelDensity = 6.0; // Use average fuel value
1001
1002         node->setDoubleValue("density-ppg" , fuelDensity);
1003         node->setDoubleValue("level-lbs", contents);
1004         if (temp != -9999.0) node->setDoubleValue("temperature_degC", temp);
1005       }
1006     }
1007
1008     update_gear();
1009
1010     stall_warning->setDoubleValue( Aerodynamics->GetStallWarn() );
1011
1012     elevator_pos_pct->setDoubleValue( FCS->GetDePos(ofNorm) );
1013     left_aileron_pos_pct->setDoubleValue( FCS->GetDaLPos(ofNorm) );
1014     right_aileron_pos_pct->setDoubleValue( FCS->GetDaRPos(ofNorm) );
1015     rudder_pos_pct->setDoubleValue( -1*FCS->GetDrPos(ofNorm) );
1016     flap_pos_pct->setDoubleValue( FCS->GetDfPos(ofNorm) );
1017     speedbrake_pos_pct->setDoubleValue( FCS->GetDsbPos(ofNorm) );
1018     spoilers_pos_pct->setDoubleValue( FCS->GetDspPos(ofNorm) );
1019     tailhook_pos_pct->setDoubleValue( FCS->GetTailhookPos() );
1020     wing_fold_pos_pct->setDoubleValue( FCS->GetWingFoldPos() );
1021
1022     // force a sim crashed if crashed (altitude AGL < 0)
1023     if (get_Altitude_AGL() < -100.0) {
1024          fdmex->SuspendIntegration();
1025          crashed = true;
1026     }
1027
1028     return true;
1029 }
1030
1031
1032 bool FGJSBsim::ToggleDataLogging(void)
1033 {
1034   // ToDo: handle this properly
1035   fdmex->DisableOutput();
1036   return false;
1037 }
1038
1039
1040 bool FGJSBsim::ToggleDataLogging(bool state)
1041 {
1042     if (state) {
1043       fdmex->EnableOutput();
1044       return true;
1045     } else {
1046       fdmex->DisableOutput();
1047       return false;
1048     }
1049 }
1050
1051
1052 //Positions
1053 void FGJSBsim::set_Latitude(double lat)
1054 {
1055     static SGConstPropertyNode_ptr altitude = fgGetNode("/position/altitude-ft");
1056     double alt;
1057     double sea_level_radius_meters, lat_geoc;
1058
1059     // In case we're not trimming
1060     FGInterface::set_Latitude(lat);
1061
1062     if ( altitude->getDoubleValue() > -9990 ) {
1063       alt = altitude->getDoubleValue();
1064     } else {
1065       alt = 0.0;
1066     }
1067
1068     update_ic();
1069     SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Latitude: " << lat );
1070     SG_LOG(SG_FLIGHT,SG_INFO," cur alt (ft) =  " << alt );
1071
1072     sgGeodToGeoc( lat, alt * SG_FEET_TO_METER,
1073                       &sea_level_radius_meters, &lat_geoc );
1074     _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET  );
1075     fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET  );
1076     fgic->SetLatitudeRadIC( lat_geoc );
1077
1078     if (!fdmex->Holding())
1079       needTrim=true;
1080 }
1081
1082
1083 void FGJSBsim::set_Longitude(double lon)
1084 {
1085     SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Longitude: " << lon );
1086
1087     // In case we're not trimming
1088     FGInterface::set_Longitude(lon);
1089
1090     update_ic();
1091     fgic->SetLongitudeRadIC( lon );
1092
1093     if (!fdmex->Holding())
1094       needTrim=true;
1095 }
1096
1097 // Sets the altitude above sea level.
1098 void FGJSBsim::set_Altitude(double alt)
1099 {
1100     static SGConstPropertyNode_ptr latitude = fgGetNode("/position/latitude-deg");
1101
1102     double sea_level_radius_meters,lat_geoc;
1103
1104     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Altitude: " << alt );
1105     SG_LOG(SG_FLIGHT,SG_INFO, "  lat (deg) = " << latitude->getDoubleValue() );
1106
1107     // In case we're not trimming
1108     FGInterface::set_Altitude(alt);
1109
1110     update_ic();
1111     sgGeodToGeoc( latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS, alt,
1112                   &sea_level_radius_meters, &lat_geoc);
1113     _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET  );
1114     fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET );
1115     SG_LOG(SG_FLIGHT, SG_INFO,
1116           "Terrain elevation: " << FGInterface::get_Runway_altitude() * SG_METER_TO_FEET );
1117     fgic->SetLatitudeRadIC( lat_geoc );
1118     fgic->SetAltitudeASLFtIC(alt);
1119
1120     if (!fdmex->Holding())
1121       needTrim=true;
1122 }
1123
1124 void FGJSBsim::set_V_calibrated_kts(double vc)
1125 {
1126     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_V_calibrated_kts: " <<  vc );
1127
1128     // In case we're not trimming
1129     FGInterface::set_V_calibrated_kts(vc);
1130
1131     update_ic();
1132     fgic->SetVcalibratedKtsIC(vc);
1133
1134     if (!fdmex->Holding())
1135       needTrim=true;
1136 }
1137
1138 void FGJSBsim::set_Mach_number(double mach)
1139 {
1140     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Mach_number: " <<  mach );
1141
1142     // In case we're not trimming
1143     FGInterface::set_Mach_number(mach);
1144
1145     update_ic();
1146     fgic->SetMachIC(mach);
1147
1148     if (!fdmex->Holding())
1149       needTrim=true;
1150 }
1151
1152 void FGJSBsim::set_Velocities_Local( double north, double east, double down )
1153 {
1154     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Local: "
1155        << north << ", " <<  east << ", " << down );
1156
1157     // In case we're not trimming
1158     FGInterface::set_Velocities_Local(north, east, down);
1159
1160     update_ic();
1161     fgic->SetVNorthFpsIC(north);
1162     fgic->SetVEastFpsIC(east);
1163     fgic->SetVDownFpsIC(down);
1164
1165     if (!fdmex->Holding())
1166       needTrim=true;
1167 }
1168
1169 void FGJSBsim::set_Velocities_Wind_Body( double u, double v, double w)
1170 {
1171     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Wind_Body: "
1172        << u << ", " <<  v << ", " <<  w );
1173
1174     // In case we're not trimming
1175     FGInterface::set_Velocities_Wind_Body(u, v, w);
1176
1177     update_ic();
1178     fgic->SetUBodyFpsIC(u);
1179     fgic->SetVBodyFpsIC(v);
1180     fgic->SetWBodyFpsIC(w);
1181
1182     if (!fdmex->Holding())
1183       needTrim=true;
1184 }
1185
1186 //Euler angles
1187 void FGJSBsim::set_Euler_Angles( double phi, double theta, double psi )
1188 {
1189     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Euler_Angles: "
1190        << phi << ", " << theta << ", " << psi );
1191
1192     // In case we're not trimming
1193     FGInterface::set_Euler_Angles(phi, theta, psi);
1194
1195     update_ic();
1196     fgic->SetThetaRadIC(theta);
1197     fgic->SetPhiRadIC(phi);
1198     fgic->SetPsiRadIC(psi);
1199
1200     if (!fdmex->Holding())
1201       needTrim=true;
1202 }
1203
1204 //Flight Path
1205 void FGJSBsim::set_Climb_Rate( double roc)
1206 {
1207     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Climb_Rate: " << roc );
1208
1209     // In case we're not trimming
1210     FGInterface::set_Climb_Rate(roc);
1211
1212     update_ic();
1213     //since both climb rate and flight path angle are set in the FG
1214     //startup sequence, something is needed to keep one from cancelling
1215     //out the other.
1216     if( !(fabs(roc) > 1 && fabs(fgic->GetFlightPathAngleRadIC()) < 0.01) ) {
1217       fgic->SetClimbRateFpsIC(roc);
1218     }
1219
1220     if (!fdmex->Holding())
1221       needTrim=true;
1222 }
1223
1224 void FGJSBsim::set_Gamma_vert_rad( double gamma)
1225 {
1226     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Gamma_vert_rad: " << gamma );
1227
1228     update_ic();
1229     if( !(fabs(gamma) < 0.01 && fabs(fgic->GetClimbRateFpsIC()) > 1) ) {
1230       fgic->SetFlightPathAngleRadIC(gamma);
1231     }
1232
1233     if (!fdmex->Holding())
1234       needTrim=true;
1235 }
1236
1237 void FGJSBsim::init_gear(void )
1238 {
1239     FGGroundReactions* gr=fdmex->GetGroundReactions();
1240     int Ngear=GroundReactions->GetNumGearUnits();
1241     for (int i=0;i<Ngear;i++) {
1242       FGLGear *gear = gr->GetGearUnit(i);
1243       SGPropertyNode * node = fgGetNode("gear/gear", i, true);
1244       node->setDoubleValue("xoffset-in", gear->GetBodyLocation()(1));
1245       node->setDoubleValue("yoffset-in", gear->GetBodyLocation()(2));
1246       node->setDoubleValue("zoffset-in", gear->GetBodyLocation()(3));
1247       node->setBoolValue("wow", gear->GetWOW());
1248       node->setDoubleValue("rollspeed-ms", gear->GetWheelRollVel()*0.3043);
1249       node->setBoolValue("has-brake", gear->GetBrakeGroup() > 0);
1250       node->setDoubleValue("position-norm", gear->GetGearUnitPos());
1251       node->setDoubleValue("tire-pressure-norm", gear->GetTirePressure());
1252       node->setDoubleValue("compression-norm", gear->GetCompLen());
1253       node->setDoubleValue("compression-ft", gear->GetCompLen());
1254       if ( gear->GetSteerable() )
1255         node->setDoubleValue("steering-norm", gear->GetSteerNorm());
1256     }
1257 }
1258
1259 void FGJSBsim::update_gear(void)
1260 {
1261     FGGroundReactions* gr=fdmex->GetGroundReactions();
1262     int Ngear=GroundReactions->GetNumGearUnits();
1263     for (int i=0;i<Ngear;i++) {
1264       FGLGear *gear = gr->GetGearUnit(i);
1265       SGPropertyNode * node = fgGetNode("gear/gear", i, true);
1266       node->getChild("wow", 0, true)->setBoolValue( gear->GetWOW());
1267       node->getChild("rollspeed-ms", 0, true)->setDoubleValue(gear->GetWheelRollVel()*0.3043);
1268       node->getChild("position-norm", 0, true)->setDoubleValue(gear->GetGearUnitPos());
1269       gear->SetTirePressure(node->getDoubleValue("tire-pressure-norm"));
1270       node->setDoubleValue("compression-norm", gear->GetCompLen());
1271       node->setDoubleValue("compression-ft", gear->GetCompLen());
1272       if ( gear->GetSteerable() )
1273         node->setDoubleValue("steering-norm", gear->GetSteerNorm());
1274     }
1275 }
1276
1277 void FGJSBsim::do_trim(void)
1278 {
1279   FGTrim *fgtrim;
1280
1281   if ( fgGetBool("/sim/presets/onground") )
1282   {
1283     fgtrim = new FGTrim(fdmex,tGround);
1284   } else {
1285     fgtrim = new FGTrim(fdmex,tFull);
1286   }
1287
1288   if ( !fgtrim->DoTrim() ) {
1289     fgtrim->Report();
1290     fgtrim->TrimStats();
1291   } else {
1292     trimmed->setBoolValue(true);
1293   }
1294   delete fgtrim;
1295
1296   pitch_trim->setDoubleValue( FCS->GetPitchTrimCmd() );
1297   throttle_trim->setDoubleValue( FCS->GetThrottleCmd(0) );
1298   aileron_trim->setDoubleValue( FCS->GetDaCmd() );
1299   rudder_trim->setDoubleValue( -FCS->GetDrCmd() );
1300
1301   globals->get_controls()->set_elevator_trim(FCS->GetPitchTrimCmd());
1302   globals->get_controls()->set_elevator(FCS->GetDeCmd());
1303   for( unsigned i = 0; i < Propulsion->GetNumEngines(); i++ )
1304     globals->get_controls()->set_throttle(i, FCS->GetThrottleCmd(i));
1305
1306   globals->get_controls()->set_aileron(FCS->GetDaCmd());
1307   globals->get_controls()->set_rudder( -FCS->GetDrCmd());
1308
1309   SG_LOG( SG_FLIGHT, SG_INFO, "  Trim complete" );
1310 }
1311
1312 void FGJSBsim::update_ic(void)
1313 {
1314    if ( !needTrim ) {
1315      fgic->SetLatitudeRadIC(get_Lat_geocentric() );
1316      fgic->SetLongitudeRadIC( get_Longitude() );
1317      fgic->SetAltitudeASLFtIC( get_Altitude() );
1318      fgic->SetVcalibratedKtsIC( get_V_calibrated_kts() );
1319      fgic->SetThetaRadIC( get_Theta() );
1320      fgic->SetPhiRadIC( get_Phi() );
1321      fgic->SetPsiRadIC( get_Psi() );
1322      fgic->SetClimbRateFpsIC( get_Climb_Rate() );
1323    }
1324 }
1325
1326 bool
1327 FGJSBsim::get_agl_ft(double t, const double pt[3], double alt_off,
1328                      double contact[3], double normal[3], double vel[3],
1329                      double angularVel[3], double *agl)
1330 {
1331    const SGMaterial* material;
1332    simgear::BVHNode::Id id;
1333    if (!FGInterface::get_agl_ft(t, pt, alt_off, contact, normal, vel,
1334                                 angularVel, material, id))
1335        return false;
1336    SGGeod geodPt = SGGeod::fromCart(SG_FEET_TO_METER*SGVec3d(pt));
1337    SGQuatd hlToEc = SGQuatd::fromLonLat(geodPt);
1338    *agl = dot(hlToEc.rotate(SGVec3d(0, 0, 1)), SGVec3d(contact) - SGVec3d(pt));
1339    return true;
1340 }
1341
1342 inline static double dot3(const FGColumnVector3& a, const FGColumnVector3& b)
1343 {
1344     return a(1) * b(1) + a(2) * b(2) + a(3) * b(3);
1345 }
1346
1347 inline static double sqr(double x)
1348 {
1349     return x * x;
1350 }
1351
1352 static double angle_diff(double a, double b)
1353 {
1354     double diff = fabs(a - b);
1355     if (diff > 180) diff = 360 - diff;
1356     
1357     return diff;
1358 }
1359
1360 static void check_hook_solution(const FGColumnVector3& ground_normal_body, double E, double hook_length, double sin_fi_guess, double cos_fi_guess, double* sin_fis, double* cos_fis, double* fis, int* points)
1361 {
1362     FGColumnVector3 tip(-hook_length * cos_fi_guess, 0, hook_length * sin_fi_guess);
1363     double dist = dot3(tip, ground_normal_body);
1364     if (fabs(dist + E) < 0.0001) {
1365         sin_fis[*points] = sin_fi_guess;
1366         cos_fis[*points] = cos_fi_guess;
1367         fis[*points] = atan2(sin_fi_guess, cos_fi_guess) * SG_RADIANS_TO_DEGREES;
1368         (*points)++;
1369     } 
1370 }
1371
1372
1373 static void check_hook_solution(const FGColumnVector3& ground_normal_body, double E, double hook_length, double sin_fi_guess, double* sin_fis, double* cos_fis, double* fis, int* points)
1374 {
1375     if (sin_fi_guess >= -1 && sin_fi_guess <= 1) {
1376         double cos_fi_guess = sqrt(1 - sqr(sin_fi_guess));
1377         check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, cos_fi_guess, sin_fis, cos_fis, fis, points);
1378         if (fabs(cos_fi_guess) > SG_EPSILON) {
1379             check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, -cos_fi_guess, sin_fis, cos_fis, fis, points);
1380         }
1381     }
1382 }
1383
1384 void FGJSBsim::update_external_forces(double t_off)
1385 {
1386     const FGMatrix33& Tb2l = Propagate->GetTb2l();
1387     const FGMatrix33& Tl2b = Propagate->GetTl2b();
1388     const FGLocation& Location = Propagate->GetLocation();
1389     const FGMatrix33& Tec2l = Location.GetTec2l();
1390         
1391     double hook_area[4][3];
1392     
1393     FGColumnVector3 hook_root_body = MassBalance->StructuralToBody(hook_root_struct);
1394     FGColumnVector3 hook_root = Location.LocalToLocation(Tb2l *   hook_root_body);
1395     hook_area[1][0] = hook_root(1);
1396     hook_area[1][1] = hook_root(2);
1397     hook_area[1][2] = hook_root(3);
1398     
1399     hook_length = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-length-ft", 6.75);
1400     double fi_min = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-min-deg", -18);
1401     double fi_max = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-max-deg", 30);
1402     double fi = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-norm") * (fi_max - fi_min) + fi_min;
1403     double cos_fi = cos(fi * SG_DEGREES_TO_RADIANS);
1404     double sin_fi = sin(fi * SG_DEGREES_TO_RADIANS);
1405
1406     FGColumnVector3 hook_tip_body = hook_root_body;
1407     hook_tip_body(1) -= hook_length * cos_fi;
1408     hook_tip_body(3) += hook_length * sin_fi;    
1409     
1410     double contact[3];
1411     double ground_normal[3];
1412     double ground_vel[3];
1413     double ground_angular_vel[3];
1414     double root_agl_ft;
1415
1416     if (!got_wire) {
1417         bool got = get_agl_ft(t_off, hook_area[1], 0, contact, ground_normal,
1418                               ground_vel, ground_angular_vel, &root_agl_ft);
1419         if (got && root_agl_ft > 0 && root_agl_ft < hook_length) {
1420             FGColumnVector3 ground_normal_body = Tl2b * (Tec2l * FGColumnVector3(ground_normal[0], ground_normal[1], ground_normal[2]));
1421             FGColumnVector3 contact_body = Tl2b * Location.LocationToLocal(FGColumnVector3(contact[0], contact[1], contact[2]));
1422             double D = -dot3(contact_body, ground_normal_body);
1423
1424             // check hook tip agl against same ground plane
1425             double hook_tip_agl_ft = dot3(hook_tip_body, ground_normal_body) + D;
1426             if (hook_tip_agl_ft < 0) {
1427
1428                 // hook tip: hx - l cos, hy, hz + l sin
1429                 // on ground:  - n0 l cos + n2 l sin + E = 0
1430
1431                 double E = D + dot3(hook_root_body, ground_normal_body);
1432
1433                 // substitue x = sin fi, cos fi = sqrt(1 - x * x)
1434                 // and rearrange to get a quadratic with coeffs:
1435                 double a = sqr(hook_length) * (sqr(ground_normal_body(1)) + sqr(ground_normal_body(3)));
1436                 double b = 2 * E * ground_normal_body(3) * hook_length;
1437                 double c = sqr(E) - sqr(ground_normal_body(1) * hook_length);   
1438
1439                 double disc = sqr(b) - 4 * a * c;
1440                 if (disc >= 0) {
1441                     double delta = sqrt(disc) / (2 * a);
1442                 
1443                     // allow 4 solutions for safety, should never happen
1444                     double sin_fis[4];
1445                     double cos_fis[4];
1446                     double fis[4];
1447                     int points = 0;
1448                 
1449                     double sin_fi_guess = -b / (2 * a) - delta;
1450                     check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, sin_fis, cos_fis, fis, &points);
1451                     check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess + 2 * delta, sin_fis, cos_fis, fis, &points);
1452                 
1453                     if (points == 2) {
1454                         double diff1 = angle_diff(fi, fis[0]);
1455                         double diff2 = angle_diff(fi, fis[1]);
1456                         int point = diff1 < diff2 ? 0 : 1;
1457                         fi = fis[point];
1458                         sin_fi = sin_fis[point];
1459                         cos_fi = cos_fis[point];
1460                         hook_tip_body(1) = hook_root_body(1) - hook_length * cos_fi;
1461                         hook_tip_body(3) = hook_root_body(3) + hook_length * sin_fi;
1462                     }
1463                 }
1464             }
1465         }
1466     } else {
1467         FGColumnVector3 hook_root_vel = Propagate->GetVel() + (Tb2l * (Propagate->GetPQR() *  hook_root_body));
1468         double wire_ends_ec[2][3];
1469         double wire_vel_ec[2][3];
1470         get_wire_ends_ft(t_off, wire_ends_ec, wire_vel_ec);
1471         FGColumnVector3 wire_vel_1 = Tec2l * FGColumnVector3(wire_vel_ec[0][0], wire_vel_ec[0][1], wire_vel_ec[0][2]);
1472         FGColumnVector3 wire_vel_2 = Tec2l * FGColumnVector3(wire_vel_ec[1][0], wire_vel_ec[1][1], wire_vel_ec[1][2]);
1473         FGColumnVector3 rel_vel = hook_root_vel - (wire_vel_1 + wire_vel_2) / 2;
1474         if (rel_vel.Magnitude() < 3) {
1475             got_wire = false;
1476             release_wire();
1477             fgSetDouble("/fdm/jsbsim/external_reactions/hook/magnitude", 0.0);
1478         } else {
1479             FGColumnVector3 wire_end1_body = Tl2b * Location.LocationToLocal(FGColumnVector3(wire_ends_ec[0][0], wire_ends_ec[0][1], wire_ends_ec[0][2])) - hook_root_body;
1480             FGColumnVector3 wire_end2_body = Tl2b * Location.LocationToLocal(FGColumnVector3(wire_ends_ec[1][0], wire_ends_ec[1][1], wire_ends_ec[1][2])) - hook_root_body;
1481             FGColumnVector3 force_plane_normal = wire_end1_body * wire_end2_body;
1482             force_plane_normal.Normalize();
1483             cos_fi = dot3(force_plane_normal, FGColumnVector3(0, 0, 1));
1484             if (cos_fi < 0) cos_fi = -cos_fi;
1485             sin_fi = sqrt(1 - sqr(cos_fi));
1486             fi = atan2(sin_fi, cos_fi) * SG_RADIANS_TO_DEGREES;
1487         
1488             fgSetDouble("/fdm/jsbsim/external_reactions/hook/x", -cos_fi);
1489             fgSetDouble("/fdm/jsbsim/external_reactions/hook/y", 0);
1490             fgSetDouble("/fdm/jsbsim/external_reactions/hook/z", sin_fi);
1491             fgSetDouble("/fdm/jsbsim/external_reactions/hook/magnitude", fgGetDouble("/fdm/jsbsim/systems/hook/force"));
1492         }
1493     }
1494
1495     FGColumnVector3 hook_tip = Location.LocalToLocation(Tb2l * hook_tip_body);
1496
1497     hook_area[0][0] = hook_tip(1);
1498     hook_area[0][1] = hook_tip(2);
1499     hook_area[0][2] = hook_tip(3);
1500
1501     if (!got_wire) {
1502         // The previous positions.
1503         hook_area[2][0] = last_hook_root[0];
1504         hook_area[2][1] = last_hook_root[1];
1505         hook_area[2][2] = last_hook_root[2];
1506         hook_area[3][0] = last_hook_tip[0];
1507         hook_area[3][1] = last_hook_tip[1];
1508         hook_area[3][2] = last_hook_tip[2];
1509
1510         // Check if we caught a wire.
1511         // Returns true if we caught one.
1512         if (caught_wire_ft(t_off, hook_area)) {
1513                 got_wire = true;
1514         }
1515     }
1516     
1517     // save actual position as old position ...
1518     last_hook_tip[0] = hook_area[0][0];
1519     last_hook_tip[1] = hook_area[0][1];
1520     last_hook_tip[2] = hook_area[0][2];
1521     last_hook_root[0] = hook_area[1][0];
1522     last_hook_root[1] = hook_area[1][1];
1523     last_hook_root[2] = hook_area[1][2];
1524     
1525     fgSetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-deg", fi);
1526 }
1527