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