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