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