6 #include <simgear/debug/logstream.hxx>
7 #include <simgear/math/sg_geodesy.hxx>
8 #include <simgear/misc/sg_path.hxx>
9 #include <simgear/scene/model/placement.hxx>
10 #include <simgear/xml/easyxml.hxx>
12 #include <Main/globals.hxx>
13 #include <Main/fg_props.hxx>
16 #include "Atmosphere.hpp"
18 #include "Airplane.hpp"
20 #include "Integrator.hpp"
24 #include "Launchbar.hpp"
25 #include "FGGround.hpp"
26 #include "PropEngine.hpp"
27 #include "PistonEngine.hpp"
31 using namespace yasim;
33 static const float YASIM_PI = 3.14159265358979323846;
34 static const float RAD2DEG = 180/YASIM_PI;
35 static const float PI2 = YASIM_PI*2;
36 static const float RAD2RPM = 9.54929658551;
37 static const float M2FT = 3.2808399;
38 static const float FT2M = 0.3048;
39 static const float MPS2KTS = 3600.0/1852.0;
40 static const float CM2GALS = 264.172037284; // gallons/cubic meter
41 static const float KG2LBS = 2.20462262185;
42 static const float W2HP = 1.3416e-3;
43 static const float INHG2PA = 3386.389;
44 static const float SLUG2KG = 14.59390;
46 YASim::YASim(double dt) :
54 _fdm->getAirplane()->getModel()->setGroundCallback( new FGGround(this) );
55 _fdm->getAirplane()->getModel()->getIntegrator()->setInterval(_dt);
65 Airplane* a = _fdm->getAirplane();
67 float aoa = a->getCruiseAoA() * RAD2DEG;
68 float tail = -1 * a->getTailIncidence() * RAD2DEG;
69 float drag = 1000 * a->getDragCoefficient();
71 SG_LOG(SG_FLIGHT,SG_INFO,"YASim solution results:");
72 SG_LOG(SG_FLIGHT,SG_INFO," Iterations: "<<a->getSolutionIterations());
73 SG_LOG(SG_FLIGHT,SG_INFO," Drag Coefficient: "<< drag);
74 SG_LOG(SG_FLIGHT,SG_INFO," Lift Ratio: "<<a->getLiftRatio());
75 SG_LOG(SG_FLIGHT,SG_INFO," Cruise AoA: "<< aoa);
76 SG_LOG(SG_FLIGHT,SG_INFO," Tail Incidence: "<< tail);
77 SG_LOG(SG_FLIGHT,SG_INFO,"Approach Elevator: "<<a->getApproachElevator());
82 a->getModel()->getBody()->getCG(cg);
83 sprintf(buf, " CG: %.3f, %.3f, %.3f", cg[0], cg[1], cg[2]);
84 SG_LOG(SG_FLIGHT, SG_INFO, buf);
86 if(a->getFailureMsg()) {
87 SG_LOG(SG_FLIGHT, SG_ALERT, "YASim SOLUTION FAILURE:");
88 SG_LOG(SG_FLIGHT, SG_ALERT, a->getFailureMsg());
95 // Run the superclass bind to set up a bunch of property ties
98 //Torsten Dreyer: we shouldn't do this anymore because we don't set these values nomore
99 // Now UNtie the ones that we are going to set ourselves.
100 // fgUntie("/consumables/fuel/tank[0]/level-gal_us");
101 // fgUntie("/consumables/fuel/tank[1]/level-gal_us");
104 for(int i=0; i<_fdm->getAirplane()->getModel()->numThrusters(); i++) {
105 sprintf(buf, "/engines/engine[%d]/fuel-flow-gph", i); fgUntie(buf);
106 sprintf(buf, "/engines/engine[%d]/rpm", i); fgUntie(buf);
107 sprintf(buf, "/engines/engine[%d]/mp-osi", i); fgUntie(buf);
108 sprintf(buf, "/engines/engine[%d]/egt-degf", i); fgUntie(buf);
109 sprintf(buf, "/engines/engine[%d]/oil-temperature-degf", i); fgUntie(buf);
115 Airplane* a = _fdm->getAirplane();
116 Model* m = a->getModel();
121 m->setCrashed(false);
123 // Figure out the initial speed type
124 string speed_set = fgGetString("/sim/presets/speed-set", "UVW");
125 if (speed_set == "NED")
127 else if (speed_set == "UVW")
129 else if (speed_set == "knots")
131 else if (speed_set == "mach")
135 SG_LOG(SG_FLIGHT, SG_ALERT, "Unknown speed type " << speed_set);
138 // Build a filename and parse it
139 SGPath f(fgGetString("/sim/aircraft-dir"));
140 f.append(fgGetString("/sim/aero"));
142 readXML(f.str(), *_fdm);
144 // Compile it into a real airplane, and tell the user what they got
150 // Create some FG{Eng|Gear}Interface objects
152 for(i=0; i<a->numGear(); i++) {
153 Gear* g = a->getGear(i);
154 SGPropertyNode * node = fgGetNode("gear/gear", i, true);
157 node->setDoubleValue("xoffset-in", pos[0] * M2FT * 12);
158 node->setDoubleValue("yoffset-in", pos[1] * M2FT * 12);
159 node->setDoubleValue("zoffset-in", pos[2] * M2FT * 12);
162 // Are we at ground level? If so, lift the plane up so the gear
164 double runway_altitude = get_Runway_altitude();
165 if(get_Altitude() - runway_altitude < 50) {
166 fgSetBool("/controls/gear/gear-down", false);
167 float minGearZ = 1e18;
168 for(i=0; i<a->numGear(); i++) {
169 Gear* g = a->getGear(i);
172 if(pos[2] < minGearZ)
175 _set_Altitude(runway_altitude - minGearZ*M2FT);
176 fgSetBool("/controls/gear/gear-down", true);
179 // Blank the state, and copy in ours
184 _fdm->getExternalInput();
185 _fdm->getAirplane()->initEngines();
190 void YASim::update(double dt)
195 int iterations = _calc_multiloop(dt);
197 // If we're crashed, then we don't care
198 if(fgGetBool("/sim/crashed") || _fdm->getAirplane()->getModel()->isCrashed()) {
199 if(!fgGetBool("/sim/crashed"))
200 fgSetBool("/sim/crashed", true);
201 _fdm->getAirplane()->getModel()->setCrashed(false);
205 // ground. Calculate a cartesian coordinate for the ground under
206 // us, find the (geodetic) up vector normal to the ground, then
207 // use that to find the final (radius) term of the plane equation.
208 float v[3] = { get_uBody(), get_vBody(), get_wBody() };
209 float lat = get_Latitude(); float lon = get_Longitude();
210 float alt = get_Altitude() * FT2M; double xyz[3];
211 sgGeodToCart(lat, lon, alt, xyz);
212 // build the environment cache.
213 float vr = _fdm->getVehicleRadius();
214 vr += 2.0*FT2M*dt*Math::mag3(v);
215 prepare_ground_cache_m( _simTime, _simTime + dt, xyz, vr );
217 // Track time increments.
219 = (FGGround*)_fdm->getAirplane()->getModel()->getGroundCallback();
222 for(i=0; i<iterations; i++) {
223 gr->setTimeOffset(_simTime + i*_dt);
229 // Increment the local sim time
231 gr->setTimeOffset(_simTime);
234 void YASim::copyToYASim(bool copyState)
237 double lat = get_Latitude();
238 double lon = get_Longitude();
239 float alt = get_Altitude() * FT2M;
240 float roll = get_Phi();
241 float pitch = get_Theta();
242 float hdg = get_Psi();
246 wind[0] = get_V_north_airmass() * FT2M * -1.0;
247 wind[1] = get_V_east_airmass() * FT2M * -1.0;
248 wind[2] = get_V_down_airmass() * FT2M * -1.0;
250 float pressure = fgGetFloat("/environment/pressure-inhg") * INHG2PA;
251 float temp = fgGetFloat("/environment/temperature-degc") + 273.15;
252 float dens = fgGetFloat("/environment/density-slugft3")
253 * SLUG2KG * M2FT*M2FT*M2FT;
256 Model* model = _fdm->getAirplane()->getModel();
259 Glue::xyz2nedMat(lat, lon, xyz2ned);
262 sgGeodToCart(lat, lon, alt, s.pos);
264 // allow setting of /position/[lat|long|alti]tude
265 double * dp = &model->getState()->pos[0];
266 dp[0] = s.pos[0]; dp[1] = s.pos[1]; dp[2] = s.pos[2];
270 Glue::euler2orient(roll, pitch, hdg, s.orient);
271 Math::mmul33(s.orient, xyz2ned, s.orient);
274 string speed_set = fgGetString("/sim/presets/speed-set", "UVW");
276 bool needCopy = false;
277 switch (_speed_set) {
279 v[0] = get_V_north() * FT2M * -1.0;
280 v[1] = get_V_east() * FT2M * -1.0;
281 v[2] = get_V_down() * FT2M * -1.0;
284 v[0] = get_uBody() * FT2M;
285 v[1] = get_vBody() * FT2M;
286 v[2] = get_wBody() * FT2M;
287 Math::tmul33(s.orient, v, v);
290 v[0] = Atmosphere::spdFromVCAS(get_V_calibrated_kts()/MPS2KTS,
294 Math::tmul33(s.orient, v, v);
298 v[0] = Atmosphere::spdFromMach(get_Mach_number(), temp);
301 Math::tmul33(s.orient, v, v);
311 _speed_set = UVW; // change to this after initial setting
314 if(copyState || needCopy)
318 Math::tmul33(xyz2ned, wind, wind);
319 model->setWind(wind);
322 model->setAir(pressure, temp, dens);
324 // Query a ground plane for each gear/hook/launchbar and
325 // write that value into the corresponding class.
326 _fdm->getAirplane()->getModel()->updateGround(&s);
328 Launchbar* l = model->getLaunchbar();
330 l->setLaunchCmd(0.0<fgGetFloat("/controls/gear/catapult-launch-cmd"));
333 // All the settables:
335 // These are set below:
338 // _set_Accels_CG_Body
339 // _set_Accels_Pilot_Body
340 // _set_Accels_CG_Body_N
341 // _set_Velocities_Local
342 // _set_Velocities_Ground
343 // _set_Velocities_Wind_Body
348 // _set_V_ground_speed
350 // _set_V_calibrated_kts
358 // _set_Geodetic_Position
359 // _set_Runway_altitude
361 // Ignoring these, because they're unused:
362 // _set_Geocentric_Position
363 // _set_Geocentric_Rates
366 // _set_Earth_position_angle (WTF?)
367 // _set_Gamma_vert_rad
369 // _set_T_Local_to_Body
371 // _set_Sea_Level_Radius
373 // Externally set via the weather code:
374 // _set_Velocities_Local_Airmass
376 // _set_Static_pressure
377 // _set_Static_temperature
378 void YASim::copyFromYASim()
380 Airplane* airplane = _fdm->getAirplane();
381 Model* model = airplane->getModel();
382 State* s = model->getState();
385 double lat, lon, alt;
386 sgCartToGeod(s->pos, &lat, &lon, &alt);
387 _set_Geodetic_Position(lat, lon, alt*M2FT);
388 double groundlevel_m = get_groundlevel_m(lat, lon, alt);
389 _set_Runway_altitude(groundlevel_m*SG_METER_TO_FEET);
390 _set_Altitude_AGL((alt-groundlevel_m)*SG_METER_TO_FEET);
392 // the smallest agl of all gears
393 fgSetFloat("/position/gear-agl-m", model->getAGL());
394 fgSetFloat("/position/gear-agl-ft", model->getAGL()*M2FT);
397 //_set_Geocentric_Position(Glue::geod2geocLat(lat), lon, alt*M2FT);
399 // useful conversion matrix
401 Glue::xyz2nedMat(lat, lon, xyz2ned);
405 Math::vmul33(xyz2ned, s->v, v);
406 _set_Velocities_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
407 _set_V_ground_speed(Math::sqrt(M2FT*v[0]*M2FT*v[0] +
408 M2FT*v[1]*M2FT*v[1]));
409 _set_Climb_Rate(-M2FT*v[2]);
411 // The HUD uses this, but inverts down (?!)
412 _set_Velocities_Ground(M2FT*v[0], M2FT*v[1], -M2FT*v[2]);
414 // _set_Geocentric_Rates(M2FT*v[0], M2FT*v[1], M2FT*v[2]); // UNUSED
418 wind[0] = get_V_north_airmass() * FT2M * -1.0; // Wind in NED
419 wind[1] = get_V_east_airmass() * FT2M * -1.0;
420 wind[2] = get_V_down_airmass() * FT2M * -1.0;
421 Math::tmul33(xyz2ned, wind, wind); // Wind in global
422 Math::sub3(s->v, wind, v); // V - wind in global
423 Math::vmul33(s->orient, v, v); // to body coordinates
424 _set_Velocities_Wind_Body(v[0]*M2FT, -v[1]*M2FT, -v[2]*M2FT);
425 _set_V_rel_wind(Math::mag3(v)*M2FT); // units?
427 float P = fgGetDouble("/environment/pressure-inhg") * INHG2PA;
428 float T = fgGetDouble("/environment/temperature-degc") + 273.15;
429 float D = fgGetFloat("/environment/density-slugft3")
430 *SLUG2KG * M2FT*M2FT*M2FT;
431 _set_V_equiv_kts(Atmosphere::calcVEAS(v[0], P, T, D)*MPS2KTS);
432 _set_V_calibrated_kts(Atmosphere::calcVCAS(v[0], P, T)*MPS2KTS);
433 _set_Mach_number(Atmosphere::calcMach(v[0], T));
436 Math::vmul33(xyz2ned, s->acc, v);
437 _set_Accels_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
439 Math::vmul33(s->orient, s->acc, v);
440 _set_Accels_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
441 _set_Accels_CG_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
443 _fdm->getAirplane()->getPilotAccel(v);
444 _set_Accels_Pilot_Body(-M2FT*v[0], M2FT*v[1], M2FT*v[2]);
446 // There is no property for pilot G's, but I need it for a panel
447 // instrument. Hack this in here, and REMOVE IT WHEN IT FINDS A
449 fgSetFloat("/accelerations/pilot-g", -v[2]/9.8);
451 // The one appears (!) to want inverted pilot acceleration
452 // numbers, in G's...
453 Math::mul3(1.0/9.8, v, v);
454 _set_Accels_CG_Body_N(v[0], -v[1], -v[2]);
458 Glue::calcAlphaBeta(s, wind, &alpha, &beta);
463 Math::trans33(xyz2ned, tmp);
464 Math::mmul33(s->orient, tmp, tmp);
465 float roll, pitch, hdg;
466 Glue::orient2euler(tmp, &roll, &pitch, &hdg);
467 // make heading positive value
468 if(hdg < 0.0) hdg += PI2;
469 _set_Euler_Angles(roll, pitch, hdg);
472 Math::vmul33(s->orient, s->rot, v);
473 _set_Omega_Body(v[0], -v[1], -v[2]);
475 Glue::calcEulerRates(s, &roll, &pitch, &hdg);
476 _set_Euler_Rates(roll, pitch, hdg);
478 // Fill out our engine and gear objects
480 for(i=0; i<airplane->numGear(); i++) {
481 Gear* g = airplane->getGear(i);
482 SGPropertyNode * node = fgGetNode("gear/gear", i, true);
483 node->setBoolValue("has-brake", g->getBrake() != 0);
484 node->setBoolValue("wow", g->getCompressFraction() != 0);
485 node->setFloatValue("compression-norm", g->getCompressFraction());
486 node->setFloatValue("compression-m", g->getCompressDist());
487 node->setFloatValue("caster-angle-deg", g->getCasterAngle() * RAD2DEG);
488 node->setFloatValue("rollspeed-ms", g->getRollSpeed());
489 node->setBoolValue("ground-is-solid", g->getGroundIsSolid()!=0);
490 node->setFloatValue("ground-friction-factor", g->getGroundFrictionFactor());
493 Hook* h = airplane->getHook();
495 SGPropertyNode * node = fgGetNode("gear/tailhook", 0, true);
496 node->setFloatValue("position-norm", h->getCompressFraction());
499 Launchbar* l = airplane->getLaunchbar();
501 SGPropertyNode * node = fgGetNode("gear/launchbar", 0, true);
502 node->setFloatValue("position-norm", l->getCompressFraction());
503 node->setFloatValue("holdback-position-norm", l->getHoldbackCompressFraction());
504 node->setStringValue("state", l->getState());
505 node->setBoolValue("strop", l->getStrop());
511 * This is only used after a replay session and when the user requested to resume at
512 * a past point of time. In thise case the FDM must reload all values from the property
513 * tree (as given by the replay system). */
516 // Process inputs. Use excessive value for dt to make sure all transition effects
517 // have reached their final state (i.e. gear is extended/retracted) - which is vital
518 // for many properties to be complete before the first FDM run (otherwise the gear may
519 // still be up, thrust-reversers/speed-brakes/... may still be partially deployed...).
520 _fdm->getExternalInput(1000);
522 // get current FDM values from the property tree