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