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