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