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