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