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