]> git.mxchange.org Git - flightgear.git/blob - src/FDM/JSBSim/JSBSim.cxx
34f2af9a92266291d311491f86fee3fbb4198ccd
[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 #ifdef SG_MATH_EXCEPTION_CLASH
31 #  include <math.h>
32 #endif
33
34 #include STL_STRING
35
36 #include <simgear/constants.h>
37 #include <simgear/debug/logstream.hxx>
38 #include <simgear/math/sg_geodesy.hxx>
39 #include <simgear/misc/sg_path.hxx>
40
41 #include <FDM/flight.hxx>
42
43 #include <Aircraft/aircraft.hxx>
44 #include <Controls/controls.hxx>
45 #include <Main/globals.hxx>
46 #include <Main/fg_props.hxx>
47
48 #include <FDM/JSBSim/FGFDMExec.h>
49 #include <FDM/JSBSim/FGAircraft.h>
50 #include <FDM/JSBSim/FGFCS.h>
51 #include <FDM/JSBSim/FGPosition.h>
52 #include <FDM/JSBSim/FGRotation.h>
53 #include <FDM/JSBSim/FGState.h>
54 #include <FDM/JSBSim/FGTranslation.h>
55 #include <FDM/JSBSim/FGAuxiliary.h>
56 #include <FDM/JSBSim/FGInitialCondition.h>
57 #include <FDM/JSBSim/FGTrim.h>
58 #include <FDM/JSBSim/FGAtmosphere.h>
59 #include <FDM/JSBSim/FGMassBalance.h>
60 #include <FDM/JSBSim/FGAerodynamics.h>
61 #include <FDM/JSBSim/FGLGear.h>
62 #include <FDM/JSBSim/FGPropertyManager.h>
63 #include "JSBSim.hxx"
64
65 static inline double
66 FMAX (double a, double b)
67 {
68   return a > b ? a : b;
69 }
70
71
72 /******************************************************************************/
73
74 FGJSBsim::FGJSBsim( double dt ) 
75   : FGInterface(dt)
76 {
77     bool result;
78    
79                                 // Set up the debugging level
80                                 // FIXME: this will not respond to
81                                 // runtime changes
82
83                                 // if flight is excluded, don't bother
84     if ((logbuf::get_log_classes() & SG_FLIGHT) != 0) {
85
86                                 // do a rough-and-ready mapping to
87                                 // the levels documented in FGFDMExec.h
88         switch (logbuf::get_log_priority()) {
89         case SG_BULK:
90             FGJSBBase::debug_lvl = 0x1f;
91             break;
92         case SG_DEBUG:
93             FGJSBBase::debug_lvl = 0x0f;
94         case SG_INFO:
95             FGJSBBase::debug_lvl = 0x01;
96             break;
97         case SG_WARN:
98         case SG_ALERT:
99             FGJSBBase::debug_lvl = 0x00;
100             break;
101         }
102     }
103
104     fdmex = new FGFDMExec( (FGPropertyManager*)globals->get_props() );
105
106     State           = fdmex->GetState();
107     Atmosphere      = fdmex->GetAtmosphere();
108     FCS             = fdmex->GetFCS();
109     MassBalance     = fdmex->GetMassBalance();
110     Propulsion      = fdmex->GetPropulsion();
111     Aircraft        = fdmex->GetAircraft();
112     Translation     = fdmex->GetTranslation();
113     Rotation        = fdmex->GetRotation();
114     Position        = fdmex->GetPosition();
115     Auxiliary       = fdmex->GetAuxiliary();
116     Aerodynamics    = fdmex->GetAerodynamics();
117     GroundReactions = fdmex->GetGroundReactions(); 
118     
119     fgic=fdmex->GetIC();
120     needTrim=true;
121   
122     SGPath aircraft_path( globals->get_fg_root() );
123     aircraft_path.append( "Aircraft" );
124
125     SGPath engine_path( globals->get_fg_root() );
126     engine_path.append( "Engine" );
127     State->Setdt( dt );
128
129     result = fdmex->LoadModel( aircraft_path.str(),
130                                engine_path.str(),
131                                fgGetString("/sim/aero") );
132     
133     if (result) {
134       SG_LOG( SG_FLIGHT, SG_INFO, "  loaded aero.");
135     } else {
136       SG_LOG( SG_FLIGHT, SG_INFO,
137               "  aero does not exist (you may have mis-typed the name).");
138       throw(-1);
139     }
140
141     SG_LOG( SG_FLIGHT, SG_INFO, "" );
142     SG_LOG( SG_FLIGHT, SG_INFO, "" );
143     SG_LOG( SG_FLIGHT, SG_INFO, "After loading aero definition file ..." );
144
145     int Neng = Propulsion->GetNumEngines();
146     SG_LOG( SG_FLIGHT, SG_INFO, "num engines = " << Neng );
147     
148     if ( GroundReactions->GetNumGearUnits() <= 0 ) {
149         SG_LOG( SG_FLIGHT, SG_ALERT, "num gear units = "
150                 << GroundReactions->GetNumGearUnits() );
151         SG_LOG( SG_FLIGHT, SG_ALERT, "This is a very bad thing because with 0 gear units, the ground trimming");
152          SG_LOG( SG_FLIGHT, SG_ALERT, "routine (coming up later in the code) will core dump.");
153          SG_LOG( SG_FLIGHT, SG_ALERT, "Halting the sim now, and hoping a solution will present itself soon!");
154          exit(-1);
155     }
156         
157     
158     init_gear();
159
160                                 // Set initial fuel levels if provided.
161     for (unsigned int i = 0; i < Propulsion->GetNumTanks(); i++) {
162       SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
163       if (node->getChild("level-gal_us", 0, false) != 0)
164         Propulsion->GetTank(i)
165           ->SetContents(node->getDoubleValue("level-gal_us") * 6.6);
166     }
167     
168     fgSetDouble("/fdm/trim/pitch-trim", FCS->GetPitchTrimCmd());
169     fgSetDouble("/fdm/trim/throttle",   FCS->GetThrottleCmd(0));
170     fgSetDouble("/fdm/trim/aileron",    FCS->GetDaCmd());
171     fgSetDouble("/fdm/trim/rudder",     FCS->GetDrCmd());
172
173     startup_trim = fgGetNode("/sim/presets/trim", true);
174
175     trimmed = fgGetNode("/fdm/trim/trimmed", true);
176     trimmed->setBoolValue(false);
177
178     pitch_trim = fgGetNode("/fdm/trim/pitch-trim", true );
179     throttle_trim = fgGetNode("/fdm/trim/throttle", true );
180     aileron_trim = fgGetNode("/fdm/trim/aileron", true );
181     rudder_trim = fgGetNode("/fdm/trim/rudder", true );
182     
183     stall_warning = fgGetNode("/sim/alarms/stall-warning",true);
184     stall_warning->setDoubleValue(0);
185     
186
187     flap_pos_pct=fgGetNode("/surface-positions/flap-pos-norm",true);
188     elevator_pos_pct=fgGetNode("/surface-positions/elevator-pos-norm",true);
189     left_aileron_pos_pct
190         =fgGetNode("/surface-positions/left-aileron-pos-norm",true);
191     right_aileron_pos_pct
192         =fgGetNode("/surface-positions/right-aileron-pos-norm",true);
193     rudder_pos_pct=fgGetNode("/surface-positions/rudder-pos-norm",true);
194     speedbrake_pos_pct
195         =fgGetNode("/surface-positions/speedbrake-pos-norm",true);
196     spoilers_pos_pct=fgGetNode("/surface-positions/spoilers-pos-norm",true);
197     
198
199     elevator_pos_pct->setDoubleValue(0);
200     left_aileron_pos_pct->setDoubleValue(0);
201     right_aileron_pos_pct->setDoubleValue(0);
202     rudder_pos_pct->setDoubleValue(0);
203     flap_pos_pct->setDoubleValue(0);
204     speedbrake_pos_pct->setDoubleValue(0);
205     spoilers_pos_pct->setDoubleValue(0);
206
207     temperature = fgGetNode("/environment/temperature-degc",true);
208     pressure = fgGetNode("/environment/pressure-inhg",true);
209     density = fgGetNode("/environment/density-slugft3",true);
210     turbulence_gain = fgGetNode("/environment/turbulence/magnitude-norm",true);
211     turbulence_rate = fgGetNode("/environment/turbulence/rate-hz",true);
212     
213     wind_from_north= fgGetNode("/environment/wind-from-north-fps",true);
214     wind_from_east = fgGetNode("/environment/wind-from-east-fps" ,true);
215     wind_from_down = fgGetNode("/environment/wind-from-down-fps" ,true);
216      
217
218 }
219 /******************************************************************************/
220 FGJSBsim::~FGJSBsim(void) {
221         delete fdmex;
222 }
223
224 /******************************************************************************/
225
226 // Initialize the JSBsim flight model, dt is the time increment for
227 // each subsequent iteration through the EOM
228
229 void FGJSBsim::init() {
230
231     double tmp;
232     
233     SG_LOG( SG_FLIGHT, SG_INFO, "Starting and initializing JSBsim" );
234
235     // Explicitly call the superclass's
236     // init method first.
237
238 #ifdef FG_WEATHERCM
239     Atmosphere->UseInternal();
240 #else
241     if (fgGetBool("/environment/params/control-fdm-atmosphere")) {
242       Atmosphere->UseExternal();
243       Atmosphere->SetExTemperature(
244                   9.0/5.0*(temperature->getDoubleValue()+273.15) );
245       Atmosphere->SetExPressure(pressure->getDoubleValue()*70.726566);
246       Atmosphere->SetExDensity(density->getDoubleValue());
247
248       tmp = turbulence_gain->getDoubleValue();
249       Atmosphere->SetTurbGain(tmp * tmp * 100.0);
250
251       tmp = turbulence_rate->getDoubleValue();
252       Atmosphere->SetTurbRate(tmp);
253
254     } else {
255       Atmosphere->UseInternal();
256     }
257 #endif
258     
259     fgic->SetVnorthFpsIC( wind_from_north->getDoubleValue() );
260     fgic->SetVeastFpsIC( wind_from_east->getDoubleValue() );
261     fgic->SetVdownFpsIC( wind_from_down->getDoubleValue() );
262
263     //Atmosphere->SetExTemperature(get_Static_temperature());
264     //Atmosphere->SetExPressure(get_Static_pressure());
265     //Atmosphere->SetExDensity(get_Density());
266     SG_LOG(SG_FLIGHT,SG_INFO,"T,p,rho: " << fdmex->GetAtmosphere()->GetTemperature()
267      << ", " << fdmex->GetAtmosphere()->GetPressure() 
268      << ", " << fdmex->GetAtmosphere()->GetDensity() );
269
270     common_init();
271     copy_to_JSBsim();
272     
273
274     fdmex->RunIC(); //loop JSBSim once w/o integrating
275     copy_from_JSBsim(); //update the bus
276
277     SG_LOG( SG_FLIGHT, SG_INFO, "  Initialized JSBSim with:" );
278
279     switch(fgic->GetSpeedSet()) {
280     case setned:
281         SG_LOG(SG_FLIGHT,SG_INFO, "  Vn,Ve,Vd= "
282                << Position->GetVn() << ", "
283                << Position->GetVe() << ", "
284                << Position->GetVd() << " ft/s");
285     break;
286     case setuvw:
287         SG_LOG(SG_FLIGHT,SG_INFO, "  U,V,W= "
288                << Translation->GetUVW(1) << ", "
289                << Translation->GetUVW(2) << ", "
290                << Translation->GetUVW(3) << " ft/s");
291     break;
292     case setmach:
293         SG_LOG(SG_FLIGHT,SG_INFO, "  Mach: "
294                << Translation->GetMach() );
295     break;
296     case setvc:
297     default:
298         SG_LOG(SG_FLIGHT,SG_INFO, "  Indicated Airspeed: "
299                << Auxiliary->GetVcalibratedKTS() << " knots" );
300     break;
301     }
302     
303     stall_warning->setDoubleValue(0);
304     
305     SG_LOG( SG_FLIGHT, SG_INFO, "  Bank Angle: "
306             <<  Rotation->Getphi()*RADTODEG << " deg" );
307     SG_LOG( SG_FLIGHT, SG_INFO, "  Pitch Angle: "
308             << Rotation->Gettht()*RADTODEG << " deg" );
309     SG_LOG( SG_FLIGHT, SG_INFO, "  True Heading: "
310             << Rotation->Getpsi()*RADTODEG << " deg" );
311     SG_LOG( SG_FLIGHT, SG_INFO, "  Latitude: "
312             << Position->GetLatitude() << " deg" );
313     SG_LOG( SG_FLIGHT, SG_INFO, "  Longitude: "
314             << Position->GetLongitude() << " deg" );
315     SG_LOG( SG_FLIGHT, SG_INFO, "  Altitude: "
316         << Position->Geth() << " feet" );
317     SG_LOG( SG_FLIGHT, SG_INFO, "  loaded initial conditions" );
318
319     SG_LOG( SG_FLIGHT, SG_INFO, "  set dt" );
320
321     SG_LOG( SG_FLIGHT, SG_INFO, "Finished initializing JSBSim" );
322     
323     SG_LOG( SG_FLIGHT, SG_INFO, "FGControls::get_gear_down()= " << 
324                                   globals->get_controls()->get_gear_down() );
325     
326
327    
328 }
329
330 /******************************************************************************/
331
332 // Run an iteration of the EOM (equations of motion)
333
334 void
335 FGJSBsim::update( double dt ) {
336
337     if (is_suspended())
338       return;
339
340     int multiloop = _calc_multiloop(dt);
341
342     int i;
343
344     // double save_alt = 0.0;
345
346     copy_to_JSBsim();
347
348     trimmed->setBoolValue(false);
349     
350     if ( needTrim ) {
351       if ( startup_trim->getBoolValue() ) {
352         SG_LOG(SG_FLIGHT, SG_INFO,
353           "Ready to trim, terrain altitude is: " 
354             << cur_fdm_state->get_Runway_altitude() * SG_METER_TO_FEET );
355         fgic->SetTerrainAltitudeFtIC( cur_fdm_state->get_ground_elev_ft() );
356         do_trim();
357       } else {
358         fdmex->RunIC();  //apply any changes made through the set_ functions
359       }
360       needTrim = false;  
361     }    
362     
363     for ( i=0; i < multiloop; i++ ) {
364         fdmex->Run();
365     }
366
367     FGJSBBase::Message* msg;
368     while (fdmex->ReadMessage()) {
369       msg = fdmex->ProcessMessage();
370       switch (msg->type) {
371       case FGJSBBase::Message::eText:
372         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text );
373         break;
374       case FGJSBBase::Message::eBool:
375         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->bVal );
376         break;
377       case FGJSBBase::Message::eInteger:
378         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->iVal );
379         break;
380       case FGJSBBase::Message::eDouble:
381         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->dVal );
382         break;
383       default:
384         SG_LOG( SG_FLIGHT, SG_INFO, "Unrecognized message type." );
385         break;
386       }
387     }
388
389     // translate JSBsim back to FG structure so that the
390     // autopilot (and the rest of the sim can use the updated values
391     copy_from_JSBsim();
392 }
393
394 /******************************************************************************/
395
396 // Convert from the FGInterface struct to the JSBsim generic_ struct
397
398 bool FGJSBsim::copy_to_JSBsim() {
399     double tmp;
400     unsigned int i;
401
402     // copy control positions into the JSBsim structure
403
404     FCS->SetDaCmd( globals->get_controls()->get_aileron());
405     FCS->SetRollTrimCmd( globals->get_controls()->get_aileron_trim() );
406     FCS->SetDeCmd( globals->get_controls()->get_elevator());
407     FCS->SetPitchTrimCmd( globals->get_controls()->get_elevator_trim() );
408     FCS->SetDrCmd( -globals->get_controls()->get_rudder() );
409     FCS->SetYawTrimCmd( -globals->get_controls()->get_rudder_trim() );
410     FCS->SetDfCmd(  globals->get_controls()->get_flaps() );
411     FCS->SetDsbCmd( globals->get_controls()->get_speedbrake() ); 
412     FCS->SetDspCmd( globals->get_controls()->get_spoilers() ); 
413
414                                 // Parking brake sets minimum braking
415                                 // level for mains.
416     double parking_brake = globals->get_controls()->get_brake_parking();
417     FCS->SetLBrake(FMAX(globals->get_controls()->get_brake_left(), parking_brake));
418     FCS->SetRBrake(FMAX(globals->get_controls()->get_brake_right(), parking_brake));
419     FCS->SetCBrake( 0.0 );
420
421     FCS->SetGearCmd( globals->get_controls()->get_gear_down());
422     for (i = 0; i < Propulsion->GetNumEngines(); i++) {
423       FGEngine * eng = Propulsion->GetEngine(i);
424       SGPropertyNode * node = fgGetNode("engines/engine", i, true);
425       FCS->SetThrottleCmd(i, globals->get_controls()->get_throttle(i));
426       FCS->SetMixtureCmd(i, globals->get_controls()->get_mixture(i));
427       FCS->SetPropAdvanceCmd(i, globals->get_controls()->get_prop_advance(i));
428       Propulsion->GetThruster(i)->SetRPM(node->getDoubleValue("rpm"));
429       eng->SetMagnetos( globals->get_controls()->get_magnetos(i) );
430       eng->SetStarter( globals->get_controls()->get_starter(i) );
431       eng->SetAugmentation( globals->get_controls()->get_augmentation(i) );
432       eng->SetReverse( globals->get_controls()->get_reverser(i) );
433       eng->SetInjection( globals->get_controls()->get_water_injection(i) );
434       eng->SetIgnition( globals->get_controls()->get_ignition(i) );
435       eng->SetCutoff( globals->get_controls()->get_cutoff(i) );
436       eng->SetNitrous( globals->get_controls()->get_nitrous_injection(i) );
437       eng->SetRunning( node->getBoolValue("running") );
438     }
439
440     _set_Runway_altitude( cur_fdm_state->get_Runway_altitude() );
441     Position->SetSeaLevelRadius( get_Sea_level_radius() );
442     Position->SetRunwayRadius( get_Runway_altitude() 
443                                + get_Sea_level_radius() );
444
445     Atmosphere->SetExTemperature(
446                   9.0/5.0*(temperature->getDoubleValue()+273.15) );
447     Atmosphere->SetExPressure(pressure->getDoubleValue()*70.726566);
448     Atmosphere->SetExDensity(density->getDoubleValue());
449
450     tmp = turbulence_gain->getDoubleValue();
451     Atmosphere->SetTurbGain(tmp * tmp * 100.0);
452
453     tmp = turbulence_rate->getDoubleValue();
454     Atmosphere->SetTurbRate(tmp);
455
456     Atmosphere->SetWindNED( wind_from_north->getDoubleValue(),
457                             wind_from_east->getDoubleValue(),
458                             wind_from_down->getDoubleValue() );
459 //    SG_LOG(SG_FLIGHT,SG_INFO, "Wind NED: "
460 //                  << get_V_north_airmass() << ", "
461 //                  << get_V_east_airmass()  << ", "
462 //                  << get_V_down_airmass() );
463
464     for (i = 0; i < Propulsion->GetNumTanks(); i++) {
465       SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
466       FGTank * tank = Propulsion->GetTank(i);
467       tank->SetContents(node->getDoubleValue("level-gal_us") * 6.6);
468 //       tank->SetContents(node->getDoubleValue("level-lb"));
469     }
470
471     return true;
472 }
473
474 /******************************************************************************/
475
476 // Convert from the JSBsim generic_ struct to the FGInterface struct
477
478 bool FGJSBsim::copy_from_JSBsim() {
479     unsigned int i, j;
480
481     _set_Inertias( MassBalance->GetMass(),
482                    MassBalance->GetIxx(),
483                    MassBalance->GetIyy(),
484                    MassBalance->GetIzz(),
485                    MassBalance->GetIxz() );
486
487     _set_CG_Position( MassBalance->GetXYZcg(1),
488                       MassBalance->GetXYZcg(2),
489                       MassBalance->GetXYZcg(3) );
490
491     _set_Accels_Body( Aircraft->GetBodyAccel()(1),
492                       Aircraft->GetBodyAccel()(2),
493                       Aircraft->GetBodyAccel()(3) );
494
495     //_set_Accels_CG_Body( Aircraft->GetBodyAccel()(1),
496     //                     Aircraft->GetBodyAccel()(2),
497     //                     Aircraft->GetBodyAccel()(3) );
498     //
499     _set_Accels_CG_Body_N ( Aircraft->GetNcg()(1),
500                             Aircraft->GetNcg()(2),
501                             Aircraft->GetNcg()(3) );
502     
503     _set_Accels_Pilot_Body( Auxiliary->GetPilotAccel()(1),
504                             Auxiliary->GetPilotAccel()(2),
505                             Auxiliary->GetPilotAccel()(3) );
506
507    // _set_Accels_Pilot_Body_N( Auxiliary->GetPilotAccel()(1)/32.1739,
508    //                           Auxiliary->GetNpilot(2)/32.1739,
509    //                           Auxiliary->GetNpilot(3)/32.1739 );
510
511     _set_Nlf( Aircraft->GetNlf() );
512
513     // Velocities
514
515     _set_Velocities_Local( Position->GetVn(),
516                            Position->GetVe(),
517                            Position->GetVd() );
518
519     _set_Velocities_Wind_Body( Translation->GetUVW(1),
520                                Translation->GetUVW(2),
521                                Translation->GetUVW(3) );
522
523     _set_V_rel_wind( Translation->GetVt() );
524
525     _set_V_equiv_kts( Auxiliary->GetVequivalentKTS() );
526
527     // _set_V_calibrated( Auxiliary->GetVcalibratedFPS() );
528
529     _set_V_calibrated_kts( Auxiliary->GetVcalibratedKTS() );
530
531     _set_V_ground_speed( Position->GetVground() );
532
533     _set_Omega_Body( Rotation->GetPQR(1),
534                      Rotation->GetPQR(2),
535                      Rotation->GetPQR(3) );
536
537     _set_Euler_Rates( Rotation->GetEulerRates(1),
538                       Rotation->GetEulerRates(2),
539                       Rotation->GetEulerRates(3) );
540
541     _set_Geocentric_Rates(Position->GetLatitudeDot(),
542                           Position->GetLongitudeDot(),
543                           Position->Gethdot() );
544
545     _set_Mach_number( Translation->GetMach() );
546
547     // Positions
548     _updateGeocentricPosition( Position->GetLatitude(),
549                                Position->GetLongitude(),
550                                Position->Geth() );
551
552     _set_Altitude_AGL( Position->GetDistanceAGL() );
553
554     _set_Euler_Angles( Rotation->Getphi(),
555                        Rotation->Gettht(),
556                        Rotation->Getpsi() );
557
558     _set_Alpha( Translation->Getalpha() );
559     _set_Beta( Translation->Getbeta() );
560
561
562     _set_Gamma_vert_rad( Position->GetGamma() );
563     // set_Gamma_horiz_rad( Gamma_horiz_rad );
564
565     _set_Earth_position_angle( Auxiliary->GetEarthPositionAngle() );
566
567     _set_Climb_Rate( Position->Gethdot() );
568
569
570     for ( i = 1; i <= 3; i++ ) {
571         for ( j = 1; j <= 3; j++ ) {
572             _set_T_Local_to_Body( i, j, State->GetTl2b(i,j) );
573         }
574     }
575
576                                 // Copy the engine values from JSBSim.
577     for( i=0; i < Propulsion->GetNumEngines(); i++ ) {
578       SGPropertyNode * node = fgGetNode("engines/engine", i, true);
579       FGEngine * eng = Propulsion->GetEngine(i);
580       FGThruster * thrust = Propulsion->GetThruster(i);
581
582       node->setDoubleValue("mp-osi", eng->getManifoldPressure_inHg());
583       node->setDoubleValue("rpm", thrust->GetRPM());
584       node->setDoubleValue("egt-degf", eng->getExhaustGasTemp_degF());
585       node->setDoubleValue("fuel-flow-gph", eng->getFuelFlow_gph());
586       node->setDoubleValue("cht-degf", eng->getCylinderHeadTemp_degF());
587       node->setDoubleValue("oil-temperature-degf", eng->getOilTemp_degF());
588       node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
589       node->setDoubleValue("thrust_lb", eng->GetThrust());
590       node->setDoubleValue("N1", eng->GetN1());
591       node->setDoubleValue("N2", eng->GetN2());
592       node->setDoubleValue("EGT_degC", eng->GetEGT());
593       node->setDoubleValue("fuel-flow_pph", eng->getFuelFlow_pph());
594       node->setDoubleValue("nozzle-pos-norm", eng->GetNozzle());
595       node->setDoubleValue("inlet-pos-norm", eng->GetInlet());
596       node->setBoolValue("running", eng->GetRunning());
597       node->setBoolValue("starter", eng->GetStarter());
598       node->setBoolValue("cranking", eng->GetCranking());
599       node->setBoolValue("ignition", eng->GetIgnition());
600       node->setBoolValue("augmentation", eng->GetAugmentation());
601       node->setBoolValue("water-injection", eng->GetInjection());
602       node->setBoolValue("reversed", eng->GetReversed());
603       node->setBoolValue("cutoff", eng->GetCutoff());
604       node->setBoolValue("nitrous", eng->GetNitrous());
605       globals->get_controls()->set_starter(i, eng->GetStarter() );
606       globals->get_controls()->set_cutoff(i, eng->GetCutoff() );
607       globals->get_controls()->set_augmentation(i, eng->GetAugmentation() );
608       globals->get_controls()->set_reverser(i, eng->GetReversed() );
609       globals->get_controls()->set_water_injection(i, eng->GetInjection() );
610     }
611
612     static const SGPropertyNode *fuel_freeze
613         = fgGetNode("/sim/freeze/fuel");
614
615                                 // Copy the fuel levels from JSBSim if fuel
616                                 // freeze not enabled.
617     if ( ! fuel_freeze->getBoolValue() ) {
618         for (i = 0; i < Propulsion->GetNumTanks(); i++) {
619             SGPropertyNode * node
620                 = fgGetNode("/consumables/fuel/tank", i, true);
621             double contents = Propulsion->GetTank(i)->GetContents();
622             node->setDoubleValue("level-gal_us", contents/6.6);
623             node->setDoubleValue("level-lb", contents);
624             // node->setDoubleValue("temperature_degC", 
625         }
626     }
627
628     update_gear();
629     
630     stall_warning->setDoubleValue( Aerodynamics->GetStallWarn() );
631     
632     /* elevator_pos_deg->setDoubleValue( FCS->GetDePos()*SG_RADIANS_TO_DEGREES );
633     left_aileron_pos_deg->setDoubleValue( FCS->GetDaLPos()*SG_RADIANS_TO_DEGREES );
634     right_aileron_pos_deg->setDoubleValue( FCS->GetDaRPos()*SG_RADIANS_TO_DEGREES );
635     rudder_pos_deg->setDoubleValue( -1*FCS->GetDrPos()*SG_RADIANS_TO_DEGREES );
636     flap_pos_deg->setDoubleValue( FCS->GetDfPos() ); */
637
638     
639     elevator_pos_pct->setDoubleValue( FCS->GetDePos(ofNorm) );
640     left_aileron_pos_pct->setDoubleValue( FCS->GetDaLPos(ofNorm) );
641     right_aileron_pos_pct->setDoubleValue( -1*FCS->GetDaLPos(ofNorm) );
642     rudder_pos_pct->setDoubleValue( -1*FCS->GetDrPos(ofNorm) );
643     flap_pos_pct->setDoubleValue( FCS->GetDfPos(ofNorm) );
644     speedbrake_pos_pct->setDoubleValue( FCS->GetDsbPos(ofNorm) );
645     spoilers_pos_pct->setDoubleValue( FCS->GetDspPos(ofNorm) );
646
647     
648     return true;
649 }
650
651 bool FGJSBsim::ToggleDataLogging(void) {
652     return fdmex->GetOutput()->Toggle();
653 }
654
655
656 bool FGJSBsim::ToggleDataLogging(bool state) {
657     if (state) {
658       fdmex->GetOutput()->Enable();
659       return true;
660     } else {
661       fdmex->GetOutput()->Disable();
662       return false;
663     }
664 }
665
666
667 //Positions
668 void FGJSBsim::set_Latitude(double lat) {
669     static const SGPropertyNode *altitude = fgGetNode("/position/altitude-ft");
670     double alt;
671     double sea_level_radius_meters, lat_geoc;
672
673                                 // In case we're not trimming
674     FGInterface::set_Latitude(lat);
675     
676     if ( altitude->getDoubleValue() > -9990 ) {
677       alt = altitude->getDoubleValue();
678     } else {
679       alt = 0.0;
680     }
681    
682     update_ic();
683     SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Latitude: " << lat );
684     SG_LOG(SG_FLIGHT,SG_INFO," cur alt (ft) =  " << alt );
685
686     sgGeodToGeoc( lat, alt * SG_FEET_TO_METER, 
687                       &sea_level_radius_meters, &lat_geoc );
688     _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET  );
689     fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET  );    
690     _set_Runway_altitude( cur_fdm_state->get_Runway_altitude() );
691     fgic->SetTerrainAltitudeFtIC( cur_fdm_state->get_ground_elev_ft() );
692     fgic->SetLatitudeRadIC( lat_geoc );
693     needTrim=true;
694 }
695
696 void FGJSBsim::set_Longitude(double lon) {
697
698     SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Longitude: " << lon );
699
700                                 // In case we're not trimming
701     FGInterface::set_Longitude(lon);
702
703     update_ic();
704     fgic->SetLongitudeRadIC( lon );
705     _set_Runway_altitude( cur_fdm_state->get_Runway_altitude() );
706     fgic->SetTerrainAltitudeFtIC( cur_fdm_state->get_ground_elev_ft() );
707     needTrim=true;
708 }
709
710 void FGJSBsim::set_Altitude(double alt) {
711     static const SGPropertyNode *latitude = fgGetNode("/position/latitude-deg");
712
713     double sea_level_radius_meters,lat_geoc;
714
715     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Altitude: " << alt );
716     SG_LOG(SG_FLIGHT,SG_INFO, "  lat (deg) = " << latitude->getDoubleValue() );
717     
718                                 // In case we're not trimming
719     FGInterface::set_Altitude(alt);
720
721     update_ic();
722     sgGeodToGeoc( latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS, alt,
723                   &sea_level_radius_meters, &lat_geoc);
724     _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET  );
725     fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET );
726     _set_Runway_altitude( cur_fdm_state->get_Runway_altitude() );
727     fgic->SetTerrainAltitudeFtIC( cur_fdm_state->get_ground_elev_ft() );
728     SG_LOG(SG_FLIGHT, SG_INFO,
729           "Terrain altitude: " << cur_fdm_state->get_Runway_altitude() * SG_METER_TO_FEET );
730     fgic->SetLatitudeRadIC( lat_geoc );
731     fgic->SetAltitudeFtIC(alt);
732     needTrim=true;
733 }
734
735 void FGJSBsim::set_V_calibrated_kts(double vc) {
736     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_V_calibrated_kts: " <<  vc );
737
738                                 // In case we're not trimming
739     FGInterface::set_V_calibrated_kts(vc);
740
741     update_ic();
742     fgic->SetVcalibratedKtsIC(vc);
743     needTrim=true;
744 }
745
746 void FGJSBsim::set_Mach_number(double mach) {
747     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Mach_number: " <<  mach );
748     
749                                 // In case we're not trimming
750     FGInterface::set_Mach_number(mach);
751
752     update_ic();
753     fgic->SetMachIC(mach);
754     needTrim=true;
755 }
756
757 void FGJSBsim::set_Velocities_Local( double north, double east, double down ){
758     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Local: "
759        << north << ", " <<  east << ", " << down );
760     
761                                 // In case we're not trimming
762     FGInterface::set_Velocities_Local(north, east, down);
763
764     update_ic();
765     fgic->SetVnorthFpsIC(north);
766     fgic->SetVeastFpsIC(east);
767     fgic->SetVdownFpsIC(down);
768     needTrim=true;
769 }
770
771 void FGJSBsim::set_Velocities_Wind_Body( double u, double v, double w){
772     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Wind_Body: "
773        << u << ", " <<  v << ", " <<  w );
774     
775                                 // In case we're not trimming
776     FGInterface::set_Velocities_Wind_Body(u, v, w);
777
778     update_ic();
779     fgic->SetUBodyFpsIC(u);
780     fgic->SetVBodyFpsIC(v);
781     fgic->SetWBodyFpsIC(w);
782     needTrim=true;
783 }
784
785 //Euler angles
786 void FGJSBsim::set_Euler_Angles( double phi, double theta, double psi ) {
787     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Euler_Angles: "
788        << phi << ", " << theta << ", " << psi );
789     
790                                 // In case we're not trimming
791     FGInterface::set_Euler_Angles(phi, theta, psi);
792
793     update_ic();
794     fgic->SetPitchAngleRadIC(theta);
795     fgic->SetRollAngleRadIC(phi);
796     fgic->SetTrueHeadingRadIC(psi);
797     needTrim=true;
798 }
799
800 //Flight Path
801 void FGJSBsim::set_Climb_Rate( double roc) {
802     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Climb_Rate: " << roc );
803     
804                                 // In case we're not trimming
805     FGInterface::set_Climb_Rate(roc);
806
807     update_ic();
808     //since both climb rate and flight path angle are set in the FG
809     //startup sequence, something is needed to keep one from cancelling
810     //out the other.
811     if( !(fabs(roc) > 1 && fabs(fgic->GetFlightPathAngleRadIC()) < 0.01) ) {
812       fgic->SetClimbRateFpsIC(roc);
813     }  
814     needTrim=true;
815 }
816
817 void FGJSBsim::set_Gamma_vert_rad( double gamma) {
818     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Gamma_vert_rad: " << gamma );
819     
820     update_ic();
821     if( !(fabs(gamma) < 0.01 && fabs(fgic->GetClimbRateFpsIC()) > 1) ) {
822       fgic->SetFlightPathAngleRadIC(gamma);
823     }  
824     needTrim=true;
825 }
826
827 void FGJSBsim::init_gear(void ) {
828     
829     FGGroundReactions* gr=fdmex->GetGroundReactions();
830     int Ngear=GroundReactions->GetNumGearUnits();
831     for (int i=0;i<Ngear;i++) {
832       SGPropertyNode * node = fgGetNode("gear/gear", i, true);
833       node->setDoubleValue("xoffset-in",
834                            gr->GetGearUnit(i)->GetBodyLocation()(1));
835       node->setDoubleValue("yoffset-in",
836                            gr->GetGearUnit(i)->GetBodyLocation()(2));
837       node->setDoubleValue("zoffset-in",
838                            gr->GetGearUnit(i)->GetBodyLocation()(3));
839       node->setBoolValue("wow", gr->GetGearUnit(i)->GetWOW());
840       node->setBoolValue("has-brake", gr->GetGearUnit(i)->GetBrakeGroup() > 0);
841       node->setDoubleValue("position-norm", FCS->GetGearPos());
842       node->setDoubleValue("tire-pressure-norm", gr->GetGearUnit(i)->GetTirePressure());
843     }  
844 }
845
846 void FGJSBsim::update_gear(void) {
847     
848     FGGroundReactions* gr=fdmex->GetGroundReactions();
849     int Ngear=GroundReactions->GetNumGearUnits();
850     for (int i=0;i<Ngear;i++) {
851       SGPropertyNode * node = fgGetNode("gear/gear", i, true);
852       node->getChild("wow", 0, true)
853         ->setBoolValue(gr->GetGearUnit(i)->GetWOW());
854       node->getChild("position-norm", 0, true)
855         ->setDoubleValue(FCS->GetGearPos());
856       gr->GetGearUnit(i)->SetTirePressure(node->getDoubleValue("tire-pressure-norm"));
857     }  
858 }
859
860 void FGJSBsim::do_trim(void) {
861
862         FGTrim *fgtrim;
863         if( fgGetBool("/sim/presets/onground") ) {
864             fgic->SetVcalibratedKtsIC(0.0);
865             fgtrim=new FGTrim(fdmex,tGround);
866         } else {
867             fgtrim=new FGTrim(fdmex,tLongitudinal);
868         }
869         if( !fgtrim->DoTrim() ) {
870             fgtrim->Report();
871             fgtrim->TrimStats();
872         } else {
873             trimmed->setBoolValue(true);
874         }
875         if (FGJSBBase::debug_lvl > 0)
876             State->ReportState();
877         delete fgtrim;
878         pitch_trim->setDoubleValue( FCS->GetPitchTrimCmd() );
879         throttle_trim->setDoubleValue( FCS->GetThrottleCmd(0) );
880         aileron_trim->setDoubleValue( FCS->GetDaCmd() );
881         rudder_trim->setDoubleValue( FCS->GetDrCmd() );
882
883         globals->get_controls()->set_elevator_trim(FCS->GetPitchTrimCmd());
884         globals->get_controls()->set_elevator(FCS->GetDeCmd());
885         globals->get_controls()->set_throttle(FGControls::ALL_ENGINES,
886                                               FCS->GetThrottleCmd(0));
887
888         globals->get_controls()->set_aileron(FCS->GetDaCmd());
889         globals->get_controls()->set_rudder( FCS->GetDrCmd());
890     
891         SG_LOG( SG_FLIGHT, SG_INFO, "  Trim complete" );
892 }          
893
894 void FGJSBsim::update_ic(void) {       
895    if( !needTrim ) {
896      fgic->SetLatitudeRadIC(get_Lat_geocentric() );       
897      fgic->SetLongitudeRadIC( get_Longitude() );       
898      fgic->SetAltitudeFtIC( get_Altitude() );       
899      fgic->SetVcalibratedKtsIC( get_V_calibrated_kts() );       
900      fgic->SetPitchAngleRadIC( get_Theta() );       
901      fgic->SetRollAngleRadIC( get_Phi() );       
902      fgic->SetTrueHeadingRadIC( get_Psi() );       
903      fgic->SetClimbRateFpsIC( get_Climb_Rate() );
904    }  
905 }
906