1 // JSBsim.cxx -- interface to the JSBsim flight model
3 // Written by Curtis Olson, started February 1999.
5 // Copyright (C) 1999 Curtis L. Olson - curt@flightgear.org
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.
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.
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.
28 #include <simgear/compiler.h>
30 #include <stdio.h> // size_t
33 #include <simgear/constants.h>
34 #include <simgear/debug/logstream.hxx>
35 #include <simgear/math/sg_geodesy.hxx>
36 #include <simgear/misc/sg_path.hxx>
37 #include <simgear/structure/commands.hxx>
39 #include <FDM/flight.hxx>
41 #include <Aircraft/aircraft.hxx>
42 #include <Aircraft/controls.hxx>
43 #include <Main/globals.hxx>
44 #include <Main/fg_props.hxx>
47 #include <FDM/JSBSim/FGFDMExec.h>
48 #include <FDM/JSBSim/FGJSBBase.h>
49 #include <FDM/JSBSim/FGState.h>
50 #include <FDM/JSBSim/initialization/FGInitialCondition.h>
51 #include <FDM/JSBSim/initialization/FGTrim.h>
52 #include <FDM/JSBSim/models/FGModel.h>
53 #include <FDM/JSBSim/models/FGAircraft.h>
54 #include <FDM/JSBSim/models/FGFCS.h>
55 #include <FDM/JSBSim/models/FGPropagate.h>
56 #include <FDM/JSBSim/models/FGAuxiliary.h>
57 #include <FDM/JSBSim/models/FGInertial.h>
58 #include <FDM/JSBSim/models/FGAtmosphere.h>
59 #include <FDM/JSBSim/models/FGMassBalance.h>
60 #include <FDM/JSBSim/models/FGAerodynamics.h>
61 #include <FDM/JSBSim/models/FGLGear.h>
62 #include <FDM/JSBSim/models/propulsion/FGEngine.h>
63 #include <FDM/JSBSim/models/propulsion/FGPiston.h>
64 #include <FDM/JSBSim/models/propulsion/FGTurbine.h>
65 #include <FDM/JSBSim/models/propulsion/FGTurboProp.h>
66 #include <FDM/JSBSim/models/propulsion/FGRocket.h>
67 #include <FDM/JSBSim/models/propulsion/FGElectric.h>
68 #include <FDM/JSBSim/models/propulsion/FGNozzle.h>
69 #include <FDM/JSBSim/models/propulsion/FGPropeller.h>
70 #include <FDM/JSBSim/models/propulsion/FGRotor.h>
71 #include <FDM/JSBSim/models/propulsion/FGTank.h>
72 #include <FDM/JSBSim/input_output/FGPropertyManager.h>
73 #include <FDM/JSBSim/input_output/FGGroundCallback.h>
75 using namespace JSBSim;
78 FMAX (double a, double b)
83 class FGFSGroundCallback : public FGGroundCallback {
85 FGFSGroundCallback(FGJSBsim* ifc) : mInterface(ifc) {}
86 virtual ~FGFSGroundCallback() {}
88 /** Get the altitude above sea level depenent on the location. */
89 virtual double GetAltitude(const FGLocation& l) const {
90 double pt[3] = { SG_FEET_TO_METER*l(eX),
91 SG_FEET_TO_METER*l(eY),
92 SG_FEET_TO_METER*l(eZ) };
94 sgCartToGeod( pt, &lat, &lon, &alt);
95 return alt * SG_METER_TO_FEET;
98 /** Compute the altitude above ground. */
99 virtual double GetAGLevel(double t, const FGLocation& l,
101 FGColumnVector3& n, FGColumnVector3& v) const {
102 double loc_cart[3] = { l(eX), l(eY), l(eZ) };
103 double contact[3], normal[3], vel[3], agl = 0;
104 mInterface->get_agl_ft(t, loc_cart, SG_METER_TO_FEET*2, contact, normal,
106 n = l.GetTec2l()*FGColumnVector3( normal[0], normal[1], normal[2] );
107 v = l.GetTec2l()*FGColumnVector3( vel[0], vel[1], vel[2] );
108 cont = FGColumnVector3( contact[0], contact[1], contact[2] );
112 FGJSBsim* mInterface;
115 /******************************************************************************/
117 FGJSBsim::FGJSBsim( double dt )
118 : FGInterface(dt), got_wire(false)
121 // Set up the debugging level
122 // FIXME: this will not respond to
125 // if flight is excluded, don't bother
126 if ((logbuf::get_log_classes() & SG_FLIGHT) != 0) {
128 // do a rough-and-ready mapping to
129 // the levels documented in FGFDMExec.h
130 switch (logbuf::get_log_priority()) {
132 FGJSBBase::debug_lvl = 0x1f;
135 FGJSBBase::debug_lvl = 0x0f;
137 FGJSBBase::debug_lvl = 0x01;
141 FGJSBBase::debug_lvl = 0x00;
146 fdmex = new FGFDMExec( (FGPropertyManager*)globals->get_props() );
148 // Register ground callback.
149 fdmex->SetGroundCallback( new FGFSGroundCallback(this) );
151 State = fdmex->GetState();
152 Atmosphere = fdmex->GetAtmosphere();
153 FCS = fdmex->GetFCS();
154 MassBalance = fdmex->GetMassBalance();
155 Propulsion = fdmex->GetPropulsion();
156 Aircraft = fdmex->GetAircraft();
157 Propagate = fdmex->GetPropagate();
158 Auxiliary = fdmex->GetAuxiliary();
159 Inertial = fdmex->GetInertial();
160 Aerodynamics = fdmex->GetAerodynamics();
161 GroundReactions = fdmex->GetGroundReactions();
166 SGPath aircraft_path( fgGetString("/sim/aircraft-dir") );
168 SGPath engine_path( fgGetString("/sim/aircraft-dir") );
169 engine_path.append( "Engine" );
171 SGPath systems_path( fgGetString("/sim/aircraft-dir") );
172 systems_path.append( "Systems" );
176 result = fdmex->LoadModel( aircraft_path.str(),
179 fgGetString("/sim/aero"), false );
182 SG_LOG( SG_FLIGHT, SG_INFO, " loaded aero.");
184 SG_LOG( SG_FLIGHT, SG_INFO,
185 " aero does not exist (you may have mis-typed the name).");
189 SG_LOG( SG_FLIGHT, SG_INFO, "" );
190 SG_LOG( SG_FLIGHT, SG_INFO, "" );
191 SG_LOG( SG_FLIGHT, SG_INFO, "After loading aero definition file ..." );
193 int Neng = Propulsion->GetNumEngines();
194 SG_LOG( SG_FLIGHT, SG_INFO, "num engines = " << Neng );
196 if ( GroundReactions->GetNumGearUnits() <= 0 ) {
197 SG_LOG( SG_FLIGHT, SG_ALERT, "num gear units = "
198 << GroundReactions->GetNumGearUnits() );
199 SG_LOG( SG_FLIGHT, SG_ALERT, "This is a very bad thing because with 0 gear units, the ground trimming");
200 SG_LOG( SG_FLIGHT, SG_ALERT, "routine (coming up later in the code) will core dump.");
201 SG_LOG( SG_FLIGHT, SG_ALERT, "Halting the sim now, and hoping a solution will present itself soon!");
207 // Set initial fuel levels if provided.
208 for (unsigned int i = 0; i < Propulsion->GetNumTanks(); i++) {
209 SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
210 if (node->getChild("level-gal_us", 0, false) != 0) {
211 Propulsion->GetTank(i)->SetContents(node->getDoubleValue("level-gal_us") * 6.6);
213 node->setDoubleValue("level-lbs", Propulsion->GetTank(i)->GetContents());
214 node->setDoubleValue("level-gal_us", Propulsion->GetTank(i)->GetContents() / 6.6);
216 node->setDoubleValue("capacity-gal_us",
217 Propulsion->GetTank(i)->GetCapacity() / 6.6);
219 Propulsion->SetFuelFreeze((fgGetNode("/sim/freeze/fuel",true))->getBoolValue());
221 fgSetDouble("/fdm/trim/pitch-trim", FCS->GetPitchTrimCmd());
222 fgSetDouble("/fdm/trim/throttle", FCS->GetThrottleCmd(0));
223 fgSetDouble("/fdm/trim/aileron", FCS->GetDaCmd());
224 fgSetDouble("/fdm/trim/rudder", FCS->GetDrCmd());
226 startup_trim = fgGetNode("/sim/presets/trim", true);
228 trimmed = fgGetNode("/fdm/trim/trimmed", true);
229 trimmed->setBoolValue(false);
231 pitch_trim = fgGetNode("/fdm/trim/pitch-trim", true );
232 throttle_trim = fgGetNode("/fdm/trim/throttle", true );
233 aileron_trim = fgGetNode("/fdm/trim/aileron", true );
234 rudder_trim = fgGetNode("/fdm/trim/rudder", true );
236 stall_warning = fgGetNode("/sim/alarms/stall-warning",true);
237 stall_warning->setDoubleValue(0);
240 flap_pos_pct=fgGetNode("/surface-positions/flap-pos-norm",true);
241 elevator_pos_pct=fgGetNode("/surface-positions/elevator-pos-norm",true);
243 =fgGetNode("/surface-positions/left-aileron-pos-norm",true);
244 right_aileron_pos_pct
245 =fgGetNode("/surface-positions/right-aileron-pos-norm",true);
246 rudder_pos_pct=fgGetNode("/surface-positions/rudder-pos-norm",true);
248 =fgGetNode("/surface-positions/speedbrake-pos-norm",true);
249 spoilers_pos_pct=fgGetNode("/surface-positions/spoilers-pos-norm",true);
250 tailhook_pos_pct=fgGetNode("/gear/tailhook/position-norm",true);
251 wing_fold_pos_pct=fgGetNode("surface-positions/wing-fold-pos-norm",true);
253 elevator_pos_pct->setDoubleValue(0);
254 left_aileron_pos_pct->setDoubleValue(0);
255 right_aileron_pos_pct->setDoubleValue(0);
256 rudder_pos_pct->setDoubleValue(0);
257 flap_pos_pct->setDoubleValue(0);
258 speedbrake_pos_pct->setDoubleValue(0);
259 spoilers_pos_pct->setDoubleValue(0);
261 temperature = fgGetNode("/environment/temperature-degc",true);
262 pressure = fgGetNode("/environment/pressure-inhg",true);
263 density = fgGetNode("/environment/density-slugft3",true);
264 turbulence_gain = fgGetNode("/environment/turbulence/magnitude-norm",true);
265 turbulence_rate = fgGetNode("/environment/turbulence/rate-hz",true);
267 wind_from_north= fgGetNode("/environment/wind-from-north-fps",true);
268 wind_from_east = fgGetNode("/environment/wind-from-east-fps" ,true);
269 wind_from_down = fgGetNode("/environment/wind-from-down-fps" ,true);
271 slaved = fgGetNode("/sim/slaved/enabled", true);
273 for (unsigned int i = 0; i < Propulsion->GetNumEngines(); i++) {
274 SGPropertyNode * node = fgGetNode("engines/engine", i, true);
275 Propulsion->GetEngine(i)->GetThruster()->SetRPM(node->getDoubleValue("rpm") /
276 Propulsion->GetEngine(i)->GetThruster()->GetGearRatio());
279 hook_root_struct = FGColumnVector3(
280 fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-offset-x-in", 196),
281 fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-offset-y-in", 0),
282 fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-offset-z-in", -16));
284 // Untie the write-state-file property to avoid creating an initfile.xml
285 // file on each reset.
286 fgGetNode("/fdm/jsbsim/simulation/write-state-file")->untie();
291 /******************************************************************************/
292 FGJSBsim::~FGJSBsim(void)
297 /******************************************************************************/
299 // Initialize the JSBsim flight model, dt is the time increment for
300 // each subsequent iteration through the EOM
302 void FGJSBsim::init()
306 SG_LOG( SG_FLIGHT, SG_INFO, "Starting and initializing JSBsim" );
308 // Explicitly call the superclass's
309 // init method first.
311 if (fgGetBool("/environment/params/control-fdm-atmosphere")) {
312 Atmosphere->UseExternal();
313 Atmosphere->SetExTemperature(
314 9.0/5.0*(temperature->getDoubleValue()+273.15) );
315 Atmosphere->SetExPressure(pressure->getDoubleValue()*70.726566);
316 Atmosphere->SetExDensity(density->getDoubleValue());
317 Atmosphere->SetTurbType(FGAtmosphere::ttCulp);
318 Atmosphere->SetTurbGain(turbulence_gain->getDoubleValue());
319 Atmosphere->SetTurbRate(turbulence_rate->getDoubleValue());
322 Atmosphere->UseInternal();
325 fgic->SetVNorthFpsIC( wind_from_north->getDoubleValue() );
326 fgic->SetVEastFpsIC( wind_from_east->getDoubleValue() );
327 fgic->SetVDownFpsIC( wind_from_down->getDoubleValue() );
329 //Atmosphere->SetExTemperature(get_Static_temperature());
330 //Atmosphere->SetExPressure(get_Static_pressure());
331 //Atmosphere->SetExDensity(get_Density());
332 SG_LOG(SG_FLIGHT,SG_INFO,"T,p,rho: " << fdmex->GetAtmosphere()->GetTemperature()
333 << ", " << fdmex->GetAtmosphere()->GetPressure()
334 << ", " << fdmex->GetAtmosphere()->GetDensity() );
336 if (fgGetBool("/sim/presets/running")) {
337 for (int i=0; i < Propulsion->GetNumEngines(); i++) {
338 SGPropertyNode * node = fgGetNode("engines/engine", i, true);
339 node->setBoolValue("running", true);
340 Propulsion->GetEngine(i)->SetRunning(true);
344 FCS->SetDfPos( ofNorm, globals->get_controls()->get_flaps() );
349 fdmex->RunIC(); //loop JSBSim once w/o integrating
350 copy_from_JSBsim(); //update the bus
352 SG_LOG( SG_FLIGHT, SG_INFO, " Initialized JSBSim with:" );
354 switch(fgic->GetSpeedSet()) {
356 SG_LOG(SG_FLIGHT,SG_INFO, " Vn,Ve,Vd= "
357 << Propagate->GetVel(FGJSBBase::eNorth) << ", "
358 << Propagate->GetVel(FGJSBBase::eEast) << ", "
359 << Propagate->GetVel(FGJSBBase::eDown) << " ft/s");
362 SG_LOG(SG_FLIGHT,SG_INFO, " U,V,W= "
363 << Propagate->GetUVW(1) << ", "
364 << Propagate->GetUVW(2) << ", "
365 << Propagate->GetUVW(3) << " ft/s");
368 SG_LOG(SG_FLIGHT,SG_INFO, " Mach: "
369 << Auxiliary->GetMach() );
373 SG_LOG(SG_FLIGHT,SG_INFO, " Indicated Airspeed: "
374 << Auxiliary->GetVcalibratedKTS() << " knots" );
378 stall_warning->setDoubleValue(0);
380 SG_LOG( SG_FLIGHT, SG_INFO, " Bank Angle: "
381 << Propagate->GetEuler(FGJSBBase::ePhi)*RADTODEG << " deg" );
382 SG_LOG( SG_FLIGHT, SG_INFO, " Pitch Angle: "
383 << Propagate->GetEuler(FGJSBBase::eTht)*RADTODEG << " deg" );
384 SG_LOG( SG_FLIGHT, SG_INFO, " True Heading: "
385 << Propagate->GetEuler(FGJSBBase::ePsi)*RADTODEG << " deg" );
386 SG_LOG( SG_FLIGHT, SG_INFO, " Latitude: "
387 << Propagate->GetLocation().GetLatitudeDeg() << " deg" );
388 SG_LOG( SG_FLIGHT, SG_INFO, " Longitude: "
389 << Propagate->GetLocation().GetLongitudeDeg() << " deg" );
390 SG_LOG( SG_FLIGHT, SG_INFO, " Altitude: "
391 << Propagate->Geth() << " feet" );
392 SG_LOG( SG_FLIGHT, SG_INFO, " loaded initial conditions" );
394 SG_LOG( SG_FLIGHT, SG_INFO, " set dt" );
396 SG_LOG( SG_FLIGHT, SG_INFO, "Finished initializing JSBSim" );
398 SG_LOG( SG_FLIGHT, SG_INFO, "FGControls::get_gear_down()= " <<
399 globals->get_controls()->get_gear_down() );
402 /******************************************************************************/
404 // Run an iteration of the EOM (equations of motion)
406 void FGJSBsim::update( double dt )
409 if(!fgGetBool("/sim/crashed"))
410 fgSetBool("/sim/crashed", true);
417 int multiloop = _calc_multiloop(dt);
421 // Compute the radius of the aircraft. That is the radius of a ball
422 // where all gear units are in. At the moment it is at least 10ft ...
424 int n_gears = GroundReactions->GetNumGearUnits();
425 for (i=0; i<n_gears; ++i) {
426 FGColumnVector3 bl = GroundReactions->GetGearUnit(i)->GetBodyLocation();
427 double r = bl.Magnitude();
432 // Compute the potential movement of this aircraft and query for the
433 // ground in this area.
434 double groundCacheRadius = acrad + 2*dt*Propagate->GetUVW().Magnitude();
435 double alt, slr, lat, lon;
436 FGColumnVector3 cart = Auxiliary->GetLocationVRP();
437 if ( needTrim && startup_trim->getBoolValue() ) {
438 alt = fgic->GetAltitudeFtIC();
439 slr = fgic->GetSeaLevelRadiusFtIC();
440 lat = fgic->GetLatitudeDegIC() * SGD_DEGREES_TO_RADIANS;
441 lon = fgic->GetLongitudeDegIC() * SGD_DEGREES_TO_RADIANS;
442 cart = FGLocation(lon, lat, alt+slr);
444 double cart_pos[3] = { cart(1), cart(2), cart(3) };
445 bool cache_ok = prepare_ground_cache_ft( State->Getsim_time(), cart_pos,
448 SG_LOG(SG_FLIGHT, SG_WARN,
449 "FGInterface is being called without scenery below the aircraft!");
450 SG_LOG(SG_FLIGHT, SG_WARN,
451 "altitude = " << alt);
452 SG_LOG(SG_FLIGHT, SG_WARN,
453 "sea level radius = " << slr);
454 SG_LOG(SG_FLIGHT, SG_WARN,
455 "latitude = " << lat);
456 SG_LOG(SG_FLIGHT, SG_WARN,
457 "longitude = " << lon);
463 trimmed->setBoolValue(false);
466 if ( startup_trim->getBoolValue() ) {
467 double contact[3], d[3], agl;
468 get_agl_ft(State->Getsim_time(), cart_pos, SG_METER_TO_FEET*2, contact,
470 double terrain_alt = sqrt(contact[0]*contact[0] + contact[1]*contact[1]
471 + contact[2]*contact[2]) - fgic->GetSeaLevelRadiusFtIC();
473 SG_LOG(SG_FLIGHT, SG_INFO,
474 "Ready to trim, terrain altitude is: "
475 << terrain_alt * SG_METER_TO_FEET );
477 fgic->SetTerrainAltitudeFtIC( terrain_alt );
480 fdmex->RunIC(); //apply any changes made through the set_ functions
485 for ( i=0; i < multiloop; i++ ) {
487 update_external_forces(State->Getsim_time() + i * State->Getdt());
490 FGJSBBase::Message* msg;
491 while (fdmex->SomeMessages()) {
492 msg = fdmex->ProcessMessage();
494 case FGJSBBase::Message::eText:
495 if (msg->text == "Crash Detected: Simulation FREEZE.")
497 SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text );
499 case FGJSBBase::Message::eBool:
500 SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->bVal );
502 case FGJSBBase::Message::eInteger:
503 SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->iVal );
505 case FGJSBBase::Message::eDouble:
506 SG_LOG( SG_FLIGHT, SG_INFO, msg->messageId << ": " << msg->text << " " << msg->dVal );
509 SG_LOG( SG_FLIGHT, SG_INFO, "Unrecognized message type." );
514 // translate JSBsim back to FG structure so that the
515 // autopilot (and the rest of the sim can use the updated values
519 /******************************************************************************/
521 // Convert from the FGInterface struct to the JSBsim generic_ struct
523 bool FGJSBsim::copy_to_JSBsim()
528 // copy control positions into the JSBsim structure
530 FCS->SetDaCmd( globals->get_controls()->get_aileron());
531 FCS->SetRollTrimCmd( globals->get_controls()->get_aileron_trim() );
532 FCS->SetDeCmd( globals->get_controls()->get_elevator());
533 FCS->SetPitchTrimCmd( globals->get_controls()->get_elevator_trim() );
534 FCS->SetDrCmd( -globals->get_controls()->get_rudder() );
535 FCS->SetYawTrimCmd( -globals->get_controls()->get_rudder_trim() );
536 FCS->SetDsCmd( globals->get_controls()->get_rudder() );
537 FCS->SetDfCmd( globals->get_controls()->get_flaps() );
538 FCS->SetDsbCmd( globals->get_controls()->get_speedbrake() );
539 FCS->SetDspCmd( globals->get_controls()->get_spoilers() );
541 // Parking brake sets minimum braking
543 double parking_brake = globals->get_controls()->get_brake_parking();
544 FCS->SetLBrake(FMAX(globals->get_controls()->get_brake_left(), parking_brake));
545 FCS->SetRBrake(FMAX(globals->get_controls()->get_brake_right(), parking_brake));
546 FCS->SetCBrake( 0.0 );
547 // FCS->SetCBrake( globals->get_controls()->get_brake(2) );
549 FCS->SetGearCmd( globals->get_controls()->get_gear_down());
550 for (i = 0; i < Propulsion->GetNumEngines(); i++) {
551 SGPropertyNode * node = fgGetNode("engines/engine", i, true);
553 FCS->SetThrottleCmd(i, globals->get_controls()->get_throttle(i));
554 FCS->SetMixtureCmd(i, globals->get_controls()->get_mixture(i));
555 FCS->SetPropAdvanceCmd(i, globals->get_controls()->get_prop_advance(i));
556 FCS->SetFeatherCmd(i, globals->get_controls()->get_feather(i));
558 switch (Propulsion->GetEngine(i)->GetType()) {
559 case FGEngine::etPiston:
560 { // FGPiston code block
561 FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
562 eng->SetMagnetos( globals->get_controls()->get_magnetos(i) );
564 } // end FGPiston code block
565 case FGEngine::etTurbine:
566 { // FGTurbine code block
567 FGTurbine* eng = (FGTurbine*)Propulsion->GetEngine(i);
568 eng->SetAugmentation( globals->get_controls()->get_augmentation(i) );
569 eng->SetReverse( globals->get_controls()->get_reverser(i) );
570 //eng->SetInjection( globals->get_controls()->get_water_injection(i) );
571 eng->SetCutoff( globals->get_controls()->get_cutoff(i) );
572 eng->SetIgnition( globals->get_controls()->get_ignition(i) );
574 } // end FGTurbine code block
575 case FGEngine::etRocket:
576 { // FGRocket code block
577 FGRocket* eng = (FGRocket*)Propulsion->GetEngine(i);
579 } // end FGRocket code block
580 case FGEngine::etTurboprop:
581 { // FGTurboProp code block
582 FGTurboProp* eng = (FGTurboProp*)Propulsion->GetEngine(i);
583 eng->SetReverse( globals->get_controls()->get_reverser(i) );
584 eng->SetCutoff( globals->get_controls()->get_cutoff(i) );
585 eng->SetIgnition( globals->get_controls()->get_ignition(i) );
587 eng->SetGeneratorPower( globals->get_controls()->get_generator_breaker(i) );
588 eng->SetCondition( globals->get_controls()->get_condition(i) );
590 } // end FGTurboProp code block
593 { // FGEngine code block
594 FGEngine* eng = Propulsion->GetEngine(i);
596 eng->SetStarter( globals->get_controls()->get_starter(i) );
597 eng->SetRunning( node->getBoolValue("running") );
598 } // end FGEngine code block
602 Propagate->SetSeaLevelRadius( get_Sea_level_radius() );
604 Atmosphere->SetExTemperature(
605 9.0/5.0*(temperature->getDoubleValue()+273.15) );
606 Atmosphere->SetExPressure(pressure->getDoubleValue()*70.726566);
607 Atmosphere->SetExDensity(density->getDoubleValue());
609 tmp = turbulence_gain->getDoubleValue();
610 //Atmosphere->SetTurbGain(tmp * tmp * 100.0);
612 tmp = turbulence_rate->getDoubleValue();
613 //Atmosphere->SetTurbRate(tmp);
615 Atmosphere->SetWindNED( wind_from_north->getDoubleValue(),
616 wind_from_east->getDoubleValue(),
617 wind_from_down->getDoubleValue() );
618 // SG_LOG(SG_FLIGHT,SG_INFO, "Wind NED: "
619 // << get_V_north_airmass() << ", "
620 // << get_V_east_airmass() << ", "
621 // << get_V_down_airmass() );
623 for (i = 0; i < Propulsion->GetNumTanks(); i++) {
624 SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
625 FGTank * tank = Propulsion->GetTank(i);
626 tank->SetContents(node->getDoubleValue("level-gal_us") * 6.6);
627 // tank->SetContents(node->getDoubleValue("level-lbs"));
630 Propulsion->SetFuelFreeze((fgGetNode("/sim/freeze/fuel",true))->getBoolValue());
631 fdmex->SetSlave(slaved->getBoolValue());
636 /******************************************************************************/
638 // Convert from the JSBsim generic_ struct to the FGInterface struct
640 bool FGJSBsim::copy_from_JSBsim()
644 _set_Inertias( MassBalance->GetMass(),
645 MassBalance->GetIxx(),
646 MassBalance->GetIyy(),
647 MassBalance->GetIzz(),
648 MassBalance->GetIxz() );
650 _set_CG_Position( MassBalance->GetXYZcg(1),
651 MassBalance->GetXYZcg(2),
652 MassBalance->GetXYZcg(3) );
654 _set_Accels_Body( Aircraft->GetBodyAccel(1),
655 Aircraft->GetBodyAccel(2),
656 Aircraft->GetBodyAccel(3) );
658 _set_Accels_CG_Body_N ( Aircraft->GetNcg(1),
660 Aircraft->GetNcg(3) );
662 _set_Accels_Pilot_Body( Auxiliary->GetPilotAccel(1),
663 Auxiliary->GetPilotAccel(2),
664 Auxiliary->GetPilotAccel(3) );
666 _set_Nlf( Aircraft->GetNlf() );
670 _set_Velocities_Local( Propagate->GetVel(FGJSBBase::eNorth),
671 Propagate->GetVel(FGJSBBase::eEast),
672 Propagate->GetVel(FGJSBBase::eDown) );
674 _set_Velocities_Wind_Body( Propagate->GetUVW(1),
675 Propagate->GetUVW(2),
676 Propagate->GetUVW(3) );
678 // Make the HUD work ...
679 _set_Velocities_Ground( Propagate->GetVel(FGJSBBase::eNorth),
680 Propagate->GetVel(FGJSBBase::eEast),
681 -Propagate->GetVel(FGJSBBase::eDown) );
683 _set_V_rel_wind( Auxiliary->GetVt() );
685 _set_V_equiv_kts( Auxiliary->GetVequivalentKTS() );
687 _set_V_calibrated_kts( Auxiliary->GetVcalibratedKTS() );
689 _set_V_ground_speed( Auxiliary->GetVground() );
691 _set_Omega_Body( Propagate->GetPQR(FGJSBBase::eP),
692 Propagate->GetPQR(FGJSBBase::eQ),
693 Propagate->GetPQR(FGJSBBase::eR) );
695 _set_Euler_Rates( Auxiliary->GetEulerRates(FGJSBBase::ePhi),
696 Auxiliary->GetEulerRates(FGJSBBase::eTht),
697 Auxiliary->GetEulerRates(FGJSBBase::ePsi) );
699 _set_Mach_number( Auxiliary->GetMach() );
701 // Positions of Visual Reference Point
702 FGLocation l = Auxiliary->GetLocationVRP();
703 _updateGeocentricPosition( l.GetLatitude(), l.GetLongitude(),
704 l.GetRadius() - get_Sea_level_radius() );
706 _set_Altitude_AGL( Propagate->GetDistanceAGL() );
708 double loc_cart[3] = { l(FGJSBBase::eX), l(FGJSBBase::eY), l(FGJSBBase::eZ) };
709 double contact[3], d[3], sd, t;
710 is_valid_m(&t, d, &sd);
711 get_agl_ft(t, loc_cart, SG_METER_TO_FEET*2, contact, d, d, &sd);
713 = FGColumnVector3( contact[0], contact[1], contact[2] ).Magnitude();
714 _set_Runway_altitude( rwrad - get_Sea_level_radius() );
717 _set_Euler_Angles( Propagate->GetEuler(FGJSBBase::ePhi),
718 Propagate->GetEuler(FGJSBBase::eTht),
719 Propagate->GetEuler(FGJSBBase::ePsi) );
721 _set_Alpha( Auxiliary->Getalpha() );
722 _set_Beta( Auxiliary->Getbeta() );
725 _set_Gamma_vert_rad( Auxiliary->GetGamma() );
727 _set_Earth_position_angle( Inertial->GetEarthPositionAngle() );
729 _set_Climb_Rate( Propagate->Gethdot() );
731 const FGMatrix33& Tl2b = Propagate->GetTl2b();
732 for ( i = 1; i <= 3; i++ ) {
733 for ( j = 1; j <= 3; j++ ) {
734 _set_T_Local_to_Body( i, j, Tl2b(i,j) );
738 // Copy the engine values from JSBSim.
739 for ( i=0; i < Propulsion->GetNumEngines(); i++ ) {
740 SGPropertyNode * node = fgGetNode("engines/engine", i, true);
742 sprintf(buf, "engines/engine[%d]/thruster", i);
743 SGPropertyNode * tnode = fgGetNode(buf, true);
744 FGThruster * thruster = Propulsion->GetEngine(i)->GetThruster();
746 switch (Propulsion->GetEngine(i)->GetType()) {
747 case FGEngine::etPiston:
748 { // FGPiston code block
749 FGPiston* eng = (FGPiston*)Propulsion->GetEngine(i);
750 node->setDoubleValue("egt-degf", eng->getExhaustGasTemp_degF());
751 node->setDoubleValue("oil-temperature-degf", eng->getOilTemp_degF());
752 node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
753 node->setDoubleValue("mp-osi", eng->getManifoldPressure_inHg());
754 // NOTE: mp-osi is not in ounces per square inch.
755 // This error is left for reasons of backwards compatibility with
756 // existing FlightGear sound and instrument configurations.
757 node->setDoubleValue("mp-inhg", eng->getManifoldPressure_inHg());
758 node->setDoubleValue("cht-degf", eng->getCylinderHeadTemp_degF());
759 node->setDoubleValue("rpm", eng->getRPM());
760 } // end FGPiston code block
762 case FGEngine::etRocket:
763 { // FGRocket code block
764 FGRocket* eng = (FGRocket*)Propulsion->GetEngine(i);
765 } // end FGRocket code block
767 case FGEngine::etTurbine:
768 { // FGTurbine code block
769 FGTurbine* eng = (FGTurbine*)Propulsion->GetEngine(i);
770 node->setDoubleValue("n1", eng->GetN1());
771 node->setDoubleValue("n2", eng->GetN2());
772 node->setDoubleValue("egt_degf", 32 + eng->GetEGT()*9/5);
773 node->setBoolValue("augmentation", eng->GetAugmentation());
774 node->setBoolValue("water-injection", eng->GetInjection());
775 node->setBoolValue("ignition", eng->GetIgnition());
776 node->setDoubleValue("nozzle-pos-norm", eng->GetNozzle());
777 node->setDoubleValue("inlet-pos-norm", eng->GetInlet());
778 node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
779 node->setBoolValue("reversed", eng->GetReversed());
780 node->setBoolValue("cutoff", eng->GetCutoff());
781 node->setDoubleValue("epr", eng->GetEPR());
782 globals->get_controls()->set_reverser(i, eng->GetReversed() );
783 globals->get_controls()->set_cutoff(i, eng->GetCutoff() );
784 globals->get_controls()->set_water_injection(i, eng->GetInjection() );
785 globals->get_controls()->set_augmentation(i, eng->GetAugmentation() );
786 } // end FGTurbine code block
788 case FGEngine::etTurboprop:
789 { // FGTurboProp code block
790 FGTurboProp* eng = (FGTurboProp*)Propulsion->GetEngine(i);
791 node->setDoubleValue("n1", eng->GetN1());
792 //node->setDoubleValue("n2", eng->GetN2());
793 node->setDoubleValue("itt_degf", 32 + eng->GetITT()*9/5);
794 node->setBoolValue("ignition", eng->GetIgnition());
795 node->setDoubleValue("nozzle-pos-norm", eng->GetNozzle());
796 node->setDoubleValue("inlet-pos-norm", eng->GetInlet());
797 node->setDoubleValue("oil-pressure-psi", eng->getOilPressure_psi());
798 node->setBoolValue("reversed", eng->GetReversed());
799 node->setBoolValue("cutoff", eng->GetCutoff());
800 node->setBoolValue("starting", eng->GetEngStarting());
801 node->setBoolValue("generator-power", eng->GetGeneratorPower());
802 node->setBoolValue("damaged", eng->GetCondition());
803 node->setBoolValue("ielu-intervent", eng->GetIeluIntervent());
804 node->setDoubleValue("oil-temperature-degf", eng->getOilTemp_degF());
805 // node->setBoolValue("onfire", eng->GetFire());
806 globals->get_controls()->set_reverser(i, eng->GetReversed() );
807 globals->get_controls()->set_cutoff(i, eng->GetCutoff() );
808 } // end FGTurboProp code block
810 case FGEngine::etElectric:
811 { // FGElectric code block
812 FGElectric* eng = (FGElectric*)Propulsion->GetEngine(i);
813 node->setDoubleValue("rpm", eng->getRPM());
814 } // end FGElectric code block
818 { // FGEngine code block
819 FGEngine* eng = Propulsion->GetEngine(i);
820 node->setDoubleValue("fuel-flow-gph", eng->getFuelFlow_gph());
821 node->setDoubleValue("thrust_lb", thruster->GetThrust());
822 node->setDoubleValue("fuel-flow_pph", eng->getFuelFlow_pph());
823 node->setBoolValue("running", eng->GetRunning());
824 node->setBoolValue("starter", eng->GetStarter());
825 node->setBoolValue("cranking", eng->GetCranking());
826 globals->get_controls()->set_starter(i, eng->GetStarter() );
827 } // end FGEngine code block
829 switch (thruster->GetType()) {
830 case FGThruster::ttNozzle:
831 { // FGNozzle code block
832 FGNozzle* noz = (FGNozzle*)thruster;
833 } // end FGNozzle code block
835 case FGThruster::ttPropeller:
836 { // FGPropeller code block
837 FGPropeller* prop = (FGPropeller*)thruster;
838 tnode->setDoubleValue("rpm", thruster->GetRPM());
839 tnode->setDoubleValue("pitch", prop->GetPitch());
840 tnode->setDoubleValue("torque", prop->GetTorque());
841 tnode->setBoolValue("feathered", prop->GetFeather());
842 } // end FGPropeller code block
844 case FGThruster::ttRotor:
845 { // FGRotor code block
846 FGRotor* rotor = (FGRotor*)thruster;
847 } // end FGRotor code block
849 case FGThruster::ttDirect:
850 { // Direct code block
851 } // end Direct code block
857 // Copy the fuel levels from JSBSim if fuel
858 // freeze not enabled.
859 if ( ! Propulsion->GetFuelFreeze() ) {
860 for (i = 0; i < Propulsion->GetNumTanks(); i++) {
861 SGPropertyNode * node = fgGetNode("/consumables/fuel/tank", i, true);
862 FGTank* tank = Propulsion->GetTank(i);
863 double contents = tank->GetContents();
864 double temp = tank->GetTemperature_degC();
865 node->setDoubleValue("level-gal_us", contents/6.6);
866 node->setDoubleValue("level-lbs", contents);
867 if (temp != -9999.0) node->setDoubleValue("temperature_degC", temp);
873 stall_warning->setDoubleValue( Aerodynamics->GetStallWarn() );
875 elevator_pos_pct->setDoubleValue( FCS->GetDePos(ofNorm) );
876 left_aileron_pos_pct->setDoubleValue( FCS->GetDaLPos(ofNorm) );
877 right_aileron_pos_pct->setDoubleValue( FCS->GetDaRPos(ofNorm) );
878 rudder_pos_pct->setDoubleValue( -1*FCS->GetDrPos(ofNorm) );
879 flap_pos_pct->setDoubleValue( FCS->GetDfPos(ofNorm) );
880 speedbrake_pos_pct->setDoubleValue( FCS->GetDsbPos(ofNorm) );
881 spoilers_pos_pct->setDoubleValue( FCS->GetDspPos(ofNorm) );
882 tailhook_pos_pct->setDoubleValue( FCS->GetTailhookPos() );
883 wing_fold_pos_pct->setDoubleValue( FCS->GetWingFoldPos() );
885 // force a sim crashed if crashed (altitude AGL < 0)
886 if (get_Altitude_AGL() < -100.0) {
887 State->SuspendIntegration();
895 bool FGJSBsim::ToggleDataLogging(void)
897 // ToDo: handle this properly
898 fdmex->DisableOutput();
903 bool FGJSBsim::ToggleDataLogging(bool state)
906 fdmex->EnableOutput();
909 fdmex->DisableOutput();
916 void FGJSBsim::set_Latitude(double lat)
918 static SGConstPropertyNode_ptr altitude = fgGetNode("/position/altitude-ft");
920 double sea_level_radius_meters, lat_geoc;
922 // In case we're not trimming
923 FGInterface::set_Latitude(lat);
925 if ( altitude->getDoubleValue() > -9990 ) {
926 alt = altitude->getDoubleValue();
932 SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Latitude: " << lat );
933 SG_LOG(SG_FLIGHT,SG_INFO," cur alt (ft) = " << alt );
935 sgGeodToGeoc( lat, alt * SG_FEET_TO_METER,
936 &sea_level_radius_meters, &lat_geoc );
937 _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET );
938 fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET );
939 fgic->SetLatitudeRadIC( lat_geoc );
944 void FGJSBsim::set_Longitude(double lon)
946 SG_LOG(SG_FLIGHT,SG_INFO,"FGJSBsim::set_Longitude: " << lon );
948 // In case we're not trimming
949 FGInterface::set_Longitude(lon);
952 fgic->SetLongitudeRadIC( lon );
956 void FGJSBsim::set_Altitude(double alt)
958 static SGConstPropertyNode_ptr latitude = fgGetNode("/position/latitude-deg");
960 double sea_level_radius_meters,lat_geoc;
962 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Altitude: " << alt );
963 SG_LOG(SG_FLIGHT,SG_INFO, " lat (deg) = " << latitude->getDoubleValue() );
965 // In case we're not trimming
966 FGInterface::set_Altitude(alt);
969 sgGeodToGeoc( latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS, alt,
970 &sea_level_radius_meters, &lat_geoc);
971 _set_Sea_level_radius( sea_level_radius_meters * SG_METER_TO_FEET );
972 fgic->SetSeaLevelRadiusFtIC( sea_level_radius_meters * SG_METER_TO_FEET );
973 SG_LOG(SG_FLIGHT, SG_INFO,
974 "Terrain altitude: " << cur_fdm_state->get_Runway_altitude() * SG_METER_TO_FEET );
975 fgic->SetLatitudeRadIC( lat_geoc );
976 fgic->SetAltitudeFtIC(alt);
980 void FGJSBsim::set_V_calibrated_kts(double vc)
982 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_V_calibrated_kts: " << vc );
984 // In case we're not trimming
985 FGInterface::set_V_calibrated_kts(vc);
988 fgic->SetVcalibratedKtsIC(vc);
992 void FGJSBsim::set_Mach_number(double mach)
994 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Mach_number: " << mach );
996 // In case we're not trimming
997 FGInterface::set_Mach_number(mach);
1000 fgic->SetMachIC(mach);
1004 void FGJSBsim::set_Velocities_Local( double north, double east, double down )
1006 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Local: "
1007 << north << ", " << east << ", " << down );
1009 // In case we're not trimming
1010 FGInterface::set_Velocities_Local(north, east, down);
1013 fgic->SetVNorthFpsIC(north);
1014 fgic->SetVEastFpsIC(east);
1015 fgic->SetVDownFpsIC(down);
1019 void FGJSBsim::set_Velocities_Wind_Body( double u, double v, double w)
1021 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Velocities_Wind_Body: "
1022 << u << ", " << v << ", " << w );
1024 // In case we're not trimming
1025 FGInterface::set_Velocities_Wind_Body(u, v, w);
1028 fgic->SetUBodyFpsIC(u);
1029 fgic->SetVBodyFpsIC(v);
1030 fgic->SetWBodyFpsIC(w);
1035 void FGJSBsim::set_Euler_Angles( double phi, double theta, double psi )
1037 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Euler_Angles: "
1038 << phi << ", " << theta << ", " << psi );
1040 // In case we're not trimming
1041 FGInterface::set_Euler_Angles(phi, theta, psi);
1044 fgic->SetThetaRadIC(theta);
1045 fgic->SetPhiRadIC(phi);
1046 fgic->SetPsiRadIC(psi);
1051 void FGJSBsim::set_Climb_Rate( double roc)
1053 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Climb_Rate: " << roc );
1055 // In case we're not trimming
1056 FGInterface::set_Climb_Rate(roc);
1059 //since both climb rate and flight path angle are set in the FG
1060 //startup sequence, something is needed to keep one from cancelling
1062 if( !(fabs(roc) > 1 && fabs(fgic->GetFlightPathAngleRadIC()) < 0.01) ) {
1063 fgic->SetClimbRateFpsIC(roc);
1068 void FGJSBsim::set_Gamma_vert_rad( double gamma)
1070 SG_LOG(SG_FLIGHT,SG_INFO, "FGJSBsim::set_Gamma_vert_rad: " << gamma );
1073 if( !(fabs(gamma) < 0.01 && fabs(fgic->GetClimbRateFpsIC()) > 1) ) {
1074 fgic->SetFlightPathAngleRadIC(gamma);
1079 void FGJSBsim::init_gear(void )
1081 FGGroundReactions* gr=fdmex->GetGroundReactions();
1082 int Ngear=GroundReactions->GetNumGearUnits();
1083 for (int i=0;i<Ngear;i++) {
1084 FGLGear *gear = gr->GetGearUnit(i);
1085 SGPropertyNode * node = fgGetNode("gear/gear", i, true);
1086 node->setDoubleValue("xoffset-in", gear->GetBodyLocation()(1));
1087 node->setDoubleValue("yoffset-in", gear->GetBodyLocation()(2));
1088 node->setDoubleValue("zoffset-in", gear->GetBodyLocation()(3));
1089 node->setBoolValue("wow", gear->GetWOW());
1090 node->setBoolValue("has-brake", gear->GetBrakeGroup() > 0);
1091 node->setDoubleValue("position-norm", gear->GetGearUnitPos());
1092 node->setDoubleValue("tire-pressure-norm", gear->GetTirePressure());
1093 node->setDoubleValue("compression-norm", gear->GetCompLen());
1094 node->setDoubleValue("compression-ft", gear->GetCompLen());
1095 if ( gear->GetSteerable() )
1096 node->setDoubleValue("steering-norm", gear->GetSteerNorm());
1100 void FGJSBsim::update_gear(void)
1102 FGGroundReactions* gr=fdmex->GetGroundReactions();
1103 int Ngear=GroundReactions->GetNumGearUnits();
1104 for (int i=0;i<Ngear;i++) {
1105 FGLGear *gear = gr->GetGearUnit(i);
1106 SGPropertyNode * node = fgGetNode("gear/gear", i, true);
1107 node->getChild("wow", 0, true)->setBoolValue( gear->GetWOW());
1108 node->getChild("position-norm", 0, true)->setDoubleValue(gear->GetGearUnitPos());
1109 gear->SetTirePressure(node->getDoubleValue("tire-pressure-norm"));
1110 node->setDoubleValue("compression-norm", gear->GetCompLen());
1111 node->setDoubleValue("compression-ft", gear->GetCompLen());
1112 if ( gear->GetSteerable() )
1113 node->setDoubleValue("steering-norm", gear->GetSteerNorm());
1117 void FGJSBsim::do_trim(void)
1121 if ( fgGetBool("/sim/presets/onground") )
1123 fgtrim = new FGTrim(fdmex,tGround);
1125 fgtrim = new FGTrim(fdmex,tLongitudinal);
1128 if ( !fgtrim->DoTrim() ) {
1130 fgtrim->TrimStats();
1132 trimmed->setBoolValue(true);
1134 // if (FGJSBBase::debug_lvl > 0)
1135 // State->ReportState();
1139 pitch_trim->setDoubleValue( FCS->GetPitchTrimCmd() );
1140 throttle_trim->setDoubleValue( FCS->GetThrottleCmd(0) );
1141 aileron_trim->setDoubleValue( FCS->GetDaCmd() );
1142 rudder_trim->setDoubleValue( FCS->GetDrCmd() );
1144 globals->get_controls()->set_elevator_trim(FCS->GetPitchTrimCmd());
1145 globals->get_controls()->set_elevator(FCS->GetDeCmd());
1146 globals->get_controls()->set_throttle(FGControls::ALL_ENGINES,
1147 FCS->GetThrottleCmd(0));
1149 globals->get_controls()->set_aileron(FCS->GetDaCmd());
1150 globals->get_controls()->set_rudder( FCS->GetDrCmd());
1152 SG_LOG( SG_FLIGHT, SG_INFO, " Trim complete" );
1155 void FGJSBsim::update_ic(void)
1158 fgic->SetLatitudeRadIC(get_Lat_geocentric() );
1159 fgic->SetLongitudeRadIC( get_Longitude() );
1160 fgic->SetAltitudeFtIC( get_Altitude() );
1161 fgic->SetVcalibratedKtsIC( get_V_calibrated_kts() );
1162 fgic->SetThetaRadIC( get_Theta() );
1163 fgic->SetPhiRadIC( get_Phi() );
1164 fgic->SetPsiRadIC( get_Psi() );
1165 fgic->SetClimbRateFpsIC( get_Climb_Rate() );
1170 FGJSBsim::get_agl_ft(double t, const double pt[3], double alt_off,
1171 double contact[3], double normal[3], double vel[3],
1174 double angularVel[3];
1175 const SGMaterial* material;
1176 simgear::BVHNode::Id id;
1177 if (!FGInterface::get_agl_ft(t, pt, alt_off, contact, normal, vel,
1178 angularVel, material, id))
1180 SGGeod geodPt = SGGeod::fromCart(SG_FEET_TO_METER*SGVec3d(pt));
1181 SGQuatd hlToEc = SGQuatd::fromLonLat(geodPt);
1182 *agl = dot(hlToEc.rotate(SGVec3d(0, 0, 1)), SGVec3d(contact) - SGVec3d(pt));
1186 inline static double dot3(const FGColumnVector3& a, const FGColumnVector3& b)
1188 return a(1) * b(1) + a(2) * b(2) + a(3) * b(3);
1191 inline static double sqr(double x)
1196 static double angle_diff(double a, double b)
1198 double diff = fabs(a - b);
1199 if (diff > 180) diff = 360 - diff;
1204 static void check_hook_solution(const FGColumnVector3& ground_normal_body, double E, double hook_length, double sin_fi_guess, double cos_fi_guess, double* sin_fis, double* cos_fis, double* fis, int* points)
1206 FGColumnVector3 tip(-hook_length * cos_fi_guess, 0, hook_length * sin_fi_guess);
1207 double dist = dot3(tip, ground_normal_body);
1208 if (fabs(dist + E) < 0.0001) {
1209 sin_fis[*points] = sin_fi_guess;
1210 cos_fis[*points] = cos_fi_guess;
1211 fis[*points] = atan2(sin_fi_guess, cos_fi_guess) * SG_RADIANS_TO_DEGREES;
1217 static void check_hook_solution(const FGColumnVector3& ground_normal_body, double E, double hook_length, double sin_fi_guess, double* sin_fis, double* cos_fis, double* fis, int* points)
1219 if (sin_fi_guess >= -1 && sin_fi_guess <= 1) {
1220 double cos_fi_guess = sqrt(1 - sqr(sin_fi_guess));
1221 check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, cos_fi_guess, sin_fis, cos_fis, fis, points);
1222 if (fabs(cos_fi_guess) > SG_EPSILON) {
1223 check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, -cos_fi_guess, sin_fis, cos_fis, fis, points);
1228 void FGJSBsim::update_external_forces(double t_off)
1230 const FGMatrix33& Tb2l = Propagate->GetTb2l();
1231 const FGMatrix33& Tl2b = Propagate->GetTl2b();
1232 const FGLocation& Location = Propagate->GetLocation();
1233 const FGMatrix33& Tec2l = Location.GetTec2l();
1235 double hook_area[4][3];
1237 FGColumnVector3 hook_root_body = MassBalance->StructuralToBody(hook_root_struct);
1238 FGColumnVector3 hook_root = Location.LocalToLocation(Tb2l * hook_root_body);
1239 hook_area[1][0] = hook_root(1);
1240 hook_area[1][1] = hook_root(2);
1241 hook_area[1][2] = hook_root(3);
1243 hook_length = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-length-ft", 6.75);
1244 double fi_min = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-min-deg", -18);
1245 double fi_max = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-max-deg", 30);
1246 double fi = fgGetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-norm") * (fi_max - fi_min) + fi_min;
1247 double cos_fi = cos(fi * SG_DEGREES_TO_RADIANS);
1248 double sin_fi = sin(fi * SG_DEGREES_TO_RADIANS);
1250 FGColumnVector3 hook_tip_body = hook_root_body;
1251 hook_tip_body(1) -= hook_length * cos_fi;
1252 hook_tip_body(3) += hook_length * sin_fi;
1253 bool hook_tip_valid = true;
1256 double ground_normal[3];
1257 double ground_vel[3];
1261 bool got = get_agl_ft(t_off, hook_area[1], 0, contact, ground_normal, ground_vel, &root_agl_ft);
1262 if (got && root_agl_ft > 0 && root_agl_ft < hook_length) {
1263 FGColumnVector3 ground_normal_body = Tl2b * (Tec2l * FGColumnVector3(ground_normal[0], ground_normal[1], ground_normal[2]));
1264 FGColumnVector3 contact_body = Tl2b * Location.LocationToLocal(FGColumnVector3(contact[0], contact[1], contact[2]));
1265 double D = -dot3(contact_body, ground_normal_body);
1267 // check hook tip agl against same ground plane
1268 double hook_tip_agl_ft = dot3(hook_tip_body, ground_normal_body) + D;
1269 if (hook_tip_agl_ft < 0) {
1271 // hook tip: hx - l cos, hy, hz + l sin
1272 // on ground: - n0 l cos + n2 l sin + E = 0
1274 double E = D + dot3(hook_root_body, ground_normal_body);
1276 // substitue x = sin fi, cos fi = sqrt(1 - x * x)
1277 // and rearrange to get a quadratic with coeffs:
1278 double a = sqr(hook_length) * (sqr(ground_normal_body(1)) + sqr(ground_normal_body(3)));
1279 double b = 2 * E * ground_normal_body(3) * hook_length;
1280 double c = sqr(E) - sqr(ground_normal_body(1) * hook_length);
1282 double disc = sqr(b) - 4 * a * c;
1284 double delta = sqrt(disc) / (2 * a);
1286 // allow 4 solutions for safety, should never happen
1292 double sin_fi_guess = -b / (2 * a) - delta;
1293 check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess, sin_fis, cos_fis, fis, &points);
1294 check_hook_solution(ground_normal_body, E, hook_length, sin_fi_guess + 2 * delta, sin_fis, cos_fis, fis, &points);
1297 double diff1 = angle_diff(fi, fis[0]);
1298 double diff2 = angle_diff(fi, fis[1]);
1299 int point = diff1 < diff2 ? 0 : 1;
1301 sin_fi = sin_fis[point];
1302 cos_fi = cos_fis[point];
1303 hook_tip_body(1) = hook_root_body(1) - hook_length * cos_fi;
1304 hook_tip_body(3) = hook_root_body(3) + hook_length * sin_fi;
1310 FGColumnVector3 hook_root_vel = Propagate->GetVel() + (Tb2l * (Propagate->GetPQR() * hook_root_body));
1311 double wire_ends_ec[2][3];
1312 double wire_vel_ec[2][3];
1313 get_wire_ends_ft(t_off, wire_ends_ec, wire_vel_ec);
1314 FGColumnVector3 wire_vel_1 = Tec2l * FGColumnVector3(wire_vel_ec[0][0], wire_vel_ec[0][1], wire_vel_ec[0][2]);
1315 FGColumnVector3 wire_vel_2 = Tec2l * FGColumnVector3(wire_vel_ec[1][0], wire_vel_ec[1][1], wire_vel_ec[1][2]);
1316 FGColumnVector3 rel_vel = hook_root_vel - (wire_vel_1 + wire_vel_2) / 2;
1317 if (rel_vel.Magnitude() < 3) {
1320 fgSetDouble("/fdm/jsbsim/external_reactions/hook/magnitude", 0.0);
1322 FGColumnVector3 wire_end1_body = Tl2b * Location.LocationToLocal(FGColumnVector3(wire_ends_ec[0][0], wire_ends_ec[0][1], wire_ends_ec[0][2])) - hook_root_body;
1323 FGColumnVector3 wire_end2_body = Tl2b * Location.LocationToLocal(FGColumnVector3(wire_ends_ec[1][0], wire_ends_ec[1][1], wire_ends_ec[1][2])) - hook_root_body;
1324 FGColumnVector3 force_plane_normal = wire_end1_body * wire_end2_body;
1325 force_plane_normal.Normalize();
1326 cos_fi = dot3(force_plane_normal, FGColumnVector3(0, 0, 1));
1327 if (cos_fi < 0) cos_fi = -cos_fi;
1328 sin_fi = sqrt(1 - sqr(cos_fi));
1329 fi = atan2(sin_fi, cos_fi) * SG_RADIANS_TO_DEGREES;
1331 fgSetDouble("/fdm/jsbsim/external_reactions/hook/x", -cos_fi);
1332 fgSetDouble("/fdm/jsbsim/external_reactions/hook/y", 0);
1333 fgSetDouble("/fdm/jsbsim/external_reactions/hook/z", sin_fi);
1334 fgSetDouble("/fdm/jsbsim/external_reactions/hook/magnitude", fgGetDouble("/fdm/jsbsim/systems/hook/force"));
1338 FGColumnVector3 hook_tip = Location.LocalToLocation(Tb2l * hook_tip_body);
1340 hook_area[0][0] = hook_tip(1);
1341 hook_area[0][1] = hook_tip(2);
1342 hook_area[0][2] = hook_tip(3);
1345 // The previous positions.
1346 hook_area[2][0] = last_hook_root[0];
1347 hook_area[2][1] = last_hook_root[1];
1348 hook_area[2][2] = last_hook_root[2];
1349 hook_area[3][0] = last_hook_tip[0];
1350 hook_area[3][1] = last_hook_tip[1];
1351 hook_area[3][2] = last_hook_tip[2];
1353 // Check if we caught a wire.
1354 // Returns true if we caught one.
1355 if (caught_wire_ft(t_off, hook_area)) {
1360 // save actual position as old position ...
1361 last_hook_tip[0] = hook_area[0][0];
1362 last_hook_tip[1] = hook_area[0][1];
1363 last_hook_tip[2] = hook_area[0][2];
1364 last_hook_root[0] = hook_area[1][0];
1365 last_hook_root[1] = hook_area[1][1];
1366 last_hook_root[2] = hook_area[1][2];
1368 fgSetDouble("/fdm/jsbsim/systems/hook/tailhook-pos-deg", fi);