8 #include <simgear/debug/logstream.hxx>
9 #include <simgear/math/sg_geodesy.hxx>
10 #include <simgear/misc/sg_path.hxx>
11 #include <simgear/scene/model/placement.hxx>
12 #include <simgear/xml/easyxml.hxx>
14 #include <Main/globals.hxx>
15 #include <Main/fg_props.hxx>
18 #include "Atmosphere.hpp"
20 #include "Airplane.hpp"
22 #include "Integrator.hpp"
26 #include "Launchbar.hpp"
27 #include "FGGround.hpp"
28 #include "PropEngine.hpp"
29 #include "PistonEngine.hpp"
33 using namespace yasim;
35 static const float YASIM_PI = 3.14159265358979323846;
36 static const float RAD2DEG = 180/YASIM_PI;
37 static const float PI2 = YASIM_PI*2;
38 static const float RAD2RPM = 9.54929658551;
39 static const float M2FT = 3.2808399;
40 static const float FT2M = 0.3048;
41 static const float MPS2KTS = 3600.0/1852.0;
42 static const float CM2GALS = 264.172037284; // gallons/cubic meter
43 static const float KG2LBS = 2.20462262185;
44 static const float W2HP = 1.3416e-3;
45 static const float INHG2PA = 3386.389;
46 static const float SLUG2KG = 14.59390;
48 YASim::YASim(double dt) :
56 _fdm->getAirplane()->getModel()->setGroundCallback( new FGGround(this) );
57 _fdm->getAirplane()->getModel()->getIntegrator()->setInterval(_dt);
69 Airplane* a = _fdm->getAirplane();
71 float aoa = a->getCruiseAoA() * RAD2DEG;
72 float tail = -1 * a->getTailIncidence() * RAD2DEG;
73 float drag = 1000 * a->getDragCoefficient();
75 SG_LOG(SG_FLIGHT,SG_INFO,"YASim solution results:");
76 SG_LOG(SG_FLIGHT,SG_INFO," Iterations: "<<a->getSolutionIterations());
77 SG_LOG(SG_FLIGHT,SG_INFO," Drag Coefficient: "<< drag);
78 SG_LOG(SG_FLIGHT,SG_INFO," Lift Ratio: "<<a->getLiftRatio());
79 SG_LOG(SG_FLIGHT,SG_INFO," Cruise AoA: "<< aoa);
80 SG_LOG(SG_FLIGHT,SG_INFO," Tail Incidence: "<< tail);
81 SG_LOG(SG_FLIGHT,SG_INFO,"Approach Elevator: "<<a->getApproachElevator());
85 a->getModel()->getBody()->getCG(cg);
86 sprintf(buf, " CG: %.3f, %.3f, %.3f", cg[0], cg[1], cg[2]);
87 SG_LOG(SG_FLIGHT, SG_INFO, buf);
89 if(a->getFailureMsg()) {
90 SG_LOG(SG_FLIGHT, SG_ALERT, "YASim SOLUTION FAILURE:");
91 SG_LOG(SG_FLIGHT, SG_ALERT, a->getFailureMsg());
98 // Run the superclass bind to set up a bunch of property ties
101 //Torsten Dreyer: we shouldn't do this anymore because we don't set these values nomore
102 // Now UNtie the ones that we are going to set ourselves.
103 // fgUntie("/consumables/fuel/tank[0]/level-gal_us");
104 // fgUntie("/consumables/fuel/tank[1]/level-gal_us");
107 for(int i=0; i<_fdm->getAirplane()->getModel()->numThrusters(); i++) {
108 sprintf(buf, "/engines/engine[%d]/fuel-flow-gph", i); fgUntie(buf);
109 sprintf(buf, "/engines/engine[%d]/rpm", i); fgUntie(buf);
110 sprintf(buf, "/engines/engine[%d]/mp-osi", i); fgUntie(buf);
111 sprintf(buf, "/engines/engine[%d]/egt-degf", i); fgUntie(buf);
112 sprintf(buf, "/engines/engine[%d]/oil-temperature-degf", i); fgUntie(buf);
116 YASim::GearProps::GearProps(SGPropertyNode_ptr gear_root) :
117 has_brake(gear_root->getNode("has-brake", true)),
118 wow(gear_root->getNode("wow", true)),
119 compression_norm(gear_root->getNode("compression-norm", true)),
120 compression_m(gear_root->getNode("compression-m", true)),
121 caster_angle_deg(gear_root->getNode("caster-angle-deg", true)),
122 rollspeed_ms(gear_root->getNode("rollspeed-ms", true)),
123 ground_is_solid(gear_root->getNode("ground-is-solid", true)),
124 ground_friction_factor(gear_root->getNode("ground-friction-factor", true))
130 Airplane* airplane = _fdm->getAirplane();
131 Model* model = airplane->getModel();
133 _crashed = fgGetNode("/sim/crashed", true);
134 _pressure_inhg = fgGetNode("/environment/pressure-inhg", true);
135 _temp_degc = fgGetNode("/environment/temperature-degc", true);
136 _density_slugft3 = fgGetNode("/environment/density-slugft3", true);
137 _gear_agl_m = fgGetNode("/position/gear-agl-m", true);
138 _gear_agl_ft = fgGetNode("/position/gear-agl-ft", true);
139 _pilot_g = fgGetNode("/accelerations/pilot-g", true);
140 _speed_setprop = fgGetNode("/sim/presets/speed-set", true);
145 model->setCrashed(false);
146 _crashed->setBoolValue(false);
148 // Figure out the initial speed type
149 string speed_set = _speed_setprop->getStringValue();
150 if ((speed_set == "") || (speed_set == "UVW"))
152 else if (speed_set == "NED")
154 else if (speed_set == "knots")
156 else if (speed_set == "mach")
160 SG_LOG(SG_FLIGHT, SG_ALERT, "Unknown speed type " << speed_set);
163 // Build a filename and parse it
164 SGPath f(fgGetString("/sim/aircraft-dir"));
165 f.append(fgGetString("/sim/aero"));
168 readXML(f.str(), *_fdm);
169 } catch (const sg_exception &e) {
170 SG_LOG(SG_FLIGHT, SG_ALERT,
171 "Error reading YASim FDM: '" << f.str() << "'" << std::endl
172 << e.getFormattedMessage());
176 // Compile it into a real airplane, and tell the user what they got
182 if (model->getLaunchbar())
184 _catapult_launch_cmd = fgGetNode("/controls/gear/catapult-launch-cmd", true);
185 _launchbar_position_norm = fgGetNode("/gear/launchbar/position-norm", true);
186 _launchbar_holdback_pos_norm = fgGetNode("/gear/launchbar/holdback-position-norm", true);
187 _launchbar_state = fgGetNode("/gear/launchbar/state", true);
188 _launchbar_strop = fgGetNode("/gear/launchbar/strop", true);
190 if (airplane->getHook())
192 _tailhook_position_norm = fgGetNode("/gear/tailhook/position-norm", 0, true);
195 // Create some FG{Eng|Gear}Interface objects
196 for(int i=0; i<airplane->numGear(); i++) {
197 Gear* g = airplane->getGear(i);
198 SGPropertyNode * node = fgGetNode("gear/gear", i, true);
201 node->setDoubleValue("xoffset-in", pos[0] * M2FT * 12);
202 node->setDoubleValue("yoffset-in", pos[1] * M2FT * 12);
203 node->setDoubleValue("zoffset-in", pos[2] * M2FT * 12);
205 _gearProps.push_back(GearProps(node));
208 // Are we at ground level? If so, lift the plane up so the gear
210 double runway_altitude = get_Runway_altitude();
211 if(get_Altitude() - runway_altitude < 50) {
212 fgSetBool("/controls/gear/gear-down", false);
213 float minGearZ = 1e18;
214 for(int i=0; i<airplane->numGear(); i++) {
215 Gear* g = airplane->getGear(i);
218 if(pos[2] < minGearZ)
221 _set_Altitude(runway_altitude - minGearZ*M2FT);
222 // ground start-up: gear down
223 fgSetBool("/controls/gear/gear-down", true);
227 // airborne start-up: gear up
228 fgSetBool("/controls/gear/gear-down", false);
231 // Blank the state, and copy in ours
236 _fdm->getExternalInput();
237 _fdm->getAirplane()->initEngines();
242 void YASim::update(double dt)
247 int iterations = _calc_multiloop(dt);
249 // If we're crashed, then we don't care
250 if(_crashed->getBoolValue() || _fdm->getAirplane()->getModel()->isCrashed()) {
251 if(!_crashed->getBoolValue())
252 _crashed->setBoolValue(true);
253 _fdm->getAirplane()->getModel()->setCrashed(false);
257 // ground. Calculate a cartesian coordinate for the ground under
258 // us, find the (geodetic) up vector normal to the ground, then
259 // use that to find the final (radius) term of the plane equation.
260 float v[3] = { get_uBody(), get_vBody(), get_wBody() };
261 float lat = get_Latitude(); float lon = get_Longitude();
262 float alt = get_Altitude() * FT2M; double xyz[3];
263 sgGeodToCart(lat, lon, alt, xyz);
264 // build the environment cache.
265 float vr = _fdm->getVehicleRadius();
266 vr += 2.0*FT2M*dt*Math::mag3(v);
267 prepare_ground_cache_m( _simTime, _simTime + dt, xyz, vr );
269 // Track time increments.
271 = (FGGround*)_fdm->getAirplane()->getModel()->getGroundCallback();
274 for(i=0; i<iterations; i++) {
275 gr->setTimeOffset(_simTime + i*_dt);
281 // Increment the local sim time
283 gr->setTimeOffset(_simTime);
286 void YASim::copyToYASim(bool copyState)
289 double lat = get_Latitude();
290 double lon = get_Longitude();
291 float alt = get_Altitude() * FT2M;
292 float roll = get_Phi();
293 float pitch = get_Theta();
294 float hdg = get_Psi();
298 wind[0] = get_V_north_airmass() * FT2M * -1.0;
299 wind[1] = get_V_east_airmass() * FT2M * -1.0;
300 wind[2] = get_V_down_airmass() * FT2M * -1.0;
302 float pressure = _pressure_inhg->getFloatValue() * INHG2PA;
303 float temp = _temp_degc->getFloatValue() + 273.15;
304 float dens = _density_slugft3->getFloatValue() *
305 SLUG2KG * M2FT*M2FT*M2FT;
308 Model* model = _fdm->getAirplane()->getModel();
311 Glue::xyz2nedMat(lat, lon, xyz2ned);
314 sgGeodToCart(lat, lon, alt, s.pos);
316 // allow setting of /position/[lat|long|alti]tude
317 double * dp = &model->getState()->pos[0];
318 dp[0] = s.pos[0]; dp[1] = s.pos[1]; dp[2] = s.pos[2];
322 Glue::euler2orient(roll, pitch, hdg, s.orient);
323 Math::mmul33(s.orient, xyz2ned, s.orient);
327 bool needCopy = false;
328 switch (_speed_set) {
330 v[0] = get_V_north() * FT2M * -1.0;
331 v[1] = get_V_east() * FT2M * -1.0;
332 v[2] = get_V_down() * FT2M * -1.0;
335 v[0] = get_uBody() * FT2M;
336 v[1] = get_vBody() * FT2M;
337 v[2] = get_wBody() * FT2M;
338 Math::tmul33(s.orient, v, v);
341 v[0] = Atmosphere::spdFromVCAS(get_V_calibrated_kts()/MPS2KTS,
345 Math::tmul33(s.orient, v, v);
349 v[0] = Atmosphere::spdFromMach(get_Mach_number(), temp);
352 Math::tmul33(s.orient, v, v);
362 _speed_set = UVW; // change to this after initial setting
365 if(copyState || needCopy)
369 Math::tmul33(xyz2ned, wind, wind);
370 model->setWind(wind);
373 model->setAir(pressure, temp, dens);
375 // Query a ground plane for each gear/hook/launchbar and
376 // write that value into the corresponding class.
377 _fdm->getAirplane()->getModel()->updateGround(&s);
379 Launchbar* l = model->getLaunchbar();
381 l->setLaunchCmd(0.0 < _catapult_launch_cmd->getFloatValue());
384 // All the settables:
386 // These are set below:
389 // _set_Accels_CG_Body
390 // _set_Accels_Pilot_Body
391 // _set_Accels_CG_Body_N
392 // _set_Velocities_Local
393 // _set_Velocities_Ground
394 // _set_Velocities_Wind_Body
399 // _set_V_ground_speed
401 // _set_V_calibrated_kts
409 // _set_Geodetic_Position
410 // _set_Runway_altitude
412 // Ignoring these, because they're unused:
413 // _set_Geocentric_Position
414 // _set_Geocentric_Rates
417 // _set_Earth_position_angle (WTF?)
418 // _set_Gamma_vert_rad
420 // _set_T_Local_to_Body
422 // _set_Sea_Level_Radius
424 // Externally set via the weather code:
425 // _set_Velocities_Local_Airmass
427 // _set_Static_pressure
428 // _set_Static_temperature
429 void YASim::copyFromYASim()
431 Airplane* airplane = _fdm->getAirplane();
432 Model* model = airplane->getModel();
433 State* s = model->getState();
436 double lat, lon, alt;
437 sgCartToGeod(s->pos, &lat, &lon, &alt);
438 _set_Geodetic_Position(lat, lon, alt*M2FT);
439 double groundlevel_m = get_groundlevel_m(lat, lon, alt);
440 _set_Runway_altitude(groundlevel_m*SG_METER_TO_FEET);
441 _set_Altitude_AGL((alt-groundlevel_m)*SG_METER_TO_FEET);
443 // the smallest agl of all gears
444 _gear_agl_m->setFloatValue(model->getAGL());
445 _gear_agl_ft->setFloatValue(model->getAGL()*M2FT);
448 //_set_Geocentric_Position(Glue::geod2geocLat(lat), lon, alt*M2FT);
450 // useful conversion matrix
452 Glue::xyz2nedMat(lat, lon, xyz2ned);
456 Math::vmul33(xyz2ned, s->v, v);
457 _set_Velocities_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
458 _set_V_ground_speed(Math::sqrt(M2FT*v[0]*M2FT*v[0] +
459 M2FT*v[1]*M2FT*v[1]));
460 _set_Climb_Rate(-M2FT*v[2]);
462 // The HUD uses this, but inverts down (?!)
463 _set_Velocities_Ground(M2FT*v[0], M2FT*v[1], -M2FT*v[2]);
465 // _set_Geocentric_Rates(M2FT*v[0], M2FT*v[1], M2FT*v[2]); // UNUSED
469 wind[0] = get_V_north_airmass() * FT2M * -1.0; // Wind in NED
470 wind[1] = get_V_east_airmass() * FT2M * -1.0;
471 wind[2] = get_V_down_airmass() * FT2M * -1.0;
472 Math::tmul33(xyz2ned, wind, wind); // Wind in global
473 Math::sub3(s->v, wind, v); // V - wind in global
474 Math::vmul33(s->orient, v, v); // to body coordinates
475 _set_Velocities_Wind_Body(v[0]*M2FT, -v[1]*M2FT, -v[2]*M2FT);
476 _set_V_rel_wind(Math::mag3(v)*M2FT); // units?
478 float P = _pressure_inhg->getFloatValue() * INHG2PA;
479 float T = _temp_degc->getFloatValue() + 273.15;
480 float D = _density_slugft3->getFloatValue()
481 *SLUG2KG * M2FT*M2FT*M2FT;
482 _set_V_equiv_kts(Atmosphere::calcVEAS(v[0], P, T, D)*MPS2KTS);
483 _set_V_calibrated_kts(Atmosphere::calcVCAS(v[0], P, T)*MPS2KTS);
484 _set_Mach_number(Atmosphere::calcMach(v[0], T));
487 Math::vmul33(xyz2ned, s->acc, v);
488 _set_Accels_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
490 Math::vmul33(s->orient, s->acc, v);
491 _set_Accels_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
492 _set_Accels_CG_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
494 _fdm->getAirplane()->getPilotAccel(v);
495 _set_Accels_Pilot_Body(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
497 // There is no property for pilot G's, but I need it for a panel
498 // instrument. Hack this in here, and REMOVE IT WHEN IT FINDS A
500 _pilot_g->setFloatValue(-v[2]/9.8);
502 // The one appears (!) to want inverted pilot acceleration
503 // numbers, in G's...
504 Math::mul3(1.0/9.8, v, v);
505 _set_Accels_CG_Body_N(v[0], -v[1], -v[2]);
509 Glue::calcAlphaBeta(s, wind, &alpha, &beta);
514 Math::trans33(xyz2ned, tmp);
515 Math::mmul33(s->orient, tmp, tmp);
516 float roll, pitch, hdg;
517 Glue::orient2euler(tmp, &roll, &pitch, &hdg);
518 // make heading positive value
519 if(hdg < 0.0) hdg += PI2;
520 _set_Euler_Angles(roll, pitch, hdg);
523 Math::vmul33(s->orient, s->rot, v);
524 _set_Omega_Body(v[0], -v[1], -v[2]);
526 Glue::calcEulerRates(s, &roll, &pitch, &hdg);
527 _set_Euler_Rates(roll, pitch, hdg);
529 // Fill out our engine and gear objects
530 for(int i=0; i<airplane->numGear(); i++) {
531 Gear* g = airplane->getGear(i);
532 GearProps& gearProps = _gearProps[i];
533 gearProps.has_brake->setBoolValue(
535 gearProps.wow->setBoolValue(
536 g->getCompressFraction() != 0);
537 gearProps.compression_norm->setFloatValue(
538 g->getCompressFraction());
539 gearProps.compression_m->setFloatValue(
540 g->getCompressDist());
541 gearProps.caster_angle_deg->setFloatValue(
542 g->getCasterAngle() * RAD2DEG);
543 gearProps.rollspeed_ms->setFloatValue(
545 gearProps.ground_is_solid->setBoolValue(
546 g->getGroundIsSolid()!=0);
547 gearProps.ground_friction_factor->setFloatValue(
548 g->getGroundFrictionFactor());
551 Hook* h = airplane->getHook();
553 _tailhook_position_norm->setFloatValue(h->getCompressFraction());
556 Launchbar* l = airplane->getLaunchbar();
558 _launchbar_position_norm->setFloatValue(l->getCompressFraction());
559 _launchbar_holdback_pos_norm->setFloatValue(l->getHoldbackCompressFraction());
560 _launchbar_state->setStringValue(l->getState());
561 _launchbar_strop->setBoolValue(l->getStrop());
566 * This is only used after a replay session and when the user requested to resume at
567 * a past point of time. In this case the FDM must reload all values from the property
568 * tree (as given by the replay system). */
571 // Process inputs. Use excessive value for dt to make sure all transition effects
572 // have reached their final state (i.e. gear is extended/retracted) - which is vital
573 // for many properties to be complete before the first FDM run (otherwise the gear may
574 // still be up, thrust-reversers/speed-brakes/... may still be partially deployed...).
575 _fdm->getExternalInput(1000);
577 // get current FDM values from the property tree