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