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