]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/YASim.cxx
FGPUIDialog: fix reading from already free'd memory.
[flightgear.git] / src / FDM / YASim / YASim.cxx
1
2 #ifdef HAVE_CONFIG_H
3 #  include "config.h"
4 #endif
5
6 #include <cstdlib>
7 #include <cstdio>
8
9 #include <simgear/debug/logstream.hxx>
10 #include <simgear/math/sg_geodesy.hxx>
11 #include <simgear/misc/sg_path.hxx>
12 #include <simgear/scene/model/placement.hxx>
13 #include <simgear/xml/easyxml.hxx>
14
15 #include <Main/globals.hxx>
16 #include <Main/fg_props.hxx>
17
18 #include "FGFDM.hpp"
19 #include "Atmosphere.hpp"
20 #include "Math.hpp"
21 #include "Airplane.hpp"
22 #include "Model.hpp"
23 #include "Integrator.hpp"
24 #include "Glue.hpp"
25 #include "Gear.hpp"
26 #include "Hook.hpp"
27 #include "Launchbar.hpp"
28 #include "FGGround.hpp"
29 #include "PropEngine.hpp"
30 #include "PistonEngine.hpp"
31
32 #include "YASim.hxx"
33
34 using namespace yasim;
35 using std::string;
36
37 static const float YASIM_PI = 3.14159265358979323846;
38 static const float RAD2DEG = 180/YASIM_PI;
39 static const float PI2 = YASIM_PI*2;
40 static const float RAD2RPM = 9.54929658551;
41 static const float M2FT = 3.2808399;
42 static const float FT2M = 0.3048;
43 static const float MPS2KTS = 3600.0/1852.0;
44 static const float CM2GALS = 264.172037284; // gallons/cubic meter
45 static const float KG2LBS = 2.20462262185;
46 static const float W2HP = 1.3416e-3;
47 static const float INHG2PA = 3386.389;
48 static const float SLUG2KG = 14.59390;
49
50 YASim::YASim(double dt) :
51     _simTime(0)
52 {
53 //     set_delta_t(dt);
54     _fdm = new FGFDM();
55
56     _dt = dt;
57
58     _fdm->getAirplane()->getModel()->setGroundCallback( new FGGround(this) );
59     _fdm->getAirplane()->getModel()->getIntegrator()->setInterval(_dt);
60 }
61
62 YASim::~YASim()
63 {
64     delete _fdm;
65
66     _gearProps.clear();
67 }
68
69 void YASim::report()
70 {
71     Airplane* a = _fdm->getAirplane();
72
73     float aoa = a->getCruiseAoA() * RAD2DEG;
74     float tail = -1 * a->getTailIncidence() * RAD2DEG;
75     float drag = 1000 * a->getDragCoefficient();
76
77     SG_LOG(SG_FLIGHT,SG_INFO,"YASim solution results:");
78     SG_LOG(SG_FLIGHT,SG_INFO,"       Iterations: "<<a->getSolutionIterations());
79     SG_LOG(SG_FLIGHT,SG_INFO," Drag Coefficient: "<< drag);
80     SG_LOG(SG_FLIGHT,SG_INFO,"       Lift Ratio: "<<a->getLiftRatio());
81     SG_LOG(SG_FLIGHT,SG_INFO,"       Cruise AoA: "<< aoa);
82     SG_LOG(SG_FLIGHT,SG_INFO,"   Tail Incidence: "<< tail);
83     SG_LOG(SG_FLIGHT,SG_INFO,"Approach Elevator: "<<a->getApproachElevator());
84
85     float cg[3];
86     char buf[256];
87     a->getModel()->getBody()->getCG(cg);
88     sprintf(buf, "            CG: %.3f, %.3f, %.3f", cg[0], cg[1], cg[2]);
89     SG_LOG(SG_FLIGHT, SG_INFO, buf);
90
91     if(a->getFailureMsg()) {
92         SG_LOG(SG_FLIGHT, SG_ALERT, "YASim SOLUTION FAILURE:");
93         SG_LOG(SG_FLIGHT, SG_ALERT, a->getFailureMsg());
94         exit(1);
95     }
96 }
97
98 void YASim::bind()
99 {
100     // Run the superclass bind to set up a bunch of property ties
101     FGInterface::bind();
102
103 //Torsten Dreyer: we shouldn't do this anymore because we don't set these values nomore
104     // Now UNtie the ones that we are going to set ourselves.
105 //    fgUntie("/consumables/fuel/tank[0]/level-gal_us");
106 //    fgUntie("/consumables/fuel/tank[1]/level-gal_us");
107
108     char buf[256];
109     for(int i=0; i<_fdm->getAirplane()->getModel()->numThrusters(); i++) {
110         sprintf(buf, "/engines/engine[%d]/fuel-flow-gph", i);        fgUntie(buf);
111         sprintf(buf, "/engines/engine[%d]/rpm", i);                  fgUntie(buf);
112         sprintf(buf, "/engines/engine[%d]/mp-osi", i);               fgUntie(buf);
113         sprintf(buf, "/engines/engine[%d]/egt-degf", i);             fgUntie(buf);
114         sprintf(buf, "/engines/engine[%d]/oil-temperature-degf", i); fgUntie(buf);
115     }
116 }
117
118 YASim::GearProps::GearProps(SGPropertyNode_ptr gear_root) :
119     has_brake(gear_root->getNode("has-brake", true)),
120     wow(gear_root->getNode("wow", true)),
121     compression_norm(gear_root->getNode("compression-norm", true)),
122     compression_m(gear_root->getNode("compression-m", true)),
123     caster_angle_deg(gear_root->getNode("caster-angle-deg", true)),
124     rollspeed_ms(gear_root->getNode("rollspeed-ms", true)),
125     ground_is_solid(gear_root->getNode("ground-is-solid", true)),
126     ground_friction_factor(gear_root->getNode("ground-friction-factor", true))
127 {
128 }
129
130 void YASim::init()
131 {
132     Airplane* airplane = _fdm->getAirplane();
133     Model* model = airplane->getModel();
134
135     _crashed         = fgGetNode("/sim/crashed", true);
136     _pressure_inhg   = fgGetNode("/environment/pressure-inhg", true);
137     _temp_degc       = fgGetNode("/environment/temperature-degc", true);
138     _density_slugft3 = fgGetNode("/environment/density-slugft3", true);
139     _gear_agl_m      = fgGetNode("/position/gear-agl-m", true);
140     _gear_agl_ft     = fgGetNode("/position/gear-agl-ft", true);
141     _pilot_g         = fgGetNode("/accelerations/pilot-g", true);
142     _speed_setprop   = fgGetNode("/sim/presets/speed-set", true);
143
144     // Superclass hook
145     common_init();
146
147     model->setCrashed(false);
148     _crashed->setBoolValue(false);
149
150     // Figure out the initial speed type
151     string speed_set = _speed_setprop->getStringValue();
152     if ((speed_set == "") || (speed_set == "UVW"))
153         _speed_set = UVW;
154     else if (speed_set == "NED")
155         _speed_set = NED;
156     else if (speed_set == "knots")
157         _speed_set = KNOTS;
158     else if (speed_set == "mach")
159         _speed_set = MACH;
160     else {
161         _speed_set = UVW;
162         SG_LOG(SG_FLIGHT, SG_ALERT, "Unknown speed type " << speed_set);
163     }
164
165     // Build a filename and parse it
166     SGPath f(fgGetString("/sim/aircraft-dir"));
167     f.append(fgGetString("/sim/aero"));
168     f.concat(".xml");
169     try {
170         readXML(f.str(), *_fdm);
171     } catch (const sg_exception &e) {
172         SG_LOG(SG_FLIGHT, SG_ALERT,
173                "Error reading YASim FDM: '" << f.str() << "'" << std::endl
174                << e.getFormattedMessage());
175         throw e;
176     }
177
178     // Compile it into a real airplane, and tell the user what they got
179     airplane->compile();
180     report();
181
182     _fdm->init();
183
184     if (model->getLaunchbar())
185     {
186         _catapult_launch_cmd         = fgGetNode("/controls/gear/catapult-launch-cmd", true);
187         _launchbar_position_norm     = fgGetNode("/gear/launchbar/position-norm", true);
188         _launchbar_holdback_pos_norm = fgGetNode("/gear/launchbar/holdback-position-norm", true);
189         _launchbar_state             = fgGetNode("/gear/launchbar/state", true);
190         _launchbar_strop             = fgGetNode("/gear/launchbar/strop", true);
191     }
192     if (airplane->getHook())
193     {
194         _tailhook_position_norm = fgGetNode("/gear/tailhook/position-norm", 0, true);
195     }
196
197     // Create some FG{Eng|Gear}Interface objects
198     for(int i=0; i<airplane->numGear(); i++) {
199         Gear* g = airplane->getGear(i);
200         SGPropertyNode * node = fgGetNode("gear/gear", i, true);
201         float pos[3];
202         g->getPosition(pos);
203         node->setDoubleValue("xoffset-in", pos[0] * M2FT * 12);
204         node->setDoubleValue("yoffset-in", pos[1] * M2FT * 12);
205         node->setDoubleValue("zoffset-in", pos[2] * M2FT * 12);
206
207         _gearProps.push_back(GearProps(node));
208     }
209
210     // Are we at ground level?  If so, lift the plane up so the gear
211     // clear the ground.
212     double runway_altitude = get_Runway_altitude();
213     if(get_Altitude() - runway_altitude < 50) {
214         fgSetBool("/controls/gear/gear-down", false);
215         float minGearZ = 1e18;
216         for(int i=0; i<airplane->numGear(); i++) {
217             Gear* g = airplane->getGear(i);
218             float pos[3];
219             g->getPosition(pos);
220             if(pos[2] < minGearZ)
221                 minGearZ = pos[2];
222         }
223         _set_Altitude(runway_altitude - minGearZ*M2FT);
224         // ground start-up: gear down
225         fgSetBool("/controls/gear/gear-down", true);
226     }
227     else
228     {
229         // airborne start-up: gear up
230         fgSetBool("/controls/gear/gear-down", false);
231     }
232
233     // Blank the state, and copy in ours
234     State s;
235     model->setState(&s);
236     copyToYASim(true);
237
238     _fdm->getExternalInput();
239     _fdm->getAirplane()->initEngines();
240
241     set_inited(true);
242 }
243
244 void YASim::update(double dt)
245 {
246     if (is_suspended())
247         return;
248
249     int iterations = _calc_multiloop(dt);
250
251     // If we're crashed, then we don't care
252     if(_crashed->getBoolValue() || _fdm->getAirplane()->getModel()->isCrashed()) {
253         if(!_crashed->getBoolValue())
254             _crashed->setBoolValue(true);
255         _fdm->getAirplane()->getModel()->setCrashed(false);
256         return;
257     }
258
259     // ground.  Calculate a cartesian coordinate for the ground under
260     // us, find the (geodetic) up vector normal to the ground, then
261     // use that to find the final (radius) term of the plane equation.
262     float v[3] = {
263       static_cast<float>(get_uBody()),
264       static_cast<float>(get_vBody()),
265       static_cast<float>(get_wBody())
266     };
267     float lat = get_Latitude(); float lon = get_Longitude();
268     float alt = get_Altitude() * FT2M; double xyz[3];
269     sgGeodToCart(lat, lon, alt, xyz);
270     // build the environment cache.
271     float vr = _fdm->getVehicleRadius();
272     vr += 2.0*FT2M*dt*Math::mag3(v);
273     prepare_ground_cache_m( _simTime, _simTime + dt, xyz, vr );
274
275     // Track time increments.
276     FGGround* gr
277       = (FGGround*)_fdm->getAirplane()->getModel()->getGroundCallback();
278
279     int i;
280     for(i=0; i<iterations; i++) {
281         gr->setTimeOffset(_simTime + i*_dt);
282         copyToYASim(false);
283         _fdm->iterate(_dt);
284         copyFromYASim();
285     }
286
287     // Increment the local sim time
288     _simTime += dt;
289     gr->setTimeOffset(_simTime);
290 }
291
292 void YASim::copyToYASim(bool copyState)
293 {
294     // Physical state
295     double lat = get_Latitude();
296     double lon = get_Longitude();
297     float alt = get_Altitude() * FT2M;
298     float roll = get_Phi();
299     float pitch = get_Theta();
300     float hdg = get_Psi();
301
302     // Environment
303     float wind[3];
304     wind[0] = get_V_north_airmass() * FT2M * -1.0;
305     wind[1] = get_V_east_airmass() * FT2M * -1.0;
306     wind[2] = get_V_down_airmass() * FT2M * -1.0;
307
308     float pressure = _pressure_inhg->getFloatValue() * INHG2PA;
309     float temp     = _temp_degc->getFloatValue() + 273.15;
310     float dens     = _density_slugft3->getFloatValue() *
311                             SLUG2KG * M2FT*M2FT*M2FT;
312
313     // Convert and set:
314     Model* model = _fdm->getAirplane()->getModel();
315     State s;
316     float xyz2ned[9];
317     Glue::xyz2nedMat(lat, lon, xyz2ned);
318
319     // position
320     sgGeodToCart(lat, lon, alt, s.pos);
321     {
322       // allow setting of /position/[lat|long|alti]tude
323       double * dp = &model->getState()->pos[0];
324       dp[0] = s.pos[0]; dp[1] = s.pos[1]; dp[2] = s.pos[2];
325     }
326
327     // orientation
328     Glue::euler2orient(roll, pitch, hdg, s.orient);
329     Math::mmul33(s.orient, xyz2ned, s.orient);
330
331     // Velocity
332     float v[3];
333     bool needCopy = false;
334     switch (_speed_set) {
335     case NED:
336         v[0] = get_V_north() * FT2M * -1.0;
337         v[1] = get_V_east() * FT2M * -1.0;
338         v[2] = get_V_down() * FT2M * -1.0;
339         break;
340     case UVW:
341         v[0] = get_uBody() * FT2M;
342         v[1] = get_vBody() * FT2M;
343         v[2] = get_wBody() * FT2M;
344         Math::tmul33(s.orient, v, v);
345         break;
346     case KNOTS:
347         v[0] = Atmosphere::spdFromVCAS(get_V_calibrated_kts()/MPS2KTS,
348                                        pressure, temp);
349         v[1] = 0;
350         v[2] = 0;
351         Math::tmul33(s.orient, v, v);
352         needCopy = true;
353         break;
354     case MACH:
355         v[0] = Atmosphere::spdFromMach(get_Mach_number(), temp);
356         v[1] = 0;
357         v[2] = 0;
358         Math::tmul33(s.orient, v, v);
359         needCopy = true;
360         break;
361     default:
362         v[0] = 0;
363         v[1] = 0;
364         v[2] = 0;
365         break;
366     }
367     if (!copyState)
368         _speed_set = UVW;       // change to this after initial setting
369     Math::set3(v, s.v);
370
371     if(copyState || needCopy)
372         model->setState(&s);
373
374     // wind
375     Math::tmul33(xyz2ned, wind, wind);
376     model->setWind(wind);
377
378     // air
379     model->setAir(pressure, temp, dens);
380
381     // Query a ground plane for each gear/hook/launchbar and
382     // write that value into the corresponding class.
383     _fdm->getAirplane()->getModel()->updateGround(&s);
384
385     Launchbar* l = model->getLaunchbar();
386     if (l)
387         l->setLaunchCmd(0.0 < _catapult_launch_cmd->getFloatValue());
388 }
389
390 // All the settables:
391 //
392 // These are set below:
393 // _set_Accels_Local
394 // _set_Accels_Body
395 // _set_Accels_CG_Body 
396 // _set_Accels_Pilot_Body
397 // _set_Accels_CG_Body_N 
398 // _set_Velocities_Local
399 // _set_Velocities_Ground
400 // _set_Velocities_Body
401 // _set_Omega_Body
402 // _set_Euler_Rates
403 // _set_Euler_Angles
404 // _set_V_rel_wind
405 // _set_V_ground_speed
406 // _set_V_equiv_kts
407 // _set_V_calibrated_kts
408 // _set_Alpha
409 // _set_Beta
410 // _set_Mach_number
411 // _set_Climb_Rate
412 // _set_Tank1Fuel
413 // _set_Tank2Fuel
414 // _set_Altitude_AGL
415 // _set_Geodetic_Position
416 // _set_Runway_altitude
417
418 // Ignoring these, because they're unused:
419 // _set_Geocentric_Position
420 // _set_Geocentric_Rates
421 // _set_Cos_phi
422 // _set_Cos_theta
423 // _set_Earth_position_angle (WTF?)
424 // _set_Gamma_vert_rad
425 // _set_Inertias
426 // _set_T_Local_to_Body
427 // _set_CG_Position
428 // _set_Sea_Level_Radius
429
430 // Externally set via the weather code:
431 // _set_Velocities_Local_Airmass
432 // _set_Density
433 // _set_Static_pressure
434 // _set_Static_temperature
435 void YASim::copyFromYASim()
436 {
437     Airplane* airplane = _fdm->getAirplane();
438     Model* model = airplane->getModel();
439     State* s = model->getState();
440
441     // position
442     double lat, lon, alt;
443     sgCartToGeod(s->pos, &lat, &lon, &alt);
444     _set_Geodetic_Position(lat, lon, alt*M2FT);
445     double groundlevel_m = get_groundlevel_m(lat, lon, alt);
446     _set_Runway_altitude(groundlevel_m*SG_METER_TO_FEET);
447     _set_Altitude_AGL((alt-groundlevel_m)*SG_METER_TO_FEET);
448
449     // the smallest agl of all gears
450     _gear_agl_m->setFloatValue(model->getAGL());
451     _gear_agl_ft->setFloatValue(model->getAGL()*M2FT);
452
453     // UNUSED
454     //_set_Geocentric_Position(Glue::geod2geocLat(lat), lon, alt*M2FT);
455
456     // useful conversion matrix
457     float xyz2ned[9];
458     Glue::xyz2nedMat(lat, lon, xyz2ned);
459
460     // velocity
461     float v[3];
462     Math::vmul33(xyz2ned, s->v, v);
463     _set_Velocities_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
464     _set_V_ground_speed(Math::sqrt(M2FT*v[0]*M2FT*v[0] +
465                                    M2FT*v[1]*M2FT*v[1]));
466     _set_Climb_Rate(-M2FT*v[2]);
467
468     // The HUD uses this, but inverts down (?!)
469     _set_Velocities_Ground(M2FT*v[0], M2FT*v[1], -M2FT*v[2]);
470
471     // _set_Geocentric_Rates(M2FT*v[0], M2FT*v[1], M2FT*v[2]); // UNUSED
472
473     // ecef speed in body axis
474     Math::vmul33(s->orient, s->v, v);
475     _set_Velocities_Body(v[0]*M2FT, -v[1]*M2FT, -v[2]*M2FT);
476
477     // Airflow velocity.
478     float wind[3];
479     wind[0] = get_V_north_airmass() * FT2M * -1.0;  // Wind in NED
480     wind[1] = get_V_east_airmass() * FT2M * -1.0;
481     wind[2] = get_V_down_airmass() * FT2M * -1.0;
482     Math::tmul33(xyz2ned, wind, wind);              // Wind in global
483     Math::sub3(s->v, wind, v);                      // V - wind in global
484     Math::vmul33(s->orient, v, v);               // to body coordinates
485     _set_V_rel_wind(Math::mag3(v)*M2FT); // units?
486
487     float P = _pressure_inhg->getFloatValue() * INHG2PA;
488     float T = _temp_degc->getFloatValue() + 273.15;
489     float D = _density_slugft3->getFloatValue()
490         *SLUG2KG * M2FT*M2FT*M2FT;
491     _set_V_equiv_kts(Atmosphere::calcVEAS(v[0], P, T, D)*MPS2KTS);
492     _set_V_calibrated_kts(Atmosphere::calcVCAS(v[0], P, T)*MPS2KTS);
493     _set_Mach_number(Atmosphere::calcMach(Math::mag3(v), T));
494
495     // acceleration
496     Math::vmul33(xyz2ned, s->acc, v);
497     _set_Accels_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
498
499     Math::vmul33(s->orient, s->acc, v);
500     _set_Accels_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
501     _set_Accels_CG_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
502
503     _fdm->getAirplane()->getPilotAccel(v);
504     _set_Accels_Pilot_Body(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
505
506     // There is no property for pilot G's, but I need it for a panel
507     // instrument.  Hack this in here, and REMOVE IT WHEN IT FINDS A
508     // REAL HOME!
509     _pilot_g->setFloatValue(-v[2]/9.8);
510
511     // The one appears (!) to want inverted pilot acceleration
512     // numbers, in G's...
513     Math::mul3(1.0/9.8, v, v);
514     _set_Accels_CG_Body_N(v[0], -v[1], -v[2]);
515
516     // orientation
517     float alpha, beta;
518     Glue::calcAlphaBeta(s, wind, &alpha, &beta);
519     _set_Alpha(alpha);
520     _set_Beta(-beta);
521
522     float tmp[9];
523     Math::trans33(xyz2ned, tmp);
524     Math::mmul33(s->orient, tmp, tmp);
525     float roll, pitch, hdg;
526     Glue::orient2euler(tmp, &roll, &pitch, &hdg);
527     // make heading positive value
528     if(hdg < 0.0) hdg += PI2;
529     _set_Euler_Angles(roll, pitch, hdg);
530
531     // rotation
532     Math::vmul33(s->orient, s->rot, v);
533     _set_Omega_Body(v[0], -v[1], -v[2]);
534
535     Glue::calcEulerRates(s, &roll, &pitch, &hdg);
536     _set_Euler_Rates(roll, pitch, hdg);
537
538     // Fill out our engine and gear objects
539     for(int i=0; i<airplane->numGear(); i++) {
540         Gear* g = airplane->getGear(i);
541         GearProps& gearProps = _gearProps[i];
542         gearProps.has_brake->setBoolValue(
543                 g->getBrake() != 0);
544         gearProps.wow->setBoolValue(
545                 g->getCompressFraction() != 0);
546         gearProps.compression_norm->setFloatValue(
547                 g->getCompressFraction());
548         gearProps.compression_m->setFloatValue(
549                 g->getCompressDist());
550         gearProps.caster_angle_deg->setFloatValue(
551                 g->getCasterAngle() * RAD2DEG);
552         gearProps.rollspeed_ms->setFloatValue(
553                 g->getRollSpeed());
554         gearProps.ground_is_solid->setBoolValue(
555                 g->getGroundIsSolid()!=0);
556         gearProps.ground_friction_factor->setFloatValue(
557                 g->getGroundFrictionFactor());
558     }
559
560     Hook* h = airplane->getHook();
561     if(h) {
562         _tailhook_position_norm->setFloatValue(h->getCompressFraction());
563     }
564
565     Launchbar* l = airplane->getLaunchbar();
566     if(l) {
567         _launchbar_position_norm->setFloatValue(l->getCompressFraction());
568         _launchbar_holdback_pos_norm->setFloatValue(l->getHoldbackCompressFraction());
569         _launchbar_state->setStringValue(l->getState());
570         _launchbar_strop->setBoolValue(l->getStrop());
571     }
572 }
573
574 /** Reinit the FDM.
575  * This is only used after a replay session and when the user requested to resume at
576  * a past point of time. In this case the FDM must reload all values from the property
577  * tree (as given by the replay system). */
578 void YASim::reinit()
579 {
580     // Process inputs. Use excessive value for dt to make sure all transition effects
581     // have reached their final state (i.e. gear is extended/retracted) - which is vital
582     // for many properties to be complete before the first FDM run (otherwise the gear may
583     // still be up, thrust-reversers/speed-brakes/... may still be partially deployed...).
584     _fdm->getExternalInput(1000);
585
586     // get current FDM values from the property tree
587     copyToYASim(true);
588 }