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