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