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