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