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