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