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