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