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