]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/YASim.cxx
YASim airborne start-up
[flightgear.git] / src / FDM / YASim / YASim.cxx
1
2 #ifdef HAVE_CONFIG_H
3 #  include "config.h"
4 #endif
5
6 #include <cstdlib>
7
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>
13
14 #include <Main/globals.hxx>
15 #include <Main/fg_props.hxx>
16
17 #include "FGFDM.hpp"
18 #include "Atmosphere.hpp"
19 #include "Math.hpp"
20 #include "Airplane.hpp"
21 #include "Model.hpp"
22 #include "Integrator.hpp"
23 #include "Glue.hpp"
24 #include "Gear.hpp"
25 #include "Hook.hpp"
26 #include "Launchbar.hpp"
27 #include "FGGround.hpp"
28 #include "PropEngine.hpp"
29 #include "PistonEngine.hpp"
30
31 #include "YASim.hxx"
32
33 using namespace yasim;
34
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;
47
48 YASim::YASim(double dt) :
49     _simTime(0)
50 {
51 //     set_delta_t(dt);
52     _fdm = new FGFDM();
53
54     _dt = dt;
55
56     _fdm->getAirplane()->getModel()->setGroundCallback( new FGGround(this) );
57     _fdm->getAirplane()->getModel()->getIntegrator()->setInterval(_dt);
58 }
59
60 YASim::~YASim()
61 {
62     delete _fdm;
63
64     _gearProps.clear();
65 }
66
67 void YASim::report()
68 {
69     Airplane* a = _fdm->getAirplane();
70
71     float aoa = a->getCruiseAoA() * RAD2DEG;
72     float tail = -1 * a->getTailIncidence() * RAD2DEG;
73     float drag = 1000 * a->getDragCoefficient();
74
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());
82
83     float cg[3];
84     char buf[256];
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);
88
89     if(a->getFailureMsg()) {
90         SG_LOG(SG_FLIGHT, SG_ALERT, "YASim SOLUTION FAILURE:");
91         SG_LOG(SG_FLIGHT, SG_ALERT, a->getFailureMsg());
92         exit(1);
93     }
94 }
95
96 void YASim::bind()
97 {
98     // Run the superclass bind to set up a bunch of property ties
99     FGInterface::bind();
100
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");
105
106     char buf[256];
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);
113     }
114 }
115
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))
125 {
126 }
127
128 void YASim::init()
129 {
130     Airplane* airplane = _fdm->getAirplane();
131     Model* model = airplane->getModel();
132
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);
141
142     // Superclass hook
143     common_init();
144
145     model->setCrashed(false);
146     _crashed->setBoolValue(false);
147
148     // Figure out the initial speed type
149     string speed_set = _speed_setprop->getStringValue();
150     if ((speed_set == "") || (speed_set == "UVW"))
151         _speed_set = UVW;
152     else if (speed_set == "NED")
153         _speed_set = NED;
154     else if (speed_set == "knots")
155         _speed_set = KNOTS;
156     else if (speed_set == "mach")
157         _speed_set = MACH;
158     else {
159         _speed_set = UVW;
160         SG_LOG(SG_FLIGHT, SG_ALERT, "Unknown speed type " << speed_set);
161     }
162
163     // Build a filename and parse it
164     SGPath f(fgGetString("/sim/aircraft-dir"));
165     f.append(fgGetString("/sim/aero"));
166     f.concat(".xml");
167     try {
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());
173         throw e;
174     }
175
176     // Compile it into a real airplane, and tell the user what they got
177     airplane->compile();
178     report();
179
180     _fdm->init();
181
182     if (model->getLaunchbar())
183     {
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);
189     }
190     if (airplane->getHook())
191     {
192         _tailhook_position_norm = fgGetNode("/gear/tailhook/position-norm", 0, true);
193     }
194
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);
199         float pos[3];
200         g->getPosition(pos);
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);
204
205         _gearProps.push_back(GearProps(node));
206     }
207
208     // Are we at ground level?  If so, lift the plane up so the gear
209     // clear the ground.
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);
216             float pos[3];
217             g->getPosition(pos);
218             if(pos[2] < minGearZ)
219                 minGearZ = pos[2];
220         }
221         _set_Altitude(runway_altitude - minGearZ*M2FT);
222         // ground start-up: gear down
223         fgSetBool("/controls/gear/gear-down", true);
224     }
225     else
226     {
227         // airborne start-up: gear up
228         fgSetBool("/controls/gear/gear-down", false);
229     }
230
231     // Blank the state, and copy in ours
232     State s;
233     model->setState(&s);
234     copyToYASim(true);
235
236     _fdm->getExternalInput();
237     _fdm->getAirplane()->initEngines();
238
239     set_inited(true);
240 }
241
242 void YASim::update(double dt)
243 {
244     if (is_suspended())
245         return;
246
247     int iterations = _calc_multiloop(dt);
248
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);
254         return;
255     }
256
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 );
268
269     // Track time increments.
270     FGGround* gr
271       = (FGGround*)_fdm->getAirplane()->getModel()->getGroundCallback();
272
273     int i;
274     for(i=0; i<iterations; i++) {
275         gr->setTimeOffset(_simTime + i*_dt);
276         copyToYASim(false);
277         _fdm->iterate(_dt);
278         copyFromYASim();
279     }
280
281     // Increment the local sim time
282     _simTime += dt;
283     gr->setTimeOffset(_simTime);
284 }
285
286 void YASim::copyToYASim(bool copyState)
287 {
288     // Physical state
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();
295
296     // Environment
297     float wind[3];
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;
301
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;
306
307     // Convert and set:
308     Model* model = _fdm->getAirplane()->getModel();
309     State s;
310     float xyz2ned[9];
311     Glue::xyz2nedMat(lat, lon, xyz2ned);
312
313     // position
314     sgGeodToCart(lat, lon, alt, s.pos);
315     {
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];
319     }
320
321     // orientation
322     Glue::euler2orient(roll, pitch, hdg, s.orient);
323     Math::mmul33(s.orient, xyz2ned, s.orient);
324
325     // Velocity
326     float v[3];
327     bool needCopy = false;
328     switch (_speed_set) {
329     case NED:
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;
333         break;
334     case UVW:
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);
339         break;
340     case KNOTS:
341         v[0] = Atmosphere::spdFromVCAS(get_V_calibrated_kts()/MPS2KTS,
342                                        pressure, temp);
343         v[1] = 0;
344         v[2] = 0;
345         Math::tmul33(s.orient, v, v);
346         needCopy = true;
347         break;
348     case MACH:
349         v[0] = Atmosphere::spdFromMach(get_Mach_number(), temp);
350         v[1] = 0;
351         v[2] = 0;
352         Math::tmul33(s.orient, v, v);
353         needCopy = true;
354         break;
355     default:
356         v[0] = 0;
357         v[1] = 0;
358         v[2] = 0;
359         break;
360     }
361     if (!copyState)
362         _speed_set = UVW;       // change to this after initial setting
363     Math::set3(v, s.v);
364
365     if(copyState || needCopy)
366         model->setState(&s);
367
368     // wind
369     Math::tmul33(xyz2ned, wind, wind);
370     model->setWind(wind);
371
372     // air
373     model->setAir(pressure, temp, dens);
374
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);
378
379     Launchbar* l = model->getLaunchbar();
380     if (l)
381         l->setLaunchCmd(0.0 < _catapult_launch_cmd->getFloatValue());
382 }
383
384 // All the settables:
385 //
386 // These are set below:
387 // _set_Accels_Local
388 // _set_Accels_Body
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
395 // _set_Omega_Body
396 // _set_Euler_Rates
397 // _set_Euler_Angles
398 // _set_V_rel_wind
399 // _set_V_ground_speed
400 // _set_V_equiv_kts
401 // _set_V_calibrated_kts
402 // _set_Alpha
403 // _set_Beta
404 // _set_Mach_number
405 // _set_Climb_Rate
406 // _set_Tank1Fuel
407 // _set_Tank2Fuel
408 // _set_Altitude_AGL
409 // _set_Geodetic_Position
410 // _set_Runway_altitude
411
412 // Ignoring these, because they're unused:
413 // _set_Geocentric_Position
414 // _set_Geocentric_Rates
415 // _set_Cos_phi
416 // _set_Cos_theta
417 // _set_Earth_position_angle (WTF?)
418 // _set_Gamma_vert_rad
419 // _set_Inertias
420 // _set_T_Local_to_Body
421 // _set_CG_Position
422 // _set_Sea_Level_Radius
423
424 // Externally set via the weather code:
425 // _set_Velocities_Local_Airmass
426 // _set_Density
427 // _set_Static_pressure
428 // _set_Static_temperature
429 void YASim::copyFromYASim()
430 {
431     Airplane* airplane = _fdm->getAirplane();
432     Model* model = airplane->getModel();
433     State* s = model->getState();
434
435     // position
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);
442
443     // the smallest agl of all gears
444     _gear_agl_m->setFloatValue(model->getAGL());
445     _gear_agl_ft->setFloatValue(model->getAGL()*M2FT);
446
447     // UNUSED
448     //_set_Geocentric_Position(Glue::geod2geocLat(lat), lon, alt*M2FT);
449
450     // useful conversion matrix
451     float xyz2ned[9];
452     Glue::xyz2nedMat(lat, lon, xyz2ned);
453
454     // velocity
455     float v[3];
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]);
461
462     // The HUD uses this, but inverts down (?!)
463     _set_Velocities_Ground(M2FT*v[0], M2FT*v[1], -M2FT*v[2]);
464
465     // _set_Geocentric_Rates(M2FT*v[0], M2FT*v[1], M2FT*v[2]); // UNUSED
466
467     // Airflow velocity.
468     float wind[3];
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?
477
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));
485
486     // acceleration
487     Math::vmul33(xyz2ned, s->acc, v);
488     _set_Accels_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
489
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]);
493
494     _fdm->getAirplane()->getPilotAccel(v);
495     _set_Accels_Pilot_Body(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
496
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
499     // REAL HOME!
500     _pilot_g->setFloatValue(-v[2]/9.8);
501
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]);
506
507     // orientation
508     float alpha, beta;
509     Glue::calcAlphaBeta(s, wind, &alpha, &beta);
510     _set_Alpha(alpha);
511     _set_Beta(beta);
512
513     float tmp[9];
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);
521
522     // rotation
523     Math::vmul33(s->orient, s->rot, v);
524     _set_Omega_Body(v[0], -v[1], -v[2]);
525
526     Glue::calcEulerRates(s, &roll, &pitch, &hdg);
527     _set_Euler_Rates(roll, pitch, hdg);
528
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(
534                 g->getBrake() != 0);
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(
544                 g->getRollSpeed());
545         gearProps.ground_is_solid->setBoolValue(
546                 g->getGroundIsSolid()!=0);
547         gearProps.ground_friction_factor->setFloatValue(
548                 g->getGroundFrictionFactor());
549     }
550
551     Hook* h = airplane->getHook();
552     if(h) {
553         _tailhook_position_norm->setFloatValue(h->getCompressFraction());
554     }
555
556     Launchbar* l = airplane->getLaunchbar();
557     if(l) {
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());
562     }
563 }
564
565 /** Reinit the FDM.
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). */
569 void YASim::reinit()
570 {
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);
576
577     // get current FDM values from the property tree
578     copyToYASim(true);
579 }