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