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