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