]> git.mxchange.org Git - flightgear.git/blob - src/FDM/JSBSim/JSBSim.cxx
Make yasim accept the launchbar and hook properties. They are not tied to anything...
[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 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29
30 #include <stdio.h>      //      size_t
31 #ifdef SG_MATH_EXCEPTION_CLASH
32 #  include <math.h>
33 #endif
34
35 #include STL_STRING
36
37 #include <simgear/constants.h>
38 #include <simgear/debug/logstream.hxx>
39 #include <simgear/math/sg_geodesy.hxx>
40 #include <simgear/misc/sg_path.hxx>
41
42 #include <FDM/flight.hxx>
43
44 #include <Aircraft/aircraft.hxx>
45 #include <Controls/controls.hxx>
46 #include <Main/globals.hxx>
47 #include <Main/fg_props.hxx>
48
49 #include <FDM/JSBSim/FGFDMExec.h>
50 #include <FDM/JSBSim/FGAircraft.h>
51 #include <FDM/JSBSim/FGFCS.h>
52 #include <FDM/JSBSim/FGPropagate.h>
53 #include <FDM/JSBSim/FGState.h>
54 #include <FDM/JSBSim/FGAuxiliary.h>
55 #include <FDM/JSBSim/FGInitialCondition.h>
56 #include <FDM/JSBSim/FGTrim.h>
57 #include <FDM/JSBSim/FGAtmosphere.h>
58 #include <FDM/JSBSim/FGMassBalance.h>
59 #include <FDM/JSBSim/FGAerodynamics.h>
60 #include <FDM/JSBSim/FGLGear.h>
61 #include <FDM/JSBSim/FGPropertyManager.h>
62 #include <FDM/JSBSim/FGEngine.h>
63 #include <FDM/JSBSim/FGPiston.h>
64 #include <FDM/JSBSim/FGTurbine.h>
65 #include <FDM/JSBSim/FGRocket.h>
66 #include <FDM/JSBSim/FGElectric.h>
67 #include <FDM/JSBSim/FGNozzle.h>
68 #include <FDM/JSBSim/FGPropeller.h>
69 #include <FDM/JSBSim/FGRotor.h>
70 #include <FDM/JSBSim/FGTank.h>
71 #include "JSBSim.hxx"
72
73 static inline double
74 FMAX (double a, double b)
75 {
76   return a > b ? a : b;
77 }
78
79
80 /******************************************************************************/
81
82 FGJSBsim::FGJSBsim( double dt )
83   : FGInterface(dt)
84 {
85     bool result;
86
87                                 // Set up the debugging level
88                                 // FIXME: this will not respond to
89                                 // runtime changes
90
91                                 // if flight is excluded, don't bother
92     if ((logbuf::get_log_classes() & SG_FLIGHT) != 0) {
93
94                                 // do a rough-and-ready mapping to
95                                 // the levels documented in FGFDMExec.h
96         switch (logbuf::get_log_priority()) {
97         case SG_BULK:
98             FGJSBBase::debug_lvl = 0x1f;
99             break;
100         case SG_DEBUG:
101             FGJSBBase::debug_lvl = 0x0f;
102         case SG_INFO:
103             FGJSBBase::debug_lvl = 0x01;
104             break;
105         case SG_WARN:
106         case SG_ALERT:
107             FGJSBBase::debug_lvl = 0x00;
108             break;
109         }
110     }
111
112     fdmex = new FGFDMExec( (FGPropertyManager*)globals->get_props() );
113
114     State           = fdmex->GetState();
115     Atmosphere      = fdmex->GetAtmosphere();
116     FCS             = fdmex->GetFCS();
117     MassBalance     = fdmex->GetMassBalance();
118     Propulsion      = fdmex->GetPropulsion();
119     Aircraft        = fdmex->GetAircraft();
120     Propagate        = fdmex->GetPropagate();
121     Auxiliary       = fdmex->GetAuxiliary();
122     Aerodynamics    = fdmex->GetAerodynamics();
123     GroundReactions = fdmex->GetGroundReactions();
124
125     fgic=fdmex->GetIC();
126     needTrim=true;
127
128     SGPath aircraft_path( fgGetString("/sim/aircraft-dir") );
129
130     SGPath engine_path( fgGetString("/sim/aircraft-dir") );
131     engine_path.append( "Engine" );
132     State->Setdt( dt );
133
134     result = fdmex->LoadModel( aircraft_path.str(),
135                                engine_path.str(),
136                                fgGetString("/sim/aero"), false );
137
138     if (result) {
139       SG_LOG( SG_FLIGHT, SG_INFO, "  loaded aero.");
140     } else {
141       SG_LOG( SG_FLIGHT, SG_INFO,
142               "  aero does not exist (you may have mis-typed the name).");
143       throw(-1);
144     }
145
146     SG_LOG( SG_FLIGHT, SG_INFO, "" );
147     SG_LOG( SG_FLIGHT, SG_INFO, "" );
148     SG_LOG( SG_FLIGHT, SG_INFO, "After loading aero definition file ..." );
149
150     int Neng = Propulsion->GetNumEngines();
151     SG_LOG( SG_FLIGHT, SG_INFO, "num engines = " << Neng );
152
153     if ( GroundReactions->GetNumGearUnits() <= 0 ) {
154         SG_LOG( SG_FLIGHT, SG_ALERT, "num gear units = "
155                 << GroundReactions->GetNumGearUnits() );
156         SG_LOG( SG_FLIGHT, SG_ALERT, "This is a very bad thing because with 0 gear units, the ground trimming");
157         SG_LOG( SG_FLIGHT, SG_ALERT, "routine (coming up later in the code) will core dump.");
158         SG_LOG( SG_FLIGHT, SG_ALERT, "Halting the sim now, and hoping a solution will present itself soon!");
159         exit(-1);
160     }
161
162     init_gear();
163
164     // Set initial fuel levels if provided.
165     for (unsigned int i = 0; i < Propulsion->GetNumTanks(); i++) {
166       SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
167       if (node->getChild("level-gal_us", 0, false) != 0) {
168         Propulsion->GetTank(i)->SetContents(node->getDoubleValue("level-gal_us") * 6.6);
169       } else {
170         node->setDoubleValue("level-lb", Propulsion->GetTank(i)->GetContents());
171         node->setDoubleValue("level-gal_us", Propulsion->GetTank(i)->GetContents() / 6.6);
172       }
173     }
174     Propulsion->SetFuelFreeze((fgGetNode("/sim/freeze/fuel",true))->getBoolValue());
175     
176     fgSetDouble("/fdm/trim/pitch-trim", FCS->GetPitchTrimCmd());
177     fgSetDouble("/fdm/trim/throttle",   FCS->GetThrottleCmd(0));
178     fgSetDouble("/fdm/trim/aileron",    FCS->GetDaCmd());
179     fgSetDouble("/fdm/trim/rudder",     FCS->GetDrCmd());
180
181     startup_trim = fgGetNode("/sim/presets/trim", true);
182
183     trimmed = fgGetNode("/fdm/trim/trimmed", true);
184     trimmed->setBoolValue(false);
185
186     pitch_trim = fgGetNode("/fdm/trim/pitch-trim", true );
187     throttle_trim = fgGetNode("/fdm/trim/throttle", true );
188     aileron_trim = fgGetNode("/fdm/trim/aileron", true );
189     rudder_trim = fgGetNode("/fdm/trim/rudder", true );
190
191     stall_warning = fgGetNode("/sim/alarms/stall-warning",true);
192     stall_warning->setDoubleValue(0);
193
194
195     flap_pos_pct=fgGetNode("/surface-positions/flap-pos-norm",true);
196     elevator_pos_pct=fgGetNode("/surface-positions/elevator-pos-norm",true);
197     left_aileron_pos_pct
198         =fgGetNode("/surface-positions/left-aileron-pos-norm",true);
199     right_aileron_pos_pct
200         =fgGetNode("/surface-positions/right-aileron-pos-norm",true);
201     rudder_pos_pct=fgGetNode("/surface-positions/rudder-pos-norm",true);
202     speedbrake_pos_pct
203         =fgGetNode("/surface-positions/speedbrake-pos-norm",true);
204     spoilers_pos_pct=fgGetNode("/surface-positions/spoilers-pos-norm",true);
205
206     elevator_pos_pct->setDoubleValue(0);
207     left_aileron_pos_pct->setDoubleValue(0);
208     right_aileron_pos_pct->setDoubleValue(0);
209     rudder_pos_pct->setDoubleValue(0);
210     flap_pos_pct->setDoubleValue(0);
211     speedbrake_pos_pct->setDoubleValue(0);
212     spoilers_pos_pct->setDoubleValue(0);
213
214     temperature = fgGetNode("/environment/temperature-degc",true);
215     pressure = fgGetNode("/environment/pressure-inhg",true);
216     density = fgGetNode("/environment/density-slugft3",true);
217     turbulence_gain = fgGetNode("/environment/turbulence/magnitude-norm",true);
218     turbulence_rate = fgGetNode("/environment/turbulence/rate-hz",true);
219
220     wind_from_north= fgGetNode("/environment/wind-from-north-fps",true);
221     wind_from_east = fgGetNode("/environment/wind-from-east-fps" ,true);
222     wind_from_down = fgGetNode("/environment/wind-from-down-fps" ,true);
223
224     for (unsigned int i = 0; i < Propulsion->GetNumEngines(); i++) {
225       SGPropertyNode * node = fgGetNode("engines/engine", i, true);
226       Propulsion->GetEngine(i)->GetThruster()->SetRPM(node->getDoubleValue("rpm") /
227                      Propulsion->GetEngine(i)->GetThruster()->GetGearRatio());
228     }
229 }
230
231 /******************************************************************************/
232 FGJSBsim::~FGJSBsim(void)
233 {
234   delete fdmex;
235 }
236
237 /******************************************************************************/
238
239 // Initialize the JSBsim flight model, dt is the time increment for
240 // each subsequent iteration through the EOM
241
242 void FGJSBsim::init()
243 {
244     double tmp;
245
246     SG_LOG( SG_FLIGHT, SG_INFO, "Starting and initializing JSBsim" );
247
248     // Explicitly call the superclass's
249     // init method first.
250
251 #ifdef FG_WEATHERCM
252     Atmosphere->UseInternal();
253 #else
254     if (fgGetBool("/environment/params/control-fdm-atmosphere")) {
255       Atmosphere->UseExternal();
256       Atmosphere->SetExTemperature(
257                   9.0/5.0*(temperature->getDoubleValue()+273.15) );
258       Atmosphere->SetExPressure(pressure->getDoubleValue()*70.726566);
259       Atmosphere->SetExDensity(density->getDoubleValue());
260
261       tmp = turbulence_gain->getDoubleValue();
262       Atmosphere->SetTurbGain(tmp * tmp * 100.0);
263
264       tmp = turbulence_rate->getDoubleValue();
265       Atmosphere->SetTurbRate(tmp);
266
267     } else {
268       Atmosphere->UseInternal();
269     }
270 #endif
271
272     fgic->SetVnorthFpsIC( wind_from_north->getDoubleValue() );
273     fgic->SetVeastFpsIC( wind_from_east->getDoubleValue() );
274     fgic->SetVdownFpsIC( wind_from_down->getDoubleValue() );
275
276     //Atmosphere->SetExTemperature(get_Static_temperature());
277     //Atmosphere->SetExPressure(get_Static_pressure());
278     //Atmosphere->SetExDensity(get_Density());
279     SG_LOG(SG_FLIGHT,SG_INFO,"T,p,rho: " << fdmex->GetAtmosphere()->GetTemperature()
280      << ", " << fdmex->GetAtmosphere()->GetPressure()
281      << ", " << fdmex->GetAtmosphere()->GetDensity() );
282
283     common_init();
284
285     copy_to_JSBsim();
286     fdmex->RunIC();     //loop JSBSim once w/o integrating
287     copy_from_JSBsim(); //update the bus
288
289     SG_LOG( SG_FLIGHT, SG_INFO, "  Initialized JSBSim with:" );
290
291     switch(fgic->GetSpeedSet()) {
292     case setned:
293         SG_LOG(SG_FLIGHT,SG_INFO, "  Vn,Ve,Vd= "
294                << Propagate->GetVel(eNorth) << ", "
295                << Propagate->GetVel(eEast) << ", "
296                << Propagate->GetVel(eDown) << " ft/s");
297     break;
298     case setuvw:
299         SG_LOG(SG_FLIGHT,SG_INFO, "  U,V,W= "
300                << Propagate->GetUVW(1) << ", "
301                << Propagate->GetUVW(2) << ", "
302                << Propagate->GetUVW(3) << " ft/s");
303     break;
304     case setmach:
305         SG_LOG(SG_FLIGHT,SG_INFO, "  Mach: "
306                << Auxiliary->GetMach() );
307     break;
308     case setvc:
309     default:
310         SG_LOG(SG_FLIGHT,SG_INFO, "  Indicated Airspeed: "
311                << Auxiliary->GetVcalibratedKTS() << " knots" );
312     break;
313     }
314
315     stall_warning->setDoubleValue(0);
316
317     SG_LOG( SG_FLIGHT, SG_INFO, "  Bank Angle: "
318             << Propagate->GetEuler(ePhi)*RADTODEG << " deg" );
319     SG_LOG( SG_FLIGHT, SG_INFO, "  Pitch Angle: "
320             << Propagate->GetEuler(eTht)*RADTODEG << " deg" );
321     SG_LOG( SG_FLIGHT, SG_INFO, "  True Heading: "
322             << Propagate->GetEuler(ePsi)*RADTODEG << " deg" );
323     SG_LOG( SG_FLIGHT, SG_INFO, "  Latitude: "
324             << Propagate->GetLocation().GetLatitudeDeg() << " deg" );
325     SG_LOG( SG_FLIGHT, SG_INFO, "  Longitude: "
326             << Propagate->GetLocation().GetLongitudeDeg() << " deg" );
327     SG_LOG( SG_FLIGHT, SG_INFO, "  Altitude: "
328             << Propagate->Geth() << " feet" );
329     SG_LOG( SG_FLIGHT, SG_INFO, "  loaded initial conditions" );
330
331     SG_LOG( SG_FLIGHT, SG_INFO, "  set dt" );
332
333     SG_LOG( SG_FLIGHT, SG_INFO, "Finished initializing JSBSim" );
334
335     SG_LOG( SG_FLIGHT, SG_INFO, "FGControls::get_gear_down()= " <<
336                                   globals->get_controls()->get_gear_down() );
337 }
338
339 /******************************************************************************/
340
341 // Run an iteration of the EOM (equations of motion)
342
343 void FGJSBsim::update( double dt )
344 {
345     if (is_suspended())
346       return;
347
348     int multiloop = _calc_multiloop(dt);
349
350     int i;
351
352     // double save_alt = 0.0;
353
354     copy_to_JSBsim();
355
356     trimmed->setBoolValue(false);
357
358     if ( needTrim ) {
359       if ( startup_trim->getBoolValue() ) {
360         SG_LOG(SG_FLIGHT, SG_INFO,
361           "Ready to trim, terrain altitude is: "
362             << cur_fdm_state->get_Runway_altitude() * SG_METER_TO_FEET );
363         fgic->SetTerrainAltitudeFtIC( cur_fdm_state->get_ground_elev_ft() );
364         do_trim();
365       } else {
366         fdmex->RunIC();  //apply any changes made through the set_ functions
367       }
368       needTrim = false;
369     }
370
371     for ( i=0; i < multiloop; i++ ) {
372       fdmex->Run();
373     }
374
375     FGJSBBase::Message* msg;
376     while (fdmex->ReadMessage()) {
377       msg = fdmex->ProcessMessage();
378       switch (msg->type) {
379       case FGJSBBase::Message::eText:
380         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text );
381         break;
382       case FGJSBBase::Message::eBool:
383         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->bVal );
384         break;
385       case FGJSBBase::Message::eInteger:
386         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->iVal );
387         break;
388       case FGJSBBase::Message::eDouble:
389         SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->dVal );
390         break;
391       default:
392         SG_LOG( SG_FLIGHT, SG_INFO, "Unrecognized message type." );
393         break;
394       }
395     }
396
397     // translate JSBsim back to FG structure so that the
398     // autopilot (and the rest of the sim can use the updated values
399     copy_from_JSBsim();
400 }
401
402 /******************************************************************************/
403
404 // Convert from the FGInterface struct to the JSBsim generic_ struct
405
406 bool FGJSBsim::copy_to_JSBsim()
407 {
408     double tmp;
409     unsigned int i;
410
411     // copy control positions into the JSBsim structure
412
413     FCS->SetDaCmd( globals->get_controls()->get_aileron());
414     FCS->SetRollTrimCmd( globals->get_controls()->get_aileron_trim() );
415     FCS->SetDeCmd( globals->get_controls()->get_elevator());
416     FCS->SetPitchTrimCmd( globals->get_controls()->get_elevator_trim() );
417     FCS->SetDrCmd( -globals->get_controls()->get_rudder() );
418     FCS->SetYawTrimCmd( -globals->get_controls()->get_rudder_trim() );
419     // FIXME: make that get_steering work
420 //     FCS->SetDsCmd( globals->get_controls()->get_steering()/80.0 );
421     FCS->SetDsCmd( globals->get_controls()->get_rudder() );
422     FCS->SetDfCmd( globals->get_controls()->get_flaps() );
423     FCS->SetDsbCmd( globals->get_controls()->get_speedbrake() );
424     FCS->SetDspCmd( globals->get_controls()->get_spoilers() );
425
426         // Parking brake sets minimum braking
427         // level for mains.
428     double parking_brake = globals->get_controls()->get_brake_parking();
429     FCS->SetLBrake(FMAX(globals->get_controls()->get_brake_left(), parking_brake));
430     FCS->SetRBrake(FMAX(globals->get_controls()->get_brake_right(), parking_brake));
431     FCS->SetCBrake( 0.0 );
432     // FCS->SetCBrake( globals->get_controls()->get_brake(2) );
433
434     FCS->SetGearCmd( globals->get_controls()->get_gear_down());
435     for (i = 0; i < Propulsion->GetNumEngines(); i++) {
436       SGPropertyNode * node = fgGetNode("engines/engine", i, true);
437
438       FCS->SetThrottleCmd(i, globals->get_controls()->get_throttle(i));
439       FCS->SetMixtureCmd(i, globals->get_controls()->get_mixture(i));
440       FCS->SetPropAdvanceCmd(i, globals->get_controls()->get_prop_advance(i));
441
442       switch (Propulsion->GetEngine(i)->GetType()) {
443       case FGEngine::etPiston:
444         { // FGPiston code block
445         FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
446         eng->SetMagnetos( globals->get_controls()->get_magnetos(i) );
447         break;
448         } // end FGPiston code block
449       case FGEngine::etTurbine:
450         { // FGTurbine code block
451         FGTurbine* eng = (FGTurbine*)Propulsion->GetEngine(i);
452         eng->SetAugmentation( globals->get_controls()->get_augmentation(i) );
453         eng->SetReverse( globals->get_controls()->get_reverser(i) );
454         eng->SetInjection( globals->get_controls()->get_water_injection(i) );
455         eng->SetCutoff( globals->get_controls()->get_cutoff(i) );
456         eng->SetIgnition( globals->get_controls()->get_ignition(i) );
457         break;
458         } // end FGTurbine code block
459       case FGEngine::etRocket:
460         { // FGRocket code block
461         FGRocket* eng = (FGRocket*)Propulsion->GetEngine(i);
462         break;
463         } // end FGRocket code block
464       }
465
466       { // FGEngine code block
467       FGEngine* eng = Propulsion->GetEngine(i);
468
469       eng->SetStarter( globals->get_controls()->get_starter(i) );
470       eng->SetRunning( node->getBoolValue("running") );
471       } // end FGEngine code block
472     }
473
474  
475     _set_Runway_altitude( cur_fdm_state->get_Runway_altitude() );
476     Propagate->SetSeaLevelRadius( get_Sea_level_radius() );
477     Propagate->SetRunwayRadius( get_Runway_altitude()
478                                + get_Sea_level_radius() );
479
480     Atmosphere->SetExTemperature(
481                   9.0/5.0*(temperature->getDoubleValue()+273.15) );
482     Atmosphere->SetExPressure(pressure->getDoubleValue()*70.726566);
483     Atmosphere->SetExDensity(density->getDoubleValue());
484
485     tmp = turbulence_gain->getDoubleValue();
486     Atmosphere->SetTurbGain(tmp * tmp * 100.0);
487
488     tmp = turbulence_rate->getDoubleValue();
489     Atmosphere->SetTurbRate(tmp);
490
491     Atmosphere->SetWindNED( wind_from_north->getDoubleValue(),
492                             wind_from_east->getDoubleValue(),
493                             wind_from_down->getDoubleValue() );
494 //    SG_LOG(SG_FLIGHT,SG_INFO, "Wind NED: "
495 //                  << get_V_north_airmass() << ", "
496 //                  << get_V_east_airmass()  << ", "
497 //                  << get_V_down_airmass() );
498
499     for (i = 0; i < Propulsion->GetNumTanks(); i++) {
500       SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
501       FGTank * tank = Propulsion->GetTank(i);
502       tank->SetContents(node->getDoubleValue("level-gal_us") * 6.6);
503 //       tank->SetContents(node->getDoubleValue("level-lb"));
504     }
505     SGPropertyNode* node = fgGetNode("/systems/refuel", true);
506     Propulsion->SetRefuel(node->getDoubleValue("contact"));
507     Propulsion->SetFuelFreeze((fgGetNode("/sim/freeze/fuel",true))->getBoolValue());
508     
509     return true;
510 }
511
512 /******************************************************************************/
513
514 // Convert from the JSBsim generic_ struct to the FGInterface struct
515
516 bool FGJSBsim::copy_from_JSBsim()
517 {
518     unsigned int i, j;
519 /*
520     _set_Inertias( MassBalance->GetMass(),
521                    MassBalance->GetIxx(),
522                    MassBalance->GetIyy(),
523                    MassBalance->GetIzz(),
524                    MassBalance->GetIxz() );
525 */
526     _set_CG_Position( MassBalance->GetXYZcg(1),
527                       MassBalance->GetXYZcg(2),
528                       MassBalance->GetXYZcg(3) );
529
530     _set_Accels_Body( Aircraft->GetBodyAccel(1),
531                       Aircraft->GetBodyAccel(2),
532                       Aircraft->GetBodyAccel(3) );
533
534     _set_Accels_CG_Body_N ( Aircraft->GetNcg(1),
535                             Aircraft->GetNcg(2),
536                             Aircraft->GetNcg(3) );
537
538     _set_Accels_Pilot_Body( Auxiliary->GetPilotAccel(1),
539                             Auxiliary->GetPilotAccel(2),
540                             Auxiliary->GetPilotAccel(3) );
541
542     _set_Nlf( Aircraft->GetNlf() );
543
544     // Velocities
545
546     _set_Velocities_Local( Propagate->GetVel(eNorth),
547                            Propagate->GetVel(eEast),
548                            Propagate->GetVel(eDown) );
549
550     _set_Velocities_Wind_Body( Propagate->GetUVW(1),
551                                Propagate->GetUVW(2),
552                                Propagate->GetUVW(3) );
553
554     // Make the HUD work ...
555     _set_Velocities_Ground( Propagate->GetVel(eNorth),
556                             Propagate->GetVel(eEast),
557                             -Propagate->GetVel(eDown) );
558
559     _set_V_rel_wind( Auxiliary->GetVt() );
560
561     _set_V_equiv_kts( Auxiliary->GetVequivalentKTS() );
562
563     _set_V_calibrated_kts( Auxiliary->GetVcalibratedKTS() );
564
565     _set_V_ground_speed( Auxiliary->GetVground() );
566
567     _set_Omega_Body( Propagate->GetPQR(eP),
568                      Propagate->GetPQR(eQ),
569                      Propagate->GetPQR(eR) );
570
571     _set_Euler_Rates( Auxiliary->GetEulerRates(ePhi),
572                       Auxiliary->GetEulerRates(eTht),
573                       Auxiliary->GetEulerRates(ePsi) );
574
575     _set_Mach_number( Auxiliary->GetMach() );
576
577     // Positions of Visual Reference Point
578     _updateGeocentricPosition( Auxiliary->GetLocationVRP().GetLatitude(),
579                                Auxiliary->GetLocationVRP().GetLongitude(),
580                                Auxiliary->GethVRP() );
581
582     _set_Altitude_AGL( Propagate->GetDistanceAGL() );
583
584     _set_Euler_Angles( Propagate->GetEuler(ePhi),
585                        Propagate->GetEuler(eTht),
586                        Propagate->GetEuler(ePsi) );
587
588     _set_Alpha( Auxiliary->Getalpha() );
589     _set_Beta( Auxiliary->Getbeta() );
590
591
592     _set_Gamma_vert_rad( Auxiliary->GetGamma() );
593
594     _set_Earth_position_angle( Auxiliary->GetEarthPositionAngle() );
595
596     _set_Climb_Rate( Propagate->Gethdot() );
597
598     const FGMatrix33& Tl2b = Propagate->GetTl2b();
599     for ( i = 1; i <= 3; i++ ) {
600         for ( j = 1; j <= 3; j++ ) {
601             _set_T_Local_to_Body( i, j, Tl2b(i,j) );
602         }
603     }
604
605     // Copy the engine values from JSBSim.
606     for ( i=0; i < Propulsion->GetNumEngines(); i++ ) {
607       SGPropertyNode * node = fgGetNode("engines/engine", i, true);
608       char buf[30];
609       sprintf(buf, "engines/engine[%d]/thruster", i);
610       SGPropertyNode * tnode = fgGetNode(buf, true);
611       FGThruster * thruster = Propulsion->GetEngine(i)->GetThruster();
612
613       switch (Propulsion->GetEngine(i)->GetType()) {
614       case FGEngine::etPiston:
615         { // FGPiston code block
616         FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
617         node->setDoubleValue("egt-degf", eng->getExhaustGasTemp_degF());
618         node->setDoubleValue("oil-temperature-degf", eng->getOilTemp_degF());
619         node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
620         node->setDoubleValue("mp-osi", eng->getManifoldPressure_inHg());
621         node->setDoubleValue("cht-degf", eng->getCylinderHeadTemp_degF());
622         node->setDoubleValue("rpm", eng->getRPM());
623         } // end FGPiston code block
624         break;
625       case FGEngine::etRocket:
626         { // FGRocket code block
627         FGRocket* eng = (FGRocket*)Propulsion->GetEngine(i);
628         } // end FGRocket code block
629         break;
630       case FGEngine::etTurbine:
631         { // FGTurbine code block
632         FGTurbine* eng = (FGTurbine*)Propulsion->GetEngine(i);
633         node->setDoubleValue("n1", eng->GetN1());
634         node->setDoubleValue("n2", eng->GetN2());
635         node->setDoubleValue("egt_degf", 32 + eng->GetEGT()*9/5);
636         node->setBoolValue("augmentation", eng->GetAugmentation());
637         node->setBoolValue("water-injection", eng->GetInjection());
638         node->setBoolValue("ignition", eng->GetIgnition());
639         node->setDoubleValue("nozzle-pos-norm", eng->GetNozzle());
640         node->setDoubleValue("inlet-pos-norm", eng->GetInlet());
641         node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
642         node->setBoolValue("reversed", eng->GetReversed());
643         node->setBoolValue("cutoff", eng->GetCutoff());
644         node->setDoubleValue("epr", eng->GetEPR());
645         globals->get_controls()->set_reverser(i, eng->GetReversed() );
646         globals->get_controls()->set_cutoff(i, eng->GetCutoff() );
647         globals->get_controls()->set_water_injection(i, eng->GetInjection() );
648         globals->get_controls()->set_augmentation(i, eng->GetAugmentation() );
649         } // end FGTurbine code block
650         break;
651       case FGEngine::etElectric:
652         { // FGElectric code block
653         FGElectric* eng = (FGElectric*)Propulsion->GetEngine(i);
654         node->setDoubleValue("rpm", eng->getRPM());
655         } // end FGElectric code block
656         break;
657       }
658
659       { // FGEngine code block
660       FGEngine* eng = Propulsion->GetEngine(i);
661       node->setDoubleValue("fuel-flow-gph", eng->getFuelFlow_gph());
662       node->setDoubleValue("thrust_lb", thruster->GetThrust());
663       node->setDoubleValue("fuel-flow_pph", eng->getFuelFlow_pph());
664       node->setBoolValue("running", eng->GetRunning());
665       node->setBoolValue("starter", eng->GetStarter());
666       node->setBoolValue("cranking", eng->GetCranking());
667       globals->get_controls()->set_starter(i, eng->GetStarter() );
668       } // end FGEngine code block
669
670       switch (thruster->GetType()) {
671       case FGThruster::ttNozzle:
672         { // FGNozzle code block
673         FGNozzle* noz = (FGNozzle*)thruster;
674         } // end FGNozzle code block
675         break;
676       case FGThruster::ttPropeller:
677         { // FGPropeller code block
678         FGPropeller* prop = (FGPropeller*)thruster;
679         tnode->setDoubleValue("rpm", thruster->GetRPM());
680         tnode->setDoubleValue("pitch", prop->GetPitch());
681         tnode->setDoubleValue("torque", prop->GetTorque());
682         } // end FGPropeller code block
683         break;
684       case FGThruster::ttRotor:
685         { // FGRotor code block
686         FGRotor* rotor = (FGRotor*)thruster;
687         } // end FGRotor code block
688         break;
689       case FGThruster::ttDirect:
690         { // Direct code block
691         } // end Direct code block
692         break;
693       }
694
695     }
696
697     // Copy the fuel levels from JSBSim if fuel
698     // freeze not enabled.
699     if ( ! Propulsion->GetFuelFreeze() ) {
700       for (i = 0; i < Propulsion->GetNumTanks(); i++) {
701         SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
702         FGTank* tank = Propulsion->GetTank(i);
703         double contents = tank->GetContents();
704         double temp = tank->GetTemperature_degC();
705         node->setDoubleValue("level-gal_us", contents/6.6);
706         node->setDoubleValue("level-lb", contents);
707         if (temp != -9999.0) node->setDoubleValue("temperature_degC", temp);
708       }
709     }
710
711     update_gear();
712
713     stall_warning->setDoubleValue( Aerodynamics->GetStallWarn() );
714
715     elevator_pos_pct->setDoubleValue( FCS->GetDePos(ofNorm) );
716     left_aileron_pos_pct->setDoubleValue( FCS->GetDaLPos(ofNorm) );
717     right_aileron_pos_pct->setDoubleValue( FCS->GetDaRPos(ofNorm) );
718     rudder_pos_pct->setDoubleValue( -1*FCS->GetDrPos(ofNorm) );
719     flap_pos_pct->setDoubleValue( FCS->GetDfPos(ofNorm) );
720     speedbrake_pos_pct->setDoubleValue( FCS->GetDsbPos(ofNorm) );
721     spoilers_pos_pct->setDoubleValue( FCS->GetDspPos(ofNorm) );
722
723     return true;
724 }
725
726
727 bool FGJSBsim::ToggleDataLogging(void)
728 {
729     return fdmex->GetOutput()->Toggle();
730 }
731
732
733 bool FGJSBsim::ToggleDataLogging(bool state)
734 {
735     if (state) {
736       fdmex->GetOutput()->Enable();
737       return true;
738     } else {
739       fdmex->GetOutput()->Disable();
740       return false;
741     }
742 }
743
744
745 //Positions
746 void FGJSBsim::set_Latitude(double lat)
747 {
748     static const SGPropertyNode *altitude = fgGetNode("/position/altitude-ft");
749     double alt;
750     double sea_level_radius_meters, lat_geoc;
751
752     // In case we're not trimming
753     FGInterface::set_Latitude(lat);
754
755     if ( altitude->getDoubleValue() > -9990 ) {
756       alt = altitude->getDoubleValue();
757     } else {
758       alt = 0.0;
759     }
760
761     update_ic();
762     SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Latitude: " << lat );
763     SG_LOG(SG_FLIGHT,SG_INFO," cur alt (ft) =  " << alt );
764
765     sgGeodToGeoc( lat, alt * SG_FEET_TO_METER,
766                       &sea_level_radius_meters, &lat_geoc );
767     _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET  );
768     fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET  );
769     _set_Runway_altitude( cur_fdm_state->get_Runway_altitude() );
770     fgic->SetTerrainAltitudeFtIC( cur_fdm_state->get_ground_elev_ft() );
771     fgic->SetLatitudeRadIC( lat_geoc );
772     needTrim=true;
773 }
774
775
776 void FGJSBsim::set_Longitude(double lon)
777 {
778     SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Longitude: " << lon );
779
780     // In case we're not trimming
781     FGInterface::set_Longitude(lon);
782
783     update_ic();
784     fgic->SetLongitudeRadIC( lon );
785     _set_Runway_altitude( cur_fdm_state->get_Runway_altitude() );
786     fgic->SetTerrainAltitudeFtIC( cur_fdm_state->get_ground_elev_ft() );
787     needTrim=true;
788 }
789
790 void FGJSBsim::set_Altitude(double alt)
791 {
792     static const SGPropertyNode *latitude = fgGetNode("/position/latitude-deg");
793
794     double sea_level_radius_meters,lat_geoc;
795
796     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Altitude: " << alt );
797     SG_LOG(SG_FLIGHT,SG_INFO, "  lat (deg) = " << latitude->getDoubleValue() );
798
799     // In case we're not trimming
800     FGInterface::set_Altitude(alt);
801
802     update_ic();
803     sgGeodToGeoc( latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS, alt,
804                   &sea_level_radius_meters, &lat_geoc);
805     _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET  );
806     fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET );
807     _set_Runway_altitude( cur_fdm_state->get_Runway_altitude() );
808     fgic->SetTerrainAltitudeFtIC( cur_fdm_state->get_ground_elev_ft() );
809     SG_LOG(SG_FLIGHT, SG_INFO,
810           "Terrain altitude: " << cur_fdm_state->get_Runway_altitude() * SG_METER_TO_FEET );
811     fgic->SetLatitudeRadIC( lat_geoc );
812     fgic->SetAltitudeFtIC(alt);
813     needTrim=true;
814 }
815
816 void FGJSBsim::set_V_calibrated_kts(double vc)
817 {
818     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_V_calibrated_kts: " <<  vc );
819
820     // In case we're not trimming
821     FGInterface::set_V_calibrated_kts(vc);
822
823     update_ic();
824     fgic->SetVcalibratedKtsIC(vc);
825     needTrim=true;
826 }
827
828 void FGJSBsim::set_Mach_number(double mach)
829 {
830     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Mach_number: " <<  mach );
831
832     // In case we're not trimming
833     FGInterface::set_Mach_number(mach);
834
835     update_ic();
836     fgic->SetMachIC(mach);
837     needTrim=true;
838 }
839
840 void FGJSBsim::set_Velocities_Local( double north, double east, double down )
841 {
842     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Local: "
843        << north << ", " <<  east << ", " << down );
844
845     // In case we're not trimming
846     FGInterface::set_Velocities_Local(north, east, down);
847
848     update_ic();
849     fgic->SetVnorthFpsIC(north);
850     fgic->SetVeastFpsIC(east);
851     fgic->SetVdownFpsIC(down);
852     needTrim=true;
853 }
854
855 void FGJSBsim::set_Velocities_Wind_Body( double u, double v, double w)
856 {
857     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Wind_Body: "
858        << u << ", " <<  v << ", " <<  w );
859
860     // In case we're not trimming
861     FGInterface::set_Velocities_Wind_Body(u, v, w);
862
863     update_ic();
864     fgic->SetUBodyFpsIC(u);
865     fgic->SetVBodyFpsIC(v);
866     fgic->SetWBodyFpsIC(w);
867     needTrim=true;
868 }
869
870 //Euler angles
871 void FGJSBsim::set_Euler_Angles( double phi, double theta, double psi )
872 {
873     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Euler_Angles: "
874        << phi << ", " << theta << ", " << psi );
875
876     // In case we're not trimming
877     FGInterface::set_Euler_Angles(phi, theta, psi);
878
879     update_ic();
880     fgic->SetPitchAngleRadIC(theta);
881     fgic->SetRollAngleRadIC(phi);
882     fgic->SetTrueHeadingRadIC(psi);
883     needTrim=true;
884 }
885
886 //Flight Path
887 void FGJSBsim::set_Climb_Rate( double roc)
888 {
889     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Climb_Rate: " << roc );
890
891     // In case we're not trimming
892     FGInterface::set_Climb_Rate(roc);
893
894     update_ic();
895     //since both climb rate and flight path angle are set in the FG
896     //startup sequence, something is needed to keep one from cancelling
897     //out the other.
898     if( !(fabs(roc) > 1 && fabs(fgic->GetFlightPathAngleRadIC()) < 0.01) ) {
899       fgic->SetClimbRateFpsIC(roc);
900     }
901     needTrim=true;
902 }
903
904 void FGJSBsim::set_Gamma_vert_rad( double gamma)
905 {
906     SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Gamma_vert_rad: " << gamma );
907
908     update_ic();
909     if( !(fabs(gamma) < 0.01 && fabs(fgic->GetClimbRateFpsIC()) > 1) ) {
910       fgic->SetFlightPathAngleRadIC(gamma);
911     }
912     needTrim=true;
913 }
914
915 void FGJSBsim::init_gear(void )
916 {
917     FGGroundReactions* gr=fdmex->GetGroundReactions();
918     int Ngear=GroundReactions->GetNumGearUnits();
919     for (int i=0;i<Ngear;i++) {
920       FGLGear *gear = gr->GetGearUnit(i);
921       SGPropertyNode * node = fgGetNode("gear/gear", i, true);
922       node->setDoubleValue("xoffset-in", gear->GetBodyLocation()(1));
923       node->setDoubleValue("yoffset-in", gear->GetBodyLocation()(2));
924       node->setDoubleValue("zoffset-in", gear->GetBodyLocation()(3));
925       node->setBoolValue("wow", gear->GetWOW());
926       node->setBoolValue("has-brake", gear->GetBrakeGroup() > 0);
927       node->setDoubleValue("position-norm", FCS->GetGearPos());
928       node->setDoubleValue("tire-pressure-norm", gear->GetTirePressure());
929       if ( gear->GetSteerable() )
930         node->setDoubleValue("steering-norm", gear->GetSteerNorm());
931     }
932 }
933
934 void FGJSBsim::update_gear(void)
935 {
936     FGGroundReactions* gr=fdmex->GetGroundReactions();
937     int Ngear=GroundReactions->GetNumGearUnits();
938     for (int i=0;i<Ngear;i++) {
939       FGLGear *gear = gr->GetGearUnit(i);
940       SGPropertyNode * node = fgGetNode("gear/gear", i, true);
941       node->getChild("wow", 0, true)->setBoolValue( gear->GetWOW());
942       node->getChild("position-norm", 0, true)->setDoubleValue(FCS->GetGearPos());
943       gear->SetTirePressure(node->getDoubleValue("tire-pressure-norm"));
944       if ( gear->GetSteerable() )
945         node->setDoubleValue("steering-norm", gear->GetSteerNorm());
946     }
947 }
948
949 void FGJSBsim::do_trim(void)
950 {
951   FGTrim *fgtrim;
952
953   if ( fgGetBool("/sim/presets/onground") )
954   {
955     fgic->SetVcalibratedKtsIC(0.0);
956     fgtrim = new FGTrim(fdmex,tGround);
957   } else {
958     fgtrim = new FGTrim(fdmex,tLongitudinal);
959   }
960
961   if ( !fgtrim->DoTrim() ) {
962     fgtrim->Report();
963     fgtrim->TrimStats();
964   } else {
965     trimmed->setBoolValue(true);
966   }
967   if (FGJSBBase::debug_lvl > 0)
968       State->ReportState();
969
970   delete fgtrim;
971
972   pitch_trim->setDoubleValue( FCS->GetPitchTrimCmd() );
973   throttle_trim->setDoubleValue( FCS->GetThrottleCmd(0) );
974   aileron_trim->setDoubleValue( FCS->GetDaCmd() );
975   rudder_trim->setDoubleValue( FCS->GetDrCmd() );
976
977   globals->get_controls()->set_elevator_trim(FCS->GetPitchTrimCmd());
978   globals->get_controls()->set_elevator(FCS->GetDeCmd());
979   globals->get_controls()->set_throttle(FGControls::ALL_ENGINES,
980   FCS->GetThrottleCmd(0));
981
982   globals->get_controls()->set_aileron(FCS->GetDaCmd());
983   globals->get_controls()->set_rudder( FCS->GetDrCmd());
984
985   SG_LOG( SG_FLIGHT, SG_INFO, "  Trim complete" );
986 }
987
988 void FGJSBsim::update_ic(void)
989 {
990    if ( !needTrim ) {
991      fgic->SetLatitudeRadIC(get_Lat_geocentric() );
992      fgic->SetLongitudeRadIC( get_Longitude() );
993      fgic->SetAltitudeFtIC( get_Altitude() );
994      fgic->SetVcalibratedKtsIC( get_V_calibrated_kts() );
995      fgic->SetPitchAngleRadIC( get_Theta() );
996      fgic->SetRollAngleRadIC( get_Phi() );
997      fgic->SetTrueHeadingRadIC( get_Psi() );
998      fgic->SetClimbRateFpsIC( get_Climb_Rate() );
999    }
1000 }
1001